// Orders, Settlements pages

const Orders = () => {
  const [tab, setTab] = React.useState('all');
  const [selected, setSelected] = React.useState(null);
  const filtered = tab === 'all' ? ORDERS : ORDERS.filter(o => o.status === tab);

  const todayStats = {
    sales: ORDERS.reduce((s,o)=> o.status!=='cancelled' ? s + o.total : s, 0),
    count: ORDERS.filter(o=>o.status!=='cancelled').length,
    cancelled: ORDERS.filter(o=>o.status==='cancelled').length,
    avg: Math.round(ORDERS.reduce((s,o)=> o.status!=='cancelled' ? s + o.total : s, 0) / Math.max(ORDERS.filter(o=>o.status!=='cancelled').length,1)),
  };

  return (
    <div className="page">
      <div className="page-head">
        <div>
          <h1>주문 / 매출</h1>
          <div className="sub">실시간 주문 흐름과 매출을 모니터링합니다 · 2026.05.10</div>
        </div>
        <div className="actions">
          <button className="btn btn-ghost"><Icon name="calendar" size={14}/>오늘</button>
          <button className="btn btn-ghost"><Icon name="download" size={14}/>CSV 내보내기</button>
        </div>
      </div>

      <div className="stat-grid">
        <Stat icon="won" label="오늘 매출" value={fmtKRW(todayStats.sales)} delta="+18.2%" deltaTone="up" foot="전일 대비"/>
        <Stat icon="cart" label="오늘 주문" value={`${todayStats.count}건`} delta="+12.0%" deltaTone="up" foot={`취소 ${todayStats.cancelled}건`} tone="blue"/>
        <Stat icon="pkg" label="객단가" value={fmtKRW(todayStats.avg)} delta="+5.6%" deltaTone="up" foot="전일 대비" tone="green"/>
        <Stat icon="user" label="진행중" value={`${ORDERS.filter(o=>['pending','received','accepted','preparing'].includes(o.status)).length}건`} delta="실시간" deltaTone="up" foot="픽업 대기중" tone="purple"/>
      </div>

      <div className="table-wrap" style={{ marginTop:14 }}>
        <Tabs items={[
          { value:'all', label:'전체', count: ORDERS.length },
          { value:'pending', label:'대기' },
          { value:'received', label:'접수' },
          { value:'accepted', label:'수락' },
          { value:'preparing', label:'준비중' },
          { value:'done', label:'픽업완료' },
          { value:'cancelled', label:'취소' },
        ]} value={tab} onChange={setTab}/>
        <div className="table-toolbar">
          <input className="input" placeholder="주문번호, 매장, 회원" style={{ flex:1, maxWidth:340 }}/>
          <select className="select"><option>전체 매장</option>{STORES.slice(0,5).map(s=><option key={s.id}>{s.name}</option>)}</select>
          <select className="select"><option>전체 모드</option><option>포장</option><option>매장식사</option></select>
          <select className="select"><option>전체 결제</option><option>카드</option><option>간편결제</option></select>
        </div>
        <table className="table">
          <thead><tr>
            <th>주문번호</th><th>매장</th><th>회원</th><th>주문내역</th><th>모드</th><th style={{textAlign:'right'}}>결제금액</th><th>결제수단</th><th>상태</th><th>주문 / 픽업</th><th></th>
          </tr></thead>
          <tbody>
            {filtered.map(o => {
              const s = ORDER_STATUS[o.status];
              return (
                <tr key={o.id} onClick={()=>setSelected(o)} style={{ cursor:'pointer' }}>
                  <td className="t-mono">{o.id}</td>
                  <td><div style={{ fontWeight:600 }}>{o.store}</div></td>
                  <td>{o.user}</td>
                  <td style={{ color:'var(--text-2)' }}>{o.items}</td>
                  <td><Badge tone={o.mode==='포장'?'brand':'info'}>{o.mode}</Badge></td>
                  <td style={{ textAlign:'right', fontWeight:700 }}>{fmtKRW(o.total)}</td>
                  <td>{o.pay}</td>
                  <td><Badge tone={s.tone} dot={s.dot}>{s.label}</Badge></td>
                  <td style={{ fontSize:12.5, color:'var(--text-3)' }}>{o.placed} / {o.pickup}</td>
                  <td onClick={e=>e.stopPropagation()}><button className="btn-icon"><Icon name="moreV" size={16}/></button></td>
                </tr>
              );
            })}
          </tbody>
        </table>
        <div className="table-foot">
          <span style={{ fontSize:13, color:'var(--text-3)' }}>총 {filtered.length}건</span>
          <Pager total={1} current={1}/>
        </div>
      </div>

      <Drawer open={!!selected} onClose={()=>setSelected(null)} title={selected ? `주문 ${selected.id.split('-').slice(-1)}` : ''}
        footer={<>
          <button className="btn btn-danger-ghost">주문 취소</button>
          <button className="btn btn-ghost">영수증</button>
          <button className="btn btn-primary">상태 변경</button>
        </>}
      >
        {selected && <OrderDetail order={selected}/>}
      </Drawer>
    </div>
  );
};

