// === Orders / Sales history ===
function OrdersScreen({ orders, setOrders, goto }) {
  const { PRODUCTS } = window.MOCK;
  const [statusFilter, setStatusFilter] = useState("all");
  const [search, setSearch] = useState("");
  const [selected, setSelected] = useState(new Set());

  const filtered = useMemo(() => {
    return orders.filter(o => {
      if (statusFilter !== "all" && o.status !== statusFilter) return false;
      if (search) {
        const q = search.toLowerCase();
        if (!o.buyer.toLowerCase().includes(q) && !o.id.toLowerCase().includes(q) && !o.phone.includes(q)) return false;
      }
      return true;
    });
  }, [orders, statusFilter, search]);

  const toggleAll = () => {
    if (selected.size === filtered.length) setSelected(new Set());
    else setSelected(new Set(filtered.map(o => o.id)));
  };
  const toggleOne = (id) => {
    const s = new Set(selected);
    if (s.has(id)) s.delete(id); else s.add(id);
    setSelected(s);
  };

  const orderTotal = (o) => o.items.reduce((s, it) => {
    const p = PRODUCTS.find(x => x.id === it.pid);
    return s + (p ? p.price * it.qty : 0);
  }, 0);

  const counts = {
    paid: orders.filter(o => o.status === "paid").length,
    shipped: orders.filter(o => o.status === "shipped").length,
    delivered: orders.filter(o => o.status === "delivered").length,
  };

  return (
    <div className="page">
      <div className="page-header" style={{ display: "flex", alignItems: "flex-end", gap: 16 }}>
        <div style={{ flex: 1 }}>
          <h1 className="page-title">주문/판매 내역</h1>
          <p className="page-desc">전체 {orders.length}건 · 결제완료 {counts.paid}건 · 배송중 {counts.shipped}건</p>
        </div>
        <button className="btn btn-primary" onClick={() => goto("shipping")} disabled={counts.paid === 0}>
          <window.I.Truck size={14} /> 발송 대기 송장 출력 ({counts.paid})
        </button>
      </div>

      <div className="toolbar">
        <div className="input-with-icon" style={{ flex: 1, maxWidth: 320 }}>
          <window.I.Search size={14} className="input-icon" />
          <input className="input" placeholder="주문번호/구매자/연락처 검색..." value={search} onChange={e => setSearch(e.target.value)} />
        </div>
        <div className="toolbar-divider" />
        <div className="seg">
          {[["all", "전체"], ["paid", `결제완료 ${counts.paid}`], ["shipped", `배송중 ${counts.shipped}`], ["delivered", `배송완료 ${counts.delivered}`]].map(([k, l]) => (
            <button key={k} className={"seg-btn " + (statusFilter === k ? "active" : "")} onClick={() => setStatusFilter(k)}>{l}</button>
          ))}
        </div>
      </div>

      {selected.size > 0 && (
        <div style={{ padding: "10px 16px", background: "var(--accent-soft)", border: "1px solid var(--accent)", borderRadius: 8, marginBottom: 12, display: "flex", alignItems: "center", gap: 12 }}>
          <span style={{ fontWeight: 500 }}>{selected.size}건 선택됨</span>
          <div className="right row gap-2">
            <button className="btn btn-sm" onClick={() => goto("shipping")}>송장 출력</button>
            <button className="btn btn-sm">상태 변경</button>
            <button className="btn btn-sm" onClick={() => setSelected(new Set())}>해제</button>
          </div>
        </div>
      )}

      <div className="table-wrap">
        <table className="table">
          <thead>
            <tr>
              <th className="table-checkbox"><input type="checkbox" className="checkbox" checked={filtered.length > 0 && selected.size === filtered.length} onChange={toggleAll} /></th>
              <th>주문번호</th>
              <th>구매자</th>
              <th>상품</th>
              <th className="numeric">결제금액</th>
              <th>상태</th>
              <th>주문일시</th>
              <th></th>
            </tr>
          </thead>
          <tbody>
            {filtered.map(o => {
              const firstItem = PRODUCTS.find(x => x.id === o.items[0].pid);
              return (
                <tr key={o.id} className={selected.has(o.id) ? "selected" : ""}>
                  <td><input type="checkbox" className="checkbox" checked={selected.has(o.id)} onChange={() => toggleOne(o.id)} /></td>
                  <td className="font-mono text-sm">{o.id}</td>
                  <td>
                    <div style={{ fontWeight: 500 }}>{o.buyer}</div>
                    <div className="text-xs muted">{o.phone}</div>
                  </td>
                  <td>
                    <div className="row gap-2">
                      <ProductThumb tone={firstItem?.tone || 0} name={firstItem?.name || ""} size={32} />
                      <div style={{ minWidth: 0 }}>
                        <div style={{ fontSize: 13, fontWeight: 500 }}>
                          {firstItem?.name}{o.items.length > 1 ? ` 외 ${o.items.length - 1}건` : ""}
                        </div>
                        <div className="text-xs muted">총 {o.items.reduce((s, it) => s + it.qty, 0)}개</div>
                      </div>
                    </div>
                  </td>
                  <td className="numeric tabular" style={{ fontWeight: 600 }}>{formatKRW(orderTotal(o))}</td>
                  <td><StatusBadge status={o.status} /></td>
                  <td className="text-sm muted">{o.date}</td>
                  <td>
                    <button className="btn btn-icon btn-sm btn-ghost"><window.I.ChevronRight size={14} /></button>
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </div>
  );
}

window.OrdersScreen = OrdersScreen;
