// === Orders / Sales history ===
function OrdersScreen({ orders, setOrders, goto,
                        ordersSource, ordersLoading, ordersError, ordersProgress, ordersDays, reloadOrders }) {
  const { PRODUCTS } = window.MOCK;
  const isLive = ordersSource === "live";
  const [statusFilter, setStatusFilter] = useState("all");
  const [search, setSearch] = useState("");
  const [selected, setSelected] = useState(new Set());
  const [expanded, setExpanded] = useState(new Set()); // 인라인 확장된 주문 id

  const toggleExpand = (id) => {
    setExpanded(prev => {
      const next = new Set(prev);
      if (next.has(id)) next.delete(id); else next.add(id);
      return next;
    });
  };

  const buildShippingText = (o) => {
    const lines = [];
    if (o.buyer) lines.push(o.buyer);
    if (o.phone) lines.push(o.phone);
    if (o.zipcode || o.address) lines.push((o.zipcode ? "[" + o.zipcode + "] " : "") + (o.address || ""));
    const itemSummary = (o.items || []).map(it => {
      const namePart = (it.name || it.pid) + (it.option ? " [" + it.option + "]" : "");
      return namePart + " " + it.qty + "개";
    }).join(", ");
    if (itemSummary) lines.push("[" + itemSummary + "]");
    if (o.memo) lines.push("메모: " + o.memo);
    return lines.join("\n");
  };

  const copyShipping = async (o) => {
    const text = buildShippingText(o);
    try {
      await navigator.clipboard.writeText(text);
      window.toast("배송정보가 클립보드에 복사되었습니다");
    } catch (e) {
      window.toast("복사 실패: " + e.message);
    }
  };

  const copyField = async (label, value) => {
    try {
      await navigator.clipboard.writeText(value);
      window.toast(label + " 복사됨: " + value);
    } catch (e) {
      window.toast("복사 실패: " + e.message);
    }
  };

  // 마운트 시 자격증명 있고 아직 mock이면 자동 로드
  useEffect(() => {
    if (window.API.naverConfigured() && ordersSource === "mock" && reloadOrders) {
      reloadOrders({ days: ordersDays || 7 });
    }
  }, []);

  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);
  };

  // 결제금액 — 라이브는 totalPaymentAmount, mock은 PRODUCTS lookup
  const orderTotal = (o) => {
    if (o.totalPaymentAmount) return o.totalPaymentAmount;
    return o.items.reduce((s, it) => {
      if (it.price) return s + it.price * it.qty;
      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,
    canceled: orders.filter(o => o.status === "canceled").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">
            {isLive
              ? `네이버 라이브 · 최근 ${ordersDays || 7}일 · 전체 ${orders.length}건`
              : `전체 ${orders.length}건 · 결제완료 ${counts.paid}건 · 배송중 ${counts.shipped}건`}
            {isLive && counts.paid > 0 && ` · 결제완료 ${counts.paid}`}
            {isLive && counts.canceled > 0 && ` · 취소 ${counts.canceled}`}
          </p>
        </div>
        <div className="row gap-2">
          {isLive && reloadOrders && (
            <>
              <div className="seg">
                {[7, 14, 30].map(d => (
                  <button key={d} className={"seg-btn " + ((ordersDays || 7) === d ? "active" : "")}
                          disabled={ordersLoading}
                          onClick={() => reloadOrders({ days: d })}>
                    {d}일
                  </button>
                ))}
              </div>
              <button className="btn" disabled={ordersLoading} onClick={() => reloadOrders({})}>
                <window.I.Refresh size={14} /> 새로고침
              </button>
            </>
          )}
          <button className="btn btn-primary" onClick={() => goto("shipping")} disabled={counts.paid === 0}>
            <window.I.Truck size={14} /> 발송 대기 송장 출력 ({counts.paid})
          </button>
        </div>
      </div>

      {ordersLoading && ordersProgress && (
        <div style={{ padding: "10px 14px", marginBottom: 12, background: "var(--accent-soft)", borderRadius: 8, fontSize: 12, display: "flex", alignItems: "center", gap: 10 }}>
          <window.I.Refresh size={14} stroke="var(--accent)" />
          <span>네이버에서 {ordersProgress.total}일 데이터 수집 중... ({ordersProgress.done}/{ordersProgress.total})</span>
          <div style={{ flex: 1, height: 6, background: "var(--border)", borderRadius: 3, overflow: "hidden", marginLeft: 8 }}>
            <div style={{ height: "100%", background: "var(--accent)", width: (ordersProgress.done / ordersProgress.total * 100) + "%" }} />
          </div>
        </div>
      )}
      {ordersError && (
        <div style={{ padding: "10px 14px", marginBottom: 12, background: "rgba(239, 68, 68, 0.08)", border: "1px solid rgba(239, 68, 68, 0.35)", borderRadius: 8, fontSize: 12, color: "var(--danger)" }}>
          <window.I.AlertCircle size={14} stroke="var(--danger)" style={{ verticalAlign: "middle", marginRight: 6 }} />
          주문 조회 실패: {ordersError}
        </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" style={{ flexWrap: "wrap" }}>
          {[["all", "전체"], ["paid", `결제완료 ${counts.paid}`], ["shipped", `배송중 ${counts.shipped}`], ["delivered", `배송완료 ${counts.delivered}`], ["canceled", `취소 ${counts.canceled}`]].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" 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 = isLive ? null : PRODUCTS.find(x => x.id === o.items[0].pid);
              const productName = isLive ? (o.items[0]?.name || "") : (firstItem?.name || "");
              const isExpanded = expanded.has(o.id);
              return (
                <React.Fragment key={o.id}>
                <tr 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" title={isLive ? `productOrderId: ${o.productOrderId}\norderId: ${o.orderId}` : o.id}>
                    <button onClick={() => toggleExpand(o.id)}
                            style={{ background: "none", border: "none", cursor: "pointer", color: "var(--accent)", textDecoration: "underline dotted", padding: 0, fontFamily: "inherit", fontSize: "inherit" }}
                            title="클릭하면 배송정보 펼침">
                      {isLive ? o.productOrderId : o.id}
                    </button>
                  </td>
                  <td>
                    <div style={{ fontWeight: 500 }}>{o.buyer}</div>
                    <div className="text-xs muted">{o.phone}</div>
                  </td>
                  <td>
                    <div className="row gap-2">
                      {!isLive && <ProductThumb tone={firstItem?.tone || 0} name={firstItem?.name || ""} size={32} />}
                      <div style={{ minWidth: 0 }}>
                        <div style={{ fontSize: 13, fontWeight: 500, maxWidth: 360, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }} title={productName}>
                          {productName}{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" onClick={() => toggleExpand(o.id)}
                            title={isLive ? `네이버 상태: ${o.rawProductOrderStatus}${o.rawClaimStatus ? ' / ' + o.rawClaimStatus : ''}` : ""}>
                      <window.I.ChevronDown size={14} style={{ transform: isExpanded ? "rotate(180deg)" : "none", transition: "transform 0.2s" }} />
                    </button>
                  </td>
                </tr>
                {isExpanded && (
                  <tr>
                    <td colSpan={8} style={{ padding: 0, background: "var(--bg-elev)" }}>
                      <div style={{ padding: "12px 18px", display: "grid", gridTemplateColumns: "1fr auto", gap: 12, alignItems: "flex-start" }}>
                        <div style={{ fontSize: 13, lineHeight: 1.7 }}>
                          {/* 줄 1: 받는분 + 전화번호 + 우편번호 */}
                          <div>
                            <strong>{o.buyer}</strong>
                            {o.phone && <span className="font-mono" style={{ marginLeft: 12 }}>{o.phone}</span>}
                            {o.zipcode && <span className="font-mono muted" style={{ marginLeft: 12 }}>[{o.zipcode}]</span>}
                          </div>
                          {/* 줄 2: 주소 */}
                          <div>{o.address || "-"}</div>
                          {/* 줄 3: 상품 (옵션 포함) */}
                          <div>
                            {(o.items || []).map((it, i) => (
                              <span key={i}>
                                {i > 0 && <span className="muted"> · </span>}
                                {it.name || it.pid}
                                {it.option && <span style={{ color: "var(--accent)" }}> [{it.option}]</span>}
                                {it.optionPrice > 0 && <span className="muted"> (+{formatNum(it.optionPrice)}원)</span>}
                                <span className="muted"> × {it.qty}개</span>
                              </span>
                            ))}
                          </div>
                          {/* 줄 4: 메모 (있을 때만) */}
                          {o.memo && <div className="muted">메모: {o.memo}</div>}
                        </div>
                        <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
                          <button className="btn btn-primary btn-sm" onClick={() => copyShipping(o)}>
                            <window.I.Copy size={12} /> 배송정보 복사
                          </button>
                          <button className="btn btn-sm btn-ghost" onClick={() => toggleExpand(o.id)}>
                            <window.I.X size={12} /> 닫기
                          </button>
                        </div>
                      </div>
                    </td>
                  </tr>
                )}
                </React.Fragment>
              );
            })}
          </tbody>
        </table>
        {filtered.length === 0 && !ordersLoading && (
          <div className="empty">
            <window.I.Search size={32} className="empty-icon" />
            <div>{isLive ? `최근 ${ordersDays || 7}일 동안 ${statusFilter !== "all" ? "해당 상태의 " : ""}주문이 없습니다` : "검색 결과가 없습니다"}</div>
            {isLive && (
              <div className="text-xs muted" style={{ marginTop: 6 }}>기간을 늘려보세요 (14일 / 30일)</div>
            )}
          </div>
        )}
      </div>
    </div>
  );
}

window.OrdersScreen = OrdersScreen;