const OrderDetail = ({ order }) => {
  const s = ORDER_STATUS[order.status];
  const fee = Math.round(order.total * 0.02);
  const pg = Math.round(order.total * 0.035);
  return (
    <div>
      <div style={{ display:'flex', alignItems:'center', gap:8, marginBottom: 14 }}>
        <Badge tone={s.tone} dot={s.dot}>{s.label}</Badge>
        <Badge tone={order.mode==='포장'?'brand':'info'}>{order.mode}</Badge>
        <span style={{ marginLeft:'auto', fontSize:13, color:'var(--text-3)' }}>{order.placed} 주문 · {order.pickup} 픽업</span>
      </div>

      <div className="card" style={{ padding:14, marginBottom:14 }}>
        <div style={{ display:'flex', alignItems:'center', gap:10 }}>
          <div className="thumb">매</div>
          <div style={{ flex:1 }}>
            <div style={{ fontWeight:700 }}>{order.store}</div>
            <div style={{ fontSize:12, color:'var(--text-3)' }}>서울 강남구 강남대로 123 · 02-555-1042</div>
          </div>
        </div>
      </div>

      <h4 style={{ margin:'0 0 10px', fontSize:13, color:'var(--text-3)', fontWeight:600 }}>주문 내역</h4>
      <div className="card" style={{ padding:0 }}>
        {[
          { name:'참치김밥', qty:2, price:4500 },
          { name:'라볶이', qty:1, price:5800 },
        ].map((it, i) => (
          <div key={i} style={{ display:'flex', alignItems:'center', gap:10, padding:'12px 14px', borderBottom: i<1 ? '1px solid var(--border)':'0' }}>
            <div style={{ flex:1 }}>
              <div style={{ fontWeight:600, fontSize:13.5 }}>{it.name}</div>
              <div style={{ fontSize:12, color:'var(--text-3)' }}>수량 {it.qty}</div>
            </div>
            <div style={{ fontWeight:600 }}>{fmtKRW(it.price * it.qty)}</div>
          </div>
        ))}
      </div>

      <h4 style={{ margin:'24px 0 10px', fontSize:13, color:'var(--text-3)', fontWeight:600 }}>결제 정보</h4>
      <dl className="spec">
        <dt>결제수단</dt><dd>{order.pay}</dd>
        <dt>주문 금액</dt><dd>{fmtKRW(order.total)}</dd>
        <dt>중개 수수료 (2%)</dt><dd style={{ color:'var(--brand)' }}>-{fmtKRW(fee)}</dd>
        <dt>PG 수수료 (3.5%)</dt><dd style={{ color:'var(--text-3)' }}>-{fmtKRW(pg)}</dd>
        <dt>매장 정산액</dt><dd style={{ fontWeight:700, fontSize:15 }}>{fmtKRW(order.total - fee - pg)}</dd>
      </dl>

      <h4 style={{ margin:'24px 0 10px', fontSize:13, color:'var(--text-3)', fontWeight:600 }}>주문 타임라인</h4>
      <Timeline events={[
        { t: order.placed, title:'주문 접수', desc:'고객이 주문을 결제했습니다', done:true },
        { t:'14:39', title:'매장 수락', desc:'할매김밥 강남점이 주문을 수락했습니다', done: order.status !== 'pending' && order.status !== 'received' },
        { t:'14:42', title:'준비중', desc:'음식 조리를 시작했습니다', done: ['preparing','done'].includes(order.status) },
        { t: order.pickup, title:'픽업 완료', desc:'고객이 매장에서 픽업했습니다', done: order.status === 'done' },
      ]}/>
    </div>
  );
};

const Timeline = ({ events }) => (
  <div style={{ display:'flex', flexDirection:'column', gap:0 }}>
    {events.map((e,i) => (
      <div key={i} style={{ display:'flex', gap:12 }}>
        <div style={{ display:'flex', flexDirection:'column', alignItems:'center', width: 24 }}>
          <div style={{
            width:14, height:14, borderRadius:'50%',
            background: e.done ? 'var(--brand)' : 'var(--surface)',
            border: `2px solid ${e.done ? 'var(--brand)' : 'var(--border-strong)'}`,
            marginTop: 4,
          }}/>
          {i < events.length-1 && <div style={{ flex:1, width:2, background: e.done ? 'var(--brand)' : 'var(--border)', minHeight: 28 }}/>}
        </div>
        <div style={{ flex:1, paddingBottom: 14 }}>
          <div style={{ display:'flex', gap:8, alignItems:'center' }}>
            <div style={{ fontWeight:600, fontSize:13.5, color: e.done ? 'var(--text)' : 'var(--text-3)' }}>{e.title}</div>
            <span style={{ marginLeft:'auto', fontSize:12, color:'var(--text-3)' }}>{e.t}</span>
          </div>
          <div style={{ fontSize:12.5, color:'var(--text-3)', marginTop:2 }}>{e.desc}</div>
        </div>
      </div>
    ))}
  </div>
);

