// === Logen courier shipping label / invoice ===
function ShippingScreen({ orders, setOrders }) {
  const { PRODUCTS } = window.MOCK;
  const paidOrders = orders.filter(o => o.status === "paid");
  const [selected, setSelected] = useState(new Set(paidOrders.map(o => o.id)));
  const [previewMode, setPreviewMode] = useState("table"); // table / labels

  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 itemsLabel = (o) => o.items.map(it => {
    const p = PRODUCTS.find(x => x.id === it.pid);
    return `${p?.name || it.pid} ${it.qty}개`;
  }).join(" + ");

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

  const selectedOrders = paidOrders.filter(o => selected.has(o.id));

  const printNow = () => {
    window.print();
  };

  const downloadXlsx = () => {
    // Simulate Logen xlsx export
    const headers = ["수령인명", "수령인전화번호", "수령인우편번호", "수령인주소", "품목명", "수량", "박스수량", "운임구분", "배송메시지", "주문번호"];
    const rows = selectedOrders.map(o => [
      o.buyer, o.phone, o.zipcode, o.address, itemsLabel(o), o.items.reduce((s, it) => s + it.qty, 0), 1, "선불", o.memo || "", o.id
    ]);
    const csv = "\uFEFF" + [headers, ...rows].map(r => r.map(x => `"${String(x).replace(/"/g, '""')}"`).join(",")).join("\r\n");
    const blob = new Blob([csv], { type: "text/csv;charset=utf-8;" });
    const url = URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = url;
    a.download = `LOGEN_송장_${new Date().toISOString().slice(0, 10)}.csv`;
    a.click();
    URL.revokeObjectURL(url);
    toast(`로젠 송장 양식 ${selectedOrders.length}건 다운로드 완료`);
  };

  const markShipped = () => {
    setOrders(prev => prev.map(o => selected.has(o.id) ? { ...o, status: "shipped" } : o));
    setSelected(new Set());
    toast(`${selectedOrders.length}건 발송 처리되었습니다`);
  };

  return (
    <>
      <div className="page no-print">
        <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">발송 대기 {paidOrders.length}건 · 로젠택배 표준 양식 (수령인/주소/연락처/품목/수량)</p>
          </div>
          <div className="row gap-2">
            <button className="btn" onClick={downloadXlsx} disabled={selected.size === 0}>
              <window.I.Download size={14} /> XLSX 다운로드
            </button>
            <button className="btn" onClick={printNow} disabled={selected.size === 0}>
              <window.I.Print size={14} /> 송장 인쇄
            </button>
            <button className="btn btn-primary" onClick={markShipped} disabled={selected.size === 0}>
              <window.I.Check size={14} /> {selected.size}건 발송 처리
            </button>
          </div>
        </div>

        <div className="toolbar">
          <div className="row gap-2">
            <input type="checkbox" className="checkbox" checked={paidOrders.length > 0 && selected.size === paidOrders.length} onChange={toggleAll} />
            <span className="text-sm">전체 선택 ({selected.size}/{paidOrders.length})</span>
          </div>
          <div className="toolbar-divider" />
          <div className="seg">
            <button className={"seg-btn " + (previewMode === "table" ? "active" : "")} onClick={() => setPreviewMode("table")}>표</button>
            <button className={"seg-btn " + (previewMode === "labels" ? "active" : "")} onClick={() => setPreviewMode("labels")}>송장 라벨</button>
          </div>
          <div className="right text-sm muted">
            로젠택배 운임구분: 선불 · 박스 1박스 기본
          </div>
        </div>

        {paidOrders.length === 0 ? (
          <div className="card">
            <div className="empty">
              <window.I.Truck size={32} className="empty-icon" />
              <div style={{ marginBottom: 4 }}>발송 대기 중인 주문이 없습니다</div>
              <div className="text-sm">결제완료 상태의 주문이 여기에 표시됩니다</div>
            </div>
          </div>
        ) : previewMode === "table" ? (
          <div className="table-wrap">
            <table className="table">
              <thead>
                <tr style={{ background: "var(--accent-soft)" }}>
                  <th className="table-checkbox"></th>
                  <th>수령인명</th>
                  <th>전화번호</th>
                  <th>우편번호</th>
                  <th>주소</th>
                  <th>품목명</th>
                  <th className="numeric">수량</th>
                  <th>운임</th>
                  <th>배송메시지</th>
                  <th>주문번호</th>
                </tr>
              </thead>
              <tbody>
                {paidOrders.map(o => (
                  <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 style={{ fontWeight: 500 }}>{o.buyer}</td>
                    <td className="font-mono text-sm">{o.phone}</td>
                    <td className="font-mono text-sm">{o.zipcode}</td>
                    <td style={{ minWidth: 280, fontSize: 12 }}>{o.address}</td>
                    <td style={{ fontSize: 12 }}>{itemsLabel(o)}</td>
                    <td className="numeric tabular">{o.items.reduce((s, it) => s + it.qty, 0)}</td>
                    <td className="text-sm">선불</td>
                    <td className="text-xs muted" style={{ maxWidth: 160 }}>{o.memo || "-"}</td>
                    <td className="font-mono text-xs">{o.id}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        ) : (
          <div style={{ display: "grid", gridTemplateColumns: "repeat(2, 1fr)", gap: 12 }}>
            {selectedOrders.map(o => <InvoiceLabel key={o.id} order={o} itemsLabel={itemsLabel(o)} />)}
          </div>
        )}
      </div>

      {/* Print-only labels */}
      <div className="print-only">
        {selectedOrders.map(o => (
          <div key={o.id} className="invoice-page" style={{ padding: 24 }}>
            <InvoiceLabel order={o} itemsLabel={itemsLabel(o)} />
          </div>
        ))}
      </div>
    </>
  );
}

function InvoiceLabel({ order, itemsLabel }) {
  return (
    <div style={{
      background: "white", color: "black", border: "2px solid black", borderRadius: 4,
      padding: 14, fontFamily: "'Pretendard', sans-serif", fontSize: 12, position: "relative",
    }}>
      <div style={{ display: "flex", alignItems: "center", borderBottom: "2px solid black", paddingBottom: 8, marginBottom: 8 }}>
        <div style={{ background: "#e60012", color: "white", fontWeight: 800, padding: "4px 8px", fontSize: 14, marginRight: 8 }}>LOGEN</div>
        <div style={{ fontSize: 11 }}>로젠택배 주식회사 · 1588-9988</div>
        <div style={{ marginLeft: "auto", fontSize: 11 }}>운임: 선불</div>
      </div>
      <div style={{ display: "grid", gridTemplateColumns: "70px 1fr", gap: "4px 10px", fontSize: 11 }}>
        <div style={{ fontWeight: 600 }}>받는분</div>
        <div><strong style={{ fontSize: 14 }}>{order.buyer}</strong> &nbsp; <span style={{ fontFamily: "monospace" }}>{order.phone}</span></div>
        <div style={{ fontWeight: 600 }}>주소</div>
        <div>[{order.zipcode}] {order.address}</div>
        <div style={{ fontWeight: 600 }}>품목</div>
        <div>{itemsLabel}</div>
        <div style={{ fontWeight: 600 }}>주문번호</div>
        <div style={{ fontFamily: "monospace" }}>{order.id}</div>
        {order.memo && <>
          <div style={{ fontWeight: 600 }}>메시지</div>
          <div>{order.memo}</div>
        </>}
      </div>
      <div style={{ marginTop: 10, paddingTop: 8, borderTop: "1px dashed #999", display: "flex", alignItems: "center" }}>
        <div style={{ fontSize: 10 }}>보내는분: 스마트팜 (02-1234-5678) · 서울시 송파구 위례성대로 1</div>
        <div style={{ marginLeft: "auto" }}>
          {/* Fake barcode */}
          <svg width="100" height="32" viewBox="0 0 100 32">
            {[...Array(28)].map((_, i) => (
              <rect key={i} x={i * 3.5} y={0} width={Math.random() > 0.5 ? 1.5 : 2.5} height="32" fill="black" />
            ))}
          </svg>
        </div>
      </div>
    </div>
  );
}

window.ShippingScreen = ShippingScreen;
