/**
 * <CompanyDetail /> — 업체 상세 컴포넌트 (재사용 가능)
 *
 * 사용법:
 *   <script type="text/babel" src="components/company-detail.jsx"></script>
 *   <CompanyDetail company={company} onClose={fn} mode="modal|page|panel" />
 *
 * 레이아웃 (1300px+ 데스크탑):
 *   [좌 사이드 ─ 320] [센터 ─ flex] [우 사이드 ─ 360]
 *
 *   좌: 주요 정보 · 배송 정보 · 단가/결제 · 회원 주문 시스템
 *   센터(상): 월간 주문 캘린더
 *   센터(하): 주문 목록
 *   우: 메뉴별 통계 · 결제 내역서 · 메모
 *
 * 외부 의존: window.OnbabUI ({ C, GroupBadge, PayBadge, MemberBadge, DetailRow })
 */

function CompanyDetail({company, onClose, mode='modal', orders, payments, memos}) {
  const {useState, useMemo} = React;
  if (!company || !window.OnbabUI) return null;
  const {C} = window.OnbabUI;

  // ── 데모 데이터 ───────────────────────────────────────
  const MEMO_CATS = {
    complaint:{label:'컴플레인',color:'#ef4444',bg:'#fef2f2'},
    request:  {label:'요청',    color:'#f59e0b',bg:'#fffbeb'},
    delivery: {label:'배송이슈',color:'#3b82f6',bg:'#eff6ff'},
    general:  {label:'일반',    color:'#64748b',bg:'#f1f5f9'},
  };
  const DEFAULT_MEMOS = memos || [];
  const DEFAULT_ORDERS = orders || [
    {date:'2026-05-19',menu:'도시락',qty:6,unit:8000,total:48000,pay:'미결',status:'확정'},
  ];
  const DEFAULT_PAYMENTS = payments || [];

  // 메뉴별 통계 (전체 기간)
  const MENU_STATS = [
    {key:'도', label:'도', bg:'#fef3c7', color:'#a16207',  미결:6, 미결액:48000, 대기:0, 결제:0, 전체:6, 전체액:48000, 평균:8000},
  ];

  // 캘린더 상태 표시: 미결(회색) / 대기(주황) / 완료(초록)
  const ORDER_DETAIL = {
    '2026-05-19':[{m:'도', q:6, status:'미결'}],
  };
  const HOLIDAYS = ['2026-05-25'];

  // ── 상태 ─────────────────────────────────────────────
  const [memoFilter, setMemoFilter] = useState('');
  const [memoList, setMemoList] = useState(DEFAULT_MEMOS);
  const [memoInput, setMemoInput] = useState('');
  const [memoType, setMemoType] = useState('complaint');
  const [memoUrgent, setMemoUrgent] = useState(false);
  const [editingInfo, setEditingInfo] = useState(false);
  const [companyForm, setCompanyForm] = useState(company);
  const [orderRange, setOrderRange] = useState('this');
  const [adminOrderMode, setAdminOrderMode] = useState(false);

  React.useEffect(() => { setCompanyForm(company); }, [company.seq]);
  const c = editingInfo ? companyForm : company;
  const filteredMemos = memoList.filter(m => !memoFilter || m.cat === memoFilter);

  // ── 캘린더 ───────────────────────────────────────────
  const calMonth = '2026-05';
  const firstDay = new Date(calMonth+'-01').getDay(); // 0=Sun
  const daysInMonth = new Date(2026, 5, 0).getDate(); // May=31
  const calCells = [];
  for (let i=0; i<firstDay; i++) calCells.push(null);
  for (let d=1; d<=daysInMonth; d++) calCells.push(d);
  while (calCells.length % 7 !== 0) calCells.push(null);

  // 통계 합계
  const monthOrders = Object.keys(ORDER_DETAIL).filter(k=>k.startsWith(calMonth));
  const monthOrderCount = monthOrders.length;
  const monthTotal = monthOrders.reduce((s,k)=>{
    return s + ORDER_DETAIL[k].reduce((ss,it)=>ss + it.q * 8000, 0);
  }, 0);

  // ── 공통 셀 컴포넌트들 ───────────────────────────────
  const SectionCard = ({icon, title, action, children, dense}) => (
    <div style={{background:'#fff', border:'1px solid #e2e8f0', borderRadius:10, marginBottom:10, overflow:'hidden'}}>
      <div style={{padding:dense?'8px 12px':'10px 14px', display:'flex', alignItems:'center', justifyContent:'space-between', borderBottom:'1px solid #f1f5f9', background:'#fafbfc'}}>
        <span style={{fontSize:13, fontWeight:700, color:'#0f172a', display:'flex', alignItems:'center', gap:6}}>
          {icon && <span style={{color:'#64748b'}}>{icon}</span>}{title}
        </span>
        {action}
      </div>
      <div style={{padding:dense?'8px 12px':'12px 14px'}}>{children}</div>
    </div>
  );

  const KV = ({label, value, half=false, valueStyle, action}) => (
    <div style={{flex:half?'1 1 calc(50% - 5px)':'1 1 100%', minWidth:0}}>
      <div style={{display:'flex',alignItems:'center',justifyContent:'space-between',marginBottom:3}}>
        <span style={{fontSize:10, color:'#94a3b8', fontWeight:600, letterSpacing:'0.2px'}}>{label}</span>
        {action}
      </div>
      <div style={{fontSize:13, color:'#0f172a', fontWeight:600, ...(valueStyle||{})}}>{value ?? <span style={{color:'#cbd5e1'}}>-</span>}</div>
    </div>
  );
  const KVRow = ({children, gap=10}) => <div style={{display:'flex', flexWrap:'wrap', gap, marginBottom:10}}>{children}</div>;

  // ── 좌측: 주요 정보 / 배송 / 단가·결제 / 회원 주문 ────
  const LeftCol = () => (<>
    <SectionCard icon="⌂" title="주요 정보" action={
      <button onClick={()=>setEditingInfo(!editingInfo)} style={{padding:'3px 9px', fontSize:11, color:editingInfo?'#fff':'#475569', background:editingInfo?C.primary:'#fff', border:`1px solid ${editingInfo?C.primary:'#e2e8f0'}`, borderRadius:5, cursor:'pointer', fontWeight:600}}>
        {editingInfo?'✓ 저장':'✎ 편집'}
      </button>
    } dense>
      <KVRow><KV label="업체명" value={<span style={{fontSize:14, fontWeight:800, color:'#0f172a'}}>{c.name}</span>}/></KVRow>
      <KVRow><KV label="연락처" value={c.phone||'010-2732-5001'} half/><KV label="업종" value={c.biz||'-'} half/></KVRow>
      <KVRow><KV label="휴무 요일" value="-"/></KVRow>
      <KVRow><KV label="주문 메모" value="-"/></KVRow>
      <KVRow><KV label="포장 메모" value="-"/></KVRow>
      <KVRow><KV label="계약 시작" value={c.startDate||'-'} half/><KV label="계약 종료" value={c.endDate||'-'} half/></KVRow>
      <div style={{marginTop:2}}><KV label="신규 종료" value={<span style={{fontSize:12, color:'#0f172a', fontWeight:600}}>2026-05-25</span>}/></div>
    </SectionCard>

    <SectionCard icon="🚚" title="배송 정보" dense>
      <KVRow><KV label="주소" value={c.addr||'대전 서구 계룡로 639'} half/><KV label="주소 상세" value={c.addrSub||'5층'} half/></KVRow>
      <KVRow><KV label="배송 시간" value={<span style={{fontSize:13, fontWeight:700, color:'#0f172a', fontVariantNumeric:'tabular-nums'}}>12:00</span>}/></KVRow>
      <KV label="특이사항" value={<div style={{minHeight:24, padding:'4px 8px', background:'#fafbfc', border:'1px dashed #e2e8f0', borderRadius:5, color:'#94a3b8', fontSize:11}}>-</div>}/>
    </SectionCard>

    <SectionCard icon="₩" title="단가 / 결제" dense>
      <div style={{marginBottom:10, padding:'10px 12px', background:'#fff7ed', border:'1px solid #fed7aa', borderRadius:6, display:'flex', alignItems:'center', justifyContent:'space-between'}}>
        <span style={{fontSize:10, color:'#9a3412', fontWeight:700, letterSpacing:'0.3px'}}>단가</span>
        <span style={{fontSize:18, fontWeight:800, color:'#9a3412', fontVariantNumeric:'tabular-nums'}}>{(c.unit||8000).toLocaleString()}<span style={{fontSize:11, fontWeight:600, marginLeft:2}}>원</span></span>
      </div>
      <KVRow><KV label="결제방법" value={<span style={{display:'inline-flex', padding:'2px 8px', fontSize:11, fontWeight:700, background:'#dbeafe', color:'#1e40af', borderRadius:3}}>카드</span>} half/>
        <KV label="결제주기" value={<span style={{fontSize:13, fontWeight:700}}>월간</span>} half/></KVRow>
      <KVRow><KV label="증빙" value={<span style={{fontSize:12, color:'#94a3b8'}}>미발행</span>} half/>
        <KV label="예금주" value="-" half/></KVRow>
      <KV label="계좌번호" value="-"/>
    </SectionCard>

    <SectionCard icon="👤" title="회원 주문 시스템" dense>
      <div style={{display:'flex', alignItems:'center', gap:10}}>
        <div onClick={()=>setAdminOrderMode(!adminOrderMode)} style={{width:18, height:18, borderRadius:'50%', border:`2px solid ${adminOrderMode?C.primary:'#cbd5e1'}`, background:adminOrderMode?C.primary:'#fff', cursor:'pointer', flexShrink:0, display:'flex', alignItems:'center', justifyContent:'center'}}>
          {adminOrderMode && <span style={{width:8, height:8, borderRadius:'50%', background:'#fff'}}/>}
        </div>
        <div style={{flex:1, minWidth:0}}>
          <div style={{fontSize:12, fontWeight:700, color:'#0f172a'}}>관리자 주문</div>
          <div style={{fontSize:10, color:'#94a3b8', marginTop:1}}>관리자가 주문을 대신 입력합니다</div>
        </div>
        <button style={{padding:'5px 10px', fontSize:11, fontWeight:700, color:'#475569', background:'#fff', border:'1px solid #e2e8f0', borderRadius:5, cursor:'pointer'}}>회원 주문 모드 전환</button>
      </div>
    </SectionCard>
  </>);

  // ── 캘린더 ───────────────────────────────────────────
  const STATUS_COLORS = {미결:'#94a3b8', 대기:'#f59e0b', 완료:'#16a34a'};
  const Calendar = () => (
    <div style={{background:'#fff', border:'1px solid #e2e8f0', borderRadius:10, overflow:'hidden'}}>
      <div style={{padding:'10px 14px', borderBottom:'1px solid #f1f5f9', display:'flex', alignItems:'center', justifyContent:'space-between'}}>
        <span style={{fontSize:14, fontWeight:800, color:'#0f172a'}}>2026년 5월 주문 캘린더</span>
        <div style={{display:'flex', gap:4}}>
          <button style={{width:24, height:24, border:'1px solid #e2e8f0', background:'#fff', borderRadius:5, cursor:'pointer', color:'#64748b', fontSize:12}}>‹</button>
          <button style={{width:24, height:24, border:'1px solid #e2e8f0', background:'#fff', borderRadius:5, cursor:'pointer', color:'#64748b', fontSize:12}}>›</button>
        </div>
      </div>
      <div style={{padding:'8px 10px'}}>
        <div style={{display:'grid', gridTemplateColumns:'repeat(7, 1fr)', gap:0, borderBottom:'1px solid #f1f5f9', marginBottom:4}}>
          {['일','월','화','수','목','금','토'].map((d,i)=>(
            <div key={d} style={{padding:'6px 0', textAlign:'center', fontSize:11, fontWeight:700, color: i===0?'#dc2626':i===6?'#2563eb':'#64748b'}}>{d}</div>
          ))}
        </div>
        <div style={{display:'grid', gridTemplateColumns:'repeat(7, 1fr)', gap:2}}>
          {calCells.map((d, idx)=>{
            if (!d) return <div key={idx}/>;
            const dateStr = `${calMonth}-${String(d).padStart(2,'0')}`;
            const detail = ORDER_DETAIL[dateStr];
            const dow = (firstDay + d - 1) % 7;
            const isHoliday = HOLIDAYS.includes(dateStr);
            const isToday = d === 19;
            const isSat = dow === 6;
            const isSun = dow === 0;
            const isWeekend = isSat || isSun || isHoliday;
            return (
              <div key={idx} style={{
                minHeight:62,
                padding:'5px 4px 4px',
                background: isWeekend?'#fef2f2':'#fff',
                border: isToday?`2px solid ${C.primary}`:'1px solid #f1f5f9',
                borderRadius:6,
                position:'relative',
                cursor:'pointer',
                overflow:'hidden',
              }}>
                <div style={{display:'flex', alignItems:'center', justifyContent:'space-between'}}>
                  <span style={{
                    fontSize:11, fontWeight:isToday?800:600,
                    color: isToday?C.primary : isSun||isHoliday?'#dc2626' : isSat?'#2563eb':'#475569',
                  }}>{d}</span>
                </div>
                {detail && detail.map((it,i)=>(
                  <div key={i} style={{display:'flex', alignItems:'center', gap:3, marginTop:3}}>
                    <span style={{
                      padding:'1px 4px', fontSize:9, fontWeight:800, borderRadius:2,
                      background:'#fef3c7', color:'#a16207',
                    }}>{it.m}</span>
                    <span style={{fontSize:10, fontWeight:700, color: STATUS_COLORS[it.status]||'#64748b'}}>{it.q}</span>
                  </div>
                ))}
              </div>
            );
          })}
        </div>
        {/* 범례 */}
        <div style={{display:'flex', justifyContent:'center', gap:14, marginTop:10, paddingTop:8, borderTop:'1px dashed #f1f5f9', fontSize:10, color:'#64748b'}}>
          <span style={{display:'flex', alignItems:'center', gap:4}}><span style={{width:7, height:7, borderRadius:'50%', background:'#94a3b8'}}/>미결</span>
          <span style={{display:'flex', alignItems:'center', gap:4}}><span style={{width:7, height:7, borderRadius:'50%', background:'#f59e0b'}}/>대기</span>
          <span style={{display:'flex', alignItems:'center', gap:4}}><span style={{width:7, height:7, borderRadius:'50%', background:'#16a34a'}}/>완료</span>
        </div>
        {/* 이달 합계 */}
        <div style={{display:'grid', gridTemplateColumns:'1fr 1fr', gap:10, marginTop:10, padding:'10px 12px', background:'#f0fdf4', border:'1px solid #bbf7d0', borderRadius:6}}>
          <div>
            <div style={{fontSize:10, color:'#15803d', fontWeight:700}}>이달 주문</div>
            <div style={{fontSize:16, fontWeight:800, color:'#0f172a', marginTop:2, fontVariantNumeric:'tabular-nums'}}>{monthOrderCount}<span style={{fontSize:11, fontWeight:600, marginLeft:2, color:'#15803d'}}>건</span></div>
          </div>
          <div style={{textAlign:'right'}}>
            <div style={{fontSize:10, color:'#15803d', fontWeight:700}}>이달 합계</div>
            <div style={{fontSize:16, fontWeight:800, color:'#0f172a', marginTop:2, fontVariantNumeric:'tabular-nums'}}>{monthTotal.toLocaleString()}<span style={{fontSize:11, fontWeight:600, marginLeft:2, color:'#15803d'}}>원</span></div>
          </div>
        </div>
      </div>
    </div>
  );

  // ── 주문 목록 ────────────────────────────────────────
  const OrderList = () => (
    <div style={{background:'#fff', border:'1px solid #e2e8f0', borderRadius:10, overflow:'hidden', marginTop:10}}>
      <div style={{padding:'10px 14px', borderBottom:'1px solid #f1f5f9', display:'flex', alignItems:'center', justifyContent:'space-between', gap:8, flexWrap:'wrap'}}>
        <span style={{fontSize:14, fontWeight:800, color:'#0f172a'}}>주문 목록</span>
        <div style={{display:'flex', gap:5, alignItems:'center'}}>
          <input type="date" defaultValue="2026-05-01" style={{padding:'4px 6px', fontSize:11, border:'1px solid #e2e8f0', borderRadius:4, fontFamily:'inherit'}}/>
          <span style={{fontSize:11, color:'#94a3b8'}}>~</span>
          <input type="date" defaultValue="2026-05-31" style={{padding:'4px 6px', fontSize:11, border:'1px solid #e2e8f0', borderRadius:4, fontFamily:'inherit'}}/>
          <button style={{padding:'4px 10px', fontSize:11, fontWeight:700, color:'#fff', background:C.primary, border:'none', borderRadius:4, cursor:'pointer'}}>조회</button>
        </div>
      </div>
      <div style={{padding:'8px 14px', display:'flex', gap:5}}>
        {[['this','이번달'],['prev','저번달'],['7d','7일'],['30d','30일'],['90d','90일']].map(([k,l])=>(
          <button key={k} onClick={()=>setOrderRange(k)} style={{
            padding:'4px 11px', fontSize:11, fontWeight:700,
            color: orderRange===k?'#15803d':'#64748b',
            background: orderRange===k?'#dcfce7':'#fff',
            border:`1px solid ${orderRange===k?'#86efac':'#e2e8f0'}`, borderRadius:5, cursor:'pointer'
          }}>{l}</button>
        ))}
      </div>
      <div style={{padding:'8px 14px', borderTop:'1px solid #f1f5f9', borderBottom:'1px solid #f1f5f9', background:'#fafbfc', display:'flex', justifyContent:'space-between', alignItems:'center'}}>
        <span style={{fontSize:11, color:'#64748b', fontWeight:600}}>{DEFAULT_ORDERS.length}건</span>
        <span style={{fontSize:14, fontWeight:800, color:'#0f172a', fontVariantNumeric:'tabular-nums'}}>{DEFAULT_ORDERS.reduce((s,o)=>s+o.total,0).toLocaleString()}원</span>
      </div>
      <div>
        {DEFAULT_ORDERS.map((o,i)=>(
          <div key={i} style={{padding:'10px 14px', borderBottom:i<DEFAULT_ORDERS.length-1?'1px solid #f1f5f9':'none'}}>
            <div style={{display:'flex', alignItems:'center', justifyContent:'space-between', marginBottom:5}}>
              <div style={{display:'flex', alignItems:'center', gap:6}}>
                <span style={{fontSize:13, fontWeight:800, color:'#0f172a', fontVariantNumeric:'tabular-nums'}}>{o.date.slice(5).replace('-','월 ')}일 (화)</span>
                {o.status==='확정' && <span style={{padding:'1px 7px', fontSize:10, fontWeight:700, color:'#15803d', background:'#dcfce7', borderRadius:9}}>✓ {o.status}</span>}
              </div>
              <span style={{fontSize:14, fontWeight:800, color:'#0f172a', fontVariantNumeric:'tabular-nums'}}>{o.total.toLocaleString()}원</span>
            </div>
            <div style={{display:'flex', alignItems:'center', gap:8, padding:'6px 8px', background:'#fafbfc', borderRadius:5, fontSize:11}}>
              <span style={{padding:'1px 7px', fontSize:10, fontWeight:700, background:'#fef3c7', color:'#a16207', borderRadius:3}}>{o.menu}</span>
              <span style={{color:'#64748b'}}>2026-05-18 16:28</span>
              <span style={{flex:1, textAlign:'right', color:'#64748b', fontWeight:600, fontVariantNumeric:'tabular-nums'}}>{o.qty}개</span>
              <span style={{color:'#0f172a', fontWeight:700, fontVariantNumeric:'tabular-nums'}}>{o.total.toLocaleString()}원</span>
              <span style={{padding:'1px 7px', fontSize:10, fontWeight:700, background:'#fef3c7', color:'#a16207', borderRadius:3}}>{o.pay}</span>
            </div>
          </div>
        ))}
      </div>
    </div>
  );

  // ── 우측: 통계 / 결제 내역서 / 메모 ─────────────────
  const MenuStats = () => (
    <div style={{background:'#fff', border:'1px solid #e2e8f0', borderRadius:10, overflow:'hidden'}}>
      <div style={{padding:'10px 14px', borderBottom:'1px solid #f1f5f9', background:'#fafbfc'}}>
        <span style={{fontSize:13, fontWeight:700, color:'#0f172a'}}>메뉴별 통계 (전체 기간)</span>
      </div>
      <div style={{padding:'8px 0'}}>
        <div style={{display:'grid', gridTemplateColumns:'60px 1fr 1fr 1fr 1fr 1fr', padding:'6px 12px', borderBottom:'1px solid #f1f5f9', fontSize:9, fontWeight:700, color:'#94a3b8', textTransform:'uppercase', letterSpacing:'0.3px'}}>
          <span>메뉴</span><span style={{textAlign:'right'}}>미결</span><span style={{textAlign:'right'}}>대기</span><span style={{textAlign:'right'}}>결제</span><span style={{textAlign:'right'}}>전체</span><span style={{textAlign:'right'}}>평균</span>
        </div>
        {MENU_STATS.map((s,i)=>(
          <div key={i} style={{display:'grid', gridTemplateColumns:'60px 1fr 1fr 1fr 1fr 1fr', padding:'8px 12px', borderBottom:'1px solid #f1f5f9', alignItems:'center'}}>
            <span><span style={{padding:'2px 8px', fontSize:11, fontWeight:800, background:s.bg, color:s.color, borderRadius:3}}>{s.key}</span></span>
            <span style={{textAlign:'right', fontSize:12, fontWeight:700, color:'#dc2626', fontVariantNumeric:'tabular-nums'}}>{s.미결}<div style={{fontSize:9, color:'#94a3b8', fontWeight:500}}>{s.미결액.toLocaleString()}</div></span>
            <span style={{textAlign:'right', fontSize:12, color:'#94a3b8', fontVariantNumeric:'tabular-nums'}}>-</span>
            <span style={{textAlign:'right', fontSize:12, color:'#94a3b8', fontVariantNumeric:'tabular-nums'}}>-</span>
            <span style={{textAlign:'right', fontSize:12, fontWeight:700, color:'#0f172a', fontVariantNumeric:'tabular-nums'}}>{s.전체}<div style={{fontSize:9, color:'#94a3b8', fontWeight:500}}>{s.전체액.toLocaleString()}</div></span>
            <span style={{textAlign:'right', fontSize:12, fontWeight:700, color:'#0f172a', fontVariantNumeric:'tabular-nums'}}>{s.평균.toLocaleString()}원</span>
          </div>
        ))}
        <div style={{display:'grid', gridTemplateColumns:'60px 1fr 1fr 1fr 1fr 1fr', padding:'10px 12px', alignItems:'center', background:'#f0fdf4', borderTop:'2px solid #bbf7d0'}}>
          <span style={{fontSize:11, fontWeight:800, color:'#15803d'}}>합계</span>
          <span style={{textAlign:'right', fontSize:12, fontWeight:800, color:'#dc2626', fontVariantNumeric:'tabular-nums'}}>6<div style={{fontSize:9, fontWeight:500}}>48,000</div></span>
          <span style={{textAlign:'right', fontSize:12, color:'#94a3b8'}}>-</span>
          <span style={{textAlign:'right', fontSize:12, color:'#94a3b8'}}>-</span>
          <span style={{textAlign:'right', fontSize:12, fontWeight:800, color:'#15803d', fontVariantNumeric:'tabular-nums'}}>6<div style={{fontSize:9, fontWeight:500}}>48,000</div></span>
          <span style={{textAlign:'right', fontSize:12, fontWeight:800, color:'#15803d', fontVariantNumeric:'tabular-nums'}}>8,000원</span>
        </div>
      </div>
    </div>
  );

  const PaymentStmt = () => (
    <div style={{background:'#fff', border:'1px solid #e2e8f0', borderRadius:10, overflow:'hidden', marginTop:10}}>
      <div style={{padding:'10px 14px', borderBottom:'1px solid #f1f5f9', background:'#fafbfc', display:'flex', alignItems:'center', justifyContent:'space-between'}}>
        <span style={{fontSize:13, fontWeight:700, color:'#0f172a'}}>결제 내역서</span>
        <span style={{fontSize:10, fontWeight:700, color:'#64748b'}}>{DEFAULT_PAYMENTS.length}건</span>
      </div>
      <div style={{padding:DEFAULT_PAYMENTS.length===0?'24px 14px':'0'}}>
        {DEFAULT_PAYMENTS.length===0 ? (
          <div style={{textAlign:'center', fontSize:11, color:'#94a3b8'}}>결제 내역서가 없습니다.</div>
        ) : DEFAULT_PAYMENTS.map((p,i)=>(
          <div key={i} style={{padding:'10px 14px', borderBottom:i<DEFAULT_PAYMENTS.length-1?'1px solid #f1f5f9':'none', display:'flex', alignItems:'center', justifyContent:'space-between'}}>
            <div>
              <div style={{fontSize:12, fontWeight:700, color:'#0f172a'}}>{p.no}</div>
              <div style={{fontSize:10, color:'#94a3b8', marginTop:1}}>{p.date}</div>
            </div>
            <span style={{fontSize:13, fontWeight:800, color:'#0f172a', fontVariantNumeric:'tabular-nums'}}>{p.amount.toLocaleString()}원</span>
          </div>
        ))}
      </div>
    </div>
  );

  const MemoBoard = () => (
    <div style={{background:'#fff', border:'1px solid #e2e8f0', borderRadius:10, overflow:'hidden', marginTop:10, display:'flex', flexDirection:'column'}}>
      <div style={{padding:'10px 14px', borderBottom:'1px solid #f1f5f9', background:'#fafbfc', display:'flex', alignItems:'center', justifyContent:'space-between'}}>
        <span style={{fontSize:13, fontWeight:700, color:'#0f172a'}}>메모</span>
        <select value={memoFilter} onChange={e=>setMemoFilter(e.target.value)} style={{padding:'2px 6px', fontSize:11, border:'1px solid #e2e8f0', borderRadius:4, fontFamily:'inherit', color:'#475569'}}>
          <option value="">전체</option>
          {Object.entries(MEMO_CATS).map(([k,v])=><option key={k} value={k}>{v.label}</option>)}
        </select>
      </div>
      {/* 카테고리 칩 */}
      <div style={{padding:'10px 14px', display:'grid', gridTemplateColumns:'1fr 1fr 1fr 1fr', gap:5, borderBottom:'1px solid #f1f5f9'}}>
        {Object.entries(MEMO_CATS).map(([k,v])=>(
          <button key={k} onClick={()=>setMemoType(k)} style={{
            padding:'6px 0', fontSize:11, fontWeight:700,
            color: memoType===k?'#fff':v.color,
            background: memoType===k? (k==='general'?'#475569':v.color) : v.bg,
            border:'none', borderRadius:5, cursor:'pointer',
          }}>{v.label}</button>
        ))}
      </div>
      <div style={{padding:'10px 14px', display:'flex', flexDirection:'column', gap:6}}>
        <textarea value={memoInput} onChange={e=>setMemoInput(e.target.value)} placeholder="메모 내용을 입력하세요..." style={{padding:'8px 10px', fontSize:12, border:'1px solid #e2e8f0', borderRadius:5, resize:'vertical', minHeight:60, fontFamily:'inherit', outline:'none'}}/>
        <div style={{display:'flex', alignItems:'center', gap:6}}>
          <input type="date" style={{padding:'5px 8px', fontSize:11, border:'1px solid #e2e8f0', borderRadius:4, fontFamily:'inherit'}}/>
          <label style={{display:'flex', alignItems:'center', gap:4, fontSize:11, color:'#475569', cursor:'pointer'}}>
            <input type="checkbox" checked={memoUrgent} onChange={e=>setMemoUrgent(e.target.checked)} style={{accentColor:'#ef4444'}}/>긴급
          </label>
          <span style={{flex:1}}/>
          <button style={{padding:'5px 14px', fontSize:11, fontWeight:700, color:'#fff', background:C.primary, border:'none', borderRadius:5, cursor:'pointer'}}>추가</button>
        </div>
      </div>
      <div style={{padding:'14px 14px 18px', borderTop:'1px solid #f1f5f9', flex:1, overflow:'auto', minHeight:80}}>
        {filteredMemos.length===0 ? (
          <div style={{textAlign:'center', fontSize:11, color:'#94a3b8', padding:'10px 0'}}>메모가 없습니다.</div>
        ) : filteredMemos.map((m,i)=>{
          const cat = MEMO_CATS[m.cat] || MEMO_CATS.general;
          return (
            <div key={i} style={{padding:'8px 10px', marginBottom:6, background:'#fff', border:'1px solid #e2e8f0', borderLeft:`3px solid ${cat.color}`, borderRadius:5}}>
              <div style={{display:'flex', alignItems:'center', gap:5, marginBottom:4}}>
                <span style={{padding:'1px 6px', fontSize:9, fontWeight:800, background:cat.bg, color:cat.color, borderRadius:3}}>{cat.label}</span>
                {m.priority==='high' && <span style={{fontSize:9, color:'#ef4444', fontWeight:800}}>● 긴급</span>}
                <span style={{flex:1}}/>
                <span style={{fontSize:9, color:'#94a3b8'}}>{m.date} · {m.who}</span>
              </div>
              <div style={{fontSize:11, color:'#0f172a', lineHeight:1.5}}>{m.content}</div>
            </div>
          );
        })}
      </div>
    </div>
  );

  // ── 헤더 ─────────────────────────────────────────────
  const header = (
    <div style={{padding:'16px 22px', borderBottom:'1px solid #e2e8f0', background:'#fff', display:'flex', alignItems:'center', gap:10, flexShrink:0}}>
      <span style={{fontSize:18, fontWeight:800, color:'#0f172a', letterSpacing:'-0.3px'}}>{c.name}</span>
      <span style={{padding:'2px 8px', fontSize:11, fontWeight:700, background:'#fef3c7', color:'#a16207', borderRadius:3}}>6. 6호 - 4709 용정</span>
      {c.new && <span style={{padding:'2px 8px', fontSize:10, fontWeight:700, background:'#fef2f2', color:'#dc2626', borderRadius:3}}>신규</span>}
      <span style={{flex:1}}/>
      <button style={{padding:'7px 14px', fontSize:12, fontWeight:600, color:'#475569', background:'#fff', border:'1px solid #e2e8f0', borderRadius:6, cursor:'pointer'}}>새로고침</button>
      <button style={{padding:'7px 14px', fontSize:12, fontWeight:600, color:'#475569', background:'#fff', border:'1px solid #e2e8f0', borderRadius:6, cursor:'pointer'}}>링크 복사</button>
      <button style={{padding:'7px 14px', fontSize:12, fontWeight:600, color:'#475569', background:'#fff', border:'1px solid #e2e8f0', borderRadius:6, cursor:'pointer'}}>새 창</button>
      {onClose && <button onClick={onClose} style={{padding:'7px 16px', fontSize:12, fontWeight:700, color:'#fff', background:'#0f172a', border:'none', borderRadius:6, cursor:'pointer'}}>닫기</button>}
    </div>
  );

  // ── 본문: 3컬럼 ─────────────────────────────────────
  const body = (
    <div style={{flex:1, overflow:'auto', background:'#f8fafc', padding:'14px 18px'}}>
      <div style={{display:'grid', gridTemplateColumns:'320px 1fr 380px', gap:14, alignItems:'flex-start'}}>
        <div>{LeftCol()}</div>
        <div>
          {Calendar()}
          {OrderList()}
        </div>
        <div>
          {MenuStats()}
          {PaymentStmt()}
          {MemoBoard()}
        </div>
      </div>
    </div>
  );

  // ── 모드별 렌더 ──────────────────────────────────────
  if (mode === 'panel') return body;

  if (mode === 'page') return (
    <div style={{height:'100%', display:'flex', flexDirection:'column', background:'#f8fafc'}}>
      {header}{body}
    </div>
  );

  // modal
  return (
    <div style={{position:'fixed', inset:0, background:'rgba(15,23,42,0.45)', zIndex:1000, display:'flex', alignItems:'center', justifyContent:'center', padding:14}}
      onClick={e=>{ if(e.target===e.currentTarget) onClose?.(); }}>
      <div style={{width:'min(1400px, 100%)', height:'min(900px, 100%)', background:'#f8fafc', borderRadius:12, overflow:'hidden', display:'flex', flexDirection:'column', boxShadow:'0 20px 60px rgba(0,0,0,0.3)'}}>
        {header}{body}
      </div>
    </div>
  );
}

window.CompanyDetail = CompanyDetail;