const Settlements = () => {
  const [tab, setTab] = React.useState('all');
  const filtered = tab === 'all' ? SETTLEMENTS : SETTLEMENTS.filter(s => s.status === tab);
  const totalPending = SETTLEMENTS.filter(s=>s.status==='pending').reduce((sum,s)=>sum+s.payout,0);
  const totalPaid = SETTLEMENTS.filter(s=>s.status==='paid').reduce((sum,s)=>sum+s.payout,0);
  const totalFee = SETTLEMENTS.reduce((sum,s)=>sum+s.fee,0);

  return (
    <div className="page">
      <div className="page-head">
        <div>
          <h1>정산 관리</h1>
          <div className="sub">매장별 정산 내역과 지급 상태를 관리합니다 · 정산주기 매월 5일</div>
        </div>
        <div className="actions">
          <select className="select" style={{ height:36 }}><option>2026년 4월</option><option>2026년 3월</option></select>
          <button className="btn btn-ghost"><Icon name="download" size={14}/>정산서 일괄</button>
          <button className="btn btn-primary"><Icon name="check" size={14}/>지급 처리</button>
        </div>
      </div>

      <div className="stat-grid">
        <Stat icon="won" label="정산 대기" value={fmtKRW(totalPending)} delta="2건" deltaTone="up" foot="이번 회차"/>
        <Stat icon="check" label="지급 완료" value={fmtKRW(totalPaid)} delta="3건" deltaTone="up" foot="2026.05.05" tone="green"/>
        <Stat icon="building" label="중개 수수료 매출" value={fmtKRW(totalFee)} delta="+12.5%" deltaTone="up" foot="회사 수익" tone="blue"/>
        <Stat icon="info" label="정산 보류" value="1건" delta="검토중" deltaTone="down" foot="정산계좌 미등록" tone="purple"/>
      </div>

      <div className="table-wrap" style={{ marginTop: 14 }}>
        <Tabs items={[
          { value:'all', label:'전체', count: SETTLEMENTS.length },
          { value:'pending', label:'정산대기', count: SETTLEMENTS.filter(s=>s.status==='pending').length },
          { value:'review', label:'검토중', count: SETTLEMENTS.filter(s=>s.status==='review').length },
          { value:'paid', label:'지급완료', count: SETTLEMENTS.filter(s=>s.status==='paid').length },
          { value:'hold', label:'보류', count: SETTLEMENTS.filter(s=>s.status==='hold').length },
        ]} value={tab} onChange={setTab}/>
        <div className="table-toolbar">
          <input className="input" placeholder="정산ID, 사업자명" style={{ flex:1, maxWidth:340 }}/>
          <button className="btn btn-ghost btn-sm"><Icon name="filter" size={14}/>필터</button>
        </div>
        <table className="table">
          <thead><tr>
            <th className="checkbox-cell"><span className="checkbox"></span></th>
            <th>정산ID</th><th>사업자</th><th>회차</th><th style={{textAlign:'right'}}>주문</th>
            <th style={{textAlign:'right'}}>총 매출</th>
            <th style={{textAlign:'right'}}>중개료 2%</th>
            <th style={{textAlign:'right'}}>PG 3.5%</th>
            <th style={{textAlign:'right'}}>지급액</th>
            <th>입금계좌</th><th>상태</th><th>지급일</th><th></th>
          </tr></thead>
          <tbody>
            {filtered.map(s => {
              const st = SETTLEMENT_STATUS[s.status];
              return (
                <tr key={s.id}>
                  <td className="checkbox-cell"><span className="checkbox"></span></td>
                  <td className="t-mono">{s.id}</td>
                  <td style={{ fontWeight:600 }}>{s.biz}</td>
                  <td>{s.period}</td>
                  <td style={{ textAlign:'right' }}>{s.orders}</td>
                  <td style={{ textAlign:'right' }}>{fmtKRW(s.gross)}</td>
                  <td style={{ textAlign:'right', color:'var(--brand)' }}>-{fmtKRW(s.fee)}</td>
                  <td style={{ textAlign:'right', color:'var(--text-3)' }}>-{fmtKRW(s.pg)}</td>
                  <td style={{ textAlign:'right', fontWeight:700 }}>{fmtKRW(s.payout)}</td>
                  <td style={{ fontSize:12.5, color:'var(--text-2)' }}>{s.bank}</td>
                  <td><Badge tone={st.tone}>{st.label}</Badge></td>
                  <td style={{ color:'var(--text-3)' }}>{s.date}</td>
                  <td>
                    <div className="row-actions">
                      {s.status === 'pending' ? <button className="btn btn-sm btn-primary">지급</button> : null}
                      <button className="btn btn-sm btn-ghost">상세</button>
                    </div>
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
        <div className="table-foot">
          <span style={{ fontSize:13, color:'var(--text-3)' }}>총 {filtered.length}건 · 합계 {fmtKRW(filtered.reduce((s,r)=>s+r.payout,0))}</span>
          <Pager total={1} current={1}/>
        </div>
      </div>
    </div>
  );
};

Object.assign(window, { Orders, Settlements });
