/* Sentosa Marketplace - Seller Portal: Orders, Inventory, Promotions, Reports
   S/No. 3   Comprehensive inventory tracking
   S/No. 4   Automated redemption tracking
   S/No. 12  Quantity and allotment controls
   S/No. 15  Seller self-service pricing
   S/No. 127-129 Bulk inventory upload, bulk inventory actions, bulk transaction processing
   S/No. 79-82 Promotion mechanics - partner may request, SDC admin approves centrally (Reply 4 Q13)
   S/No. 104, 105, 107 Inventory status, eTicket tracking and product performance reports */

const TH = { textAlign: "left", padding: "11px 20px", fontSize: 12, fontWeight: 600, letterSpacing: ".04em",
  textTransform: "uppercase", color: "var(--fg2)", borderBottom: "1px solid var(--border)" };
const TD = { padding: "13px 20px", fontSize: 14.5, borderBottom: "1px solid var(--border)" };

/* ---------------- Orders ---------------- */
function OrdersScreen({ onOpen }) {
  const [q, setQ] = React.useState("");
  const [status, setStatus] = React.useState("All");
  const rows = window.ORDERS.filter(o =>
    (status === "All" || o.status === status) &&
    (o.ref + o.buyer).toLowerCase().includes(q.toLowerCase()));
  return (
    <div style={{ padding: 32, display: "flex", flexDirection: "column", gap: 20 }}>
      <div style={{ display: "grid", gridTemplateColumns: "repeat(4,1fr)", gap: 18 }}>
        <KpiCard label="Orders today" value="2" delta="+1" up icon="receipt-text" />
        <KpiCard label="Awaiting fulfilment" value="1" icon="clock" />
        <KpiCard label="Tickets issued (7d)" value="1,284" delta="+9.2%" up icon="ticket" />
        <KpiCard label="Refunds (7d)" value="1" icon="rotate-ccw" />
      </div>

      <Card pad={0}>
        <div style={{ padding: "16px 20px", borderBottom: "1px solid var(--border)", display: "flex", gap: 12, alignItems: "center", flexWrap: "wrap" }}>
          <div style={{ position: "relative", flex: 1, maxWidth: 320, minWidth: 200 }}>
            <span style={{ position: "absolute", left: 11, top: "50%", transform: "translateY(-50%)", display: "flex" }}><Icon name="search" size={17} color="var(--fg3)" /></span>
            <input value={q} onChange={e => setQ(e.target.value)} placeholder="Search order or buyer"
              style={{ width: "100%", boxSizing: "border-box", height: 40, padding: "0 12px 0 36px", borderRadius: "var(--radius-md)", border: "1.5px solid var(--border)", fontSize: 14, fontFamily: "var(--font-sans)", outline: "none" }} />
          </div>
          <div style={{ display: "flex", gap: 6 }}>
            {["All", "Confirmed", "Processing", "Refunded"].map(s => (
              <button key={s} onClick={() => setStatus(s)}
                style={{ padding: "7px 13px", borderRadius: "var(--radius-pill)", cursor: "pointer", fontFamily: "var(--font-sans)", fontSize: 13,
                  fontWeight: status === s ? 600 : 500, border: "1px solid " + (status === s ? "var(--black)" : "var(--border)"),
                  background: status === s ? "var(--black)" : "#fff", color: status === s ? "#fff" : "var(--fg2)" }}>{s}</button>
            ))}
          </div>
          <div style={{ marginLeft: "auto" }}><ExportButtons name="Order report" rows={rows.length} /></div>
        </div>
        <div style={{ overflowX: "auto" }}>
          <table style={{ width: "100%", borderCollapse: "collapse", minWidth: 860 }}>
            <thead><tr>
              <th style={TH}>Order</th><th style={TH}>Buyer</th><th style={TH}>Travel date</th>
              <th style={{ ...TH, textAlign: "right" }}>Tickets</th><th style={{ ...TH, textAlign: "right" }}>Total</th>
              <th style={TH}>Payment</th><th style={TH}>Status</th><th style={TH}></th>
            </tr></thead>
            <tbody>
              {rows.map(o => (
                <tr key={o.ref}>
                  <td style={{ ...TD, fontFamily: "var(--font-mono)", fontWeight: 600 }}>{o.ref}</td>
                  <td style={TD}>{o.buyer}</td>
                  <td style={{ ...TD, color: "var(--fg2)" }}>{o.travel}</td>
                  <td style={{ ...TD, textAlign: "right" }}>{o.lines.reduce((s, l) => s + l.qty, 0)}</td>
                  <td style={{ ...TD, textAlign: "right", fontWeight: 600 }}>S${o.total.toFixed(2)}</td>
                  <td style={{ ...TD, color: "var(--fg2)" }}>{o.method}</td>
                  <td style={TD}><Badge tone={statusTone(o.status)}>{o.status}</Badge></td>
                  <td style={{ ...TD, textAlign: "right" }}>
                    <button onClick={() => onOpen(o)} style={{ background: "none", border: 0, cursor: "pointer", color: "var(--orange-link)", fontWeight: 600, fontFamily: "var(--font-sans)", fontSize: 14, display: "inline-flex", alignItems: "center", gap: 5 }}>View<Icon name="chevron-right" size={15} /></button>
                  </td>
                </tr>
              ))}
              {rows.length === 0 && <tr><td colSpan={8} style={{ ...TD, textAlign: "center", color: "var(--fg2)", padding: 40 }}>No orders match this filter.</td></tr>}
            </tbody>
          </table>
        </div>
      </Card>
    </div>
  );
}

function OrderDetailScreen({ o, onBack, fulfilled, onFulfil }) {
  return (
    <div style={{ padding: 32, maxWidth: 980, margin: "0 auto" }}>
      <button onClick={onBack} style={{ background: "none", border: 0, cursor: "pointer", color: "var(--orange-link)", fontWeight: 500, fontFamily: "var(--font-sans)", fontSize: 14, display: "inline-flex", alignItems: "center", gap: 6, marginBottom: 18, padding: 0 }}><Icon name="arrow-left" size={16} />Back to orders</button>

      <div style={{ display: "flex", alignItems: "flex-start", gap: 16, flexWrap: "wrap", marginBottom: 22 }}>
        <div style={{ flex: 1, minWidth: 240 }}>
          <h2 style={{ margin: 0, fontFamily: "var(--font-mono)" }}>{o.ref}</h2>
          <div className="caption" style={{ marginTop: 4 }}>{o.buyer} · placed {o.placed} · paid by {o.method}</div>
        </div>
        <Badge tone={fulfilled ? "success" : statusTone(o.status)}>{fulfilled ? "Fulfilled" : o.status}</Badge>
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "1fr 300px", gap: 22, alignItems: "start" }}>
        <div style={{ display: "flex", flexDirection: "column", gap: 18 }}>
          <Card pad={0}>
            <div style={{ padding: "14px 20px", borderBottom: "1px solid var(--border)", fontWeight: 600 }}>Line items</div>
            <div style={{ overflowX: "auto" }}>
              <table style={{ width: "100%", borderCollapse: "collapse", minWidth: 520 }}>
                <thead><tr><th style={TH}>SKU</th><th style={TH}>Product</th><th style={{ ...TH, textAlign: "right" }}>Qty</th><th style={{ ...TH, textAlign: "right" }}>Unit</th><th style={{ ...TH, textAlign: "right" }}>Amount</th></tr></thead>
                <tbody>
                  {o.lines.map(l => (
                    <tr key={l.sku}>
                      <td style={{ ...TD, fontFamily: "var(--font-mono)", fontSize: 13, color: "var(--fg2)" }}>{l.sku}</td>
                      <td style={{ ...TD, fontWeight: 600 }}>{l.name}</td>
                      <td style={{ ...TD, textAlign: "right" }}>{l.qty}</td>
                      <td style={{ ...TD, textAlign: "right" }}>S${l.unit.toFixed(2)}</td>
                      <td style={{ ...TD, textAlign: "right", fontWeight: 600 }}>S${(l.qty * l.unit).toFixed(2)}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </Card>

          <Card pad={20}>
            <div style={{ fontWeight: 600, fontSize: 16, marginBottom: 4 }}>Fulfilment &amp; redemption</div>
            <p className="caption" style={{ marginBottom: 16 }}>
              eTicket QR codes are generated by the SnApp Ticketing System. Redemption status flows back here in real time as tickets are validated at the gate.
            </p>
            <div style={{ display: "grid", gridTemplateColumns: "repeat(3,1fr)", gap: 14 }}>
              {[["Tickets issued", fulfilled ? o.lines.reduce((s, l) => s + l.qty, 0) : o.issued, "ticket"],
                ["Redeemed", o.redeemed, "check-circle"],
                ["Outstanding", (fulfilled ? o.lines.reduce((s, l) => s + l.qty, 0) : o.issued) - o.redeemed, "clock"]].map(([l, v, ic]) => (
                <div key={l} style={{ padding: 14, border: "1px solid var(--border)", borderRadius: "var(--radius-md)" }}>
                  <div style={{ display: "flex", alignItems: "center", gap: 7, fontSize: 12.5, color: "var(--fg2)" }}><Icon name={ic} size={15} color="var(--fg3)" />{l}</div>
                  <div style={{ fontSize: 22, fontWeight: 700, marginTop: 5 }}>{v}</div>
                </div>
              ))}
            </div>
            {o.status === "Processing" && !fulfilled && (
              <div style={{ marginTop: 18, display: "flex", alignItems: "center", gap: 14, flexWrap: "wrap" }}>
                <Btn variant="primary" icon="check" onClick={onFulfil}>Confirm and issue tickets</Btn>
                <span className="caption">Issues {o.lines.reduce((s, l) => s + l.qty, 0)} eTickets to the buyer organisation.</span>
              </div>
            )}
            {fulfilled && (
              <div style={{ marginTop: 18, display: "flex", alignItems: "center", gap: 10, padding: 13, background: "var(--success-bg)", borderRadius: "var(--radius-md)", fontSize: 13.5, color: "#0f5e35", fontWeight: 500 }}>
                <Icon name="check-circle" size={17} />Tickets issued and released to {o.buyer}. Synchronised to SnApp.
              </div>
            )}
          </Card>
        </div>

        <div style={{ display: "flex", flexDirection: "column", gap: 18, position: "sticky", top: 88 }}>
          <Card pad={20}>
            <div style={{ fontWeight: 600, fontSize: 15, marginBottom: 12 }}>Settlement</div>
            <div style={{ display: "flex", flexDirection: "column", gap: 9, fontSize: 14 }}>
              <SRow l="Order value" r={`S$${o.total.toFixed(2)}`} />
              <SRow l="SDC commission" r={`−S$${(o.total * 0.12).toFixed(2)}`} sub />
              <SRow l="Bank charges" r={`−S$${(o.total * 0.006).toFixed(2)}`} sub />
            </div>
            <div style={{ borderTop: "1px solid var(--border)", marginTop: 12, paddingTop: 12, display: "flex", justifyContent: "space-between", alignItems: "baseline" }}>
              <span style={{ fontWeight: 600 }}>Payable to you</span>
              <span style={{ fontSize: 19, fontWeight: 700 }}>S${(o.total * 0.874).toFixed(2)}</span>
            </div>
            <p className="caption" style={{ marginTop: 10, marginBottom: 0 }}>Settled at your pre-agreed rate with SDC.</p>
          </Card>
          <Card pad={20}>
            <div style={{ fontWeight: 600, fontSize: 15, marginBottom: 12 }}>Buyer</div>
            <div style={{ fontSize: 14, fontWeight: 600 }}>{o.buyer}</div>
            <div style={{ fontSize: 13, color: "var(--fg2)", marginTop: 3 }}>{o.contact}</div>
            <div style={{ fontSize: 13, color: "var(--fg2)", marginTop: 10 }}>Travel date <strong style={{ color: "var(--fg1)" }}>{o.travel}</strong></div>
          </Card>
        </div>
      </div>
    </div>
  );
}

function SRow({ l, r, sub }) {
  return <div style={{ display: "flex", justifyContent: "space-between", color: sub ? "var(--fg2)" : "var(--fg1)" }}><span>{l}</span><span style={{ fontWeight: sub ? 400 : 600 }}>{r}</span></div>;
}

/* ---------------- Inventory ---------------- */
function InventoryScreen() {
  const [sel, setSel] = React.useState([]);
  const [banner, setBanner] = React.useState("");
  const [upload, setUpload] = React.useState(false);
  const rows = window.SELLER_PRODUCTS;
  const toggle = (id) => setSel(p => p.includes(id) ? p.filter(x => x !== id) : [...p, id]);
  const allOn = sel.length === rows.length;

  const bulk = (label) => {
    setBanner(`${label} applied to ${sel.length} product${sel.length !== 1 ? "s" : ""}. Synchronised to the SnApp Ticketing System.`);
    window.toast(`${label} applied`, "success", `${sel.length} product${sel.length !== 1 ? "s" : ""} updated`);
    setSel([]);
  };

  return (
    <div style={{ padding: 32, display: "flex", flexDirection: "column", gap: 20 }}>
      <div style={{ display: "grid", gridTemplateColumns: "repeat(4,1fr)", gap: 18 }}>
        <KpiCard label="Total allotment" value="5,800" icon="boxes" />
        <KpiCard label="Available now" value="3,360" icon="package" />
        <KpiCard label="Low stock" value="1" icon="alert-triangle" />
        <KpiCard label="Sold out" value="1" icon="alert-octagon" />
      </div>

      {banner && (
        <div style={{ display: "flex", alignItems: "center", gap: 10, padding: "13px 16px", background: "var(--success-bg)", border: "1px solid #b7e0c8", borderRadius: "var(--radius-md)", fontSize: 14, color: "#0f5e35", fontWeight: 500 }}>
          <Icon name="check-circle" size={18} />{banner}
          <button onClick={() => setBanner("")} aria-label="Dismiss" style={{ marginLeft: "auto", background: "none", border: 0, cursor: "pointer", display: "flex", color: "#0f5e35" }}><Icon name="x" size={16} /></button>
        </div>
      )}

      <Card pad={0}>
        <div style={{ padding: "16px 20px", borderBottom: "1px solid var(--border)", display: "flex", gap: 12, alignItems: "center", flexWrap: "wrap" }}>
          <div style={{ fontWeight: 600 }}>Allotment &amp; stock</div>
          <div style={{ marginLeft: "auto", display: "flex", gap: 8, flexWrap: "wrap", alignItems: "center" }}>
            <Btn size="sm" variant="secondary" icon="upload" onClick={() => setUpload(true)}>Bulk upload (CSV)</Btn>
            <ExportButtons name="Inventory status report" rows={rows.length} />
          </div>
        </div>

        <BulkUploadModal open={upload} onClose={() => setUpload(false)} />

        {sel.length > 0 && (
          <div style={{ padding: "12px 20px", background: "var(--orange-50)", borderBottom: "1px solid var(--border)", display: "flex", gap: 10, alignItems: "center", flexWrap: "wrap" }}>
            <strong style={{ fontSize: 13.5 }}>{sel.length} selected</strong>
            <span className="caption" style={{ margin: 0 }}>Bulk actions:</span>
            <Btn size="sm" variant="secondary" icon="plus" onClick={() => bulk("Allotment increase")}>Increase allotment</Btn>
            <Btn size="sm" variant="secondary" icon="pause" onClick={() => bulk("Deactivation")}>Deactivate</Btn>
            <Btn size="sm" variant="secondary" icon="tag" onClick={() => bulk("Price update")}>Update pricing</Btn>
            <button onClick={() => setSel([])} style={{ marginLeft: "auto", background: "none", border: 0, cursor: "pointer", color: "var(--fg2)", fontFamily: "var(--font-sans)", fontSize: 13 }}>Clear</button>
          </div>
        )}

        <div style={{ overflowX: "auto" }}>
          <table style={{ width: "100%", borderCollapse: "collapse", minWidth: 860 }}>
            <thead><tr>
              <th style={{ ...TH, width: 44 }}>
                <input type="checkbox" checked={allOn} onChange={() => setSel(allOn ? [] : rows.map(r => r.id))} aria-label="Select all" style={{ width: 17, height: 17, accentColor: "var(--action)" }} />
              </th>
              <th style={TH}>Product</th><th style={TH}>SKU</th>
              <th style={{ ...TH, textAlign: "right" }}>Allotment</th><th style={{ ...TH, textAlign: "right" }}>Available</th>
              <th style={{ ...TH, width: 180 }}>Utilisation</th><th style={TH}>Status</th>
            </tr></thead>
            <tbody>
              {rows.map(p => {
                const used = Math.round(((p.allot - p.stock) / p.allot) * 100);
                return (
                  <tr key={p.id}>
                    <td style={TD}><input type="checkbox" checked={sel.includes(p.id)} onChange={() => toggle(p.id)} aria-label={`Select ${p.name}`} style={{ width: 17, height: 17, accentColor: "var(--action)" }} /></td>
                    <td style={{ ...TD, fontWeight: 600 }}>{p.name}</td>
                    <td style={{ ...TD, fontFamily: "var(--font-mono)", fontSize: 13, color: "var(--fg2)" }}>{p.id}</td>
                    <td style={{ ...TD, textAlign: "right" }}>{p.allot.toLocaleString()}</td>
                    <td style={{ ...TD, textAlign: "right", fontWeight: p.stock < 100 ? 600 : 400, color: p.stock === 0 ? "var(--danger)" : p.stock < 100 ? "var(--warning)" : "var(--fg1)" }}>{p.stock.toLocaleString()}</td>
                    <td style={TD}>
                      <div style={{ height: 7, background: "var(--neutral-100)", borderRadius: 999, overflow: "hidden" }}>
                        <div style={{ width: `${used}%`, height: "100%", background: used >= 100 ? "var(--danger)" : used > 85 ? "var(--warning)" : "var(--action)" }}></div>
                      </div>
                      <div style={{ fontSize: 11.5, color: "var(--fg2)", marginTop: 4 }}>{used}% sold</div>
                    </td>
                    <td style={TD}><Badge tone={statusTone(p.status)}>{p.status}</Badge></td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
      </Card>
    </div>
  );
}

/* Bulk inventory upload - S/No. 127, 128 */
function BulkUploadModal({ open, onClose }) {
  const [stage, setStage] = React.useState("pick"); // pick | preview | done
  React.useEffect(() => { if (open) setStage("pick"); }, [open]);
  const preview = [
    ["SKU-1042", "Cable Car Sky Pass", "2,500", "3,000", "OK"],
    ["SKU-1043", "Cable Car + Luge Combo", "1,500", "1,800", "OK"],
    ["SKU-1077", "Cable Car Night Pass", "800", "1,200", "OK"],
    ["SKU-9999", "Unknown SKU", "-", "500", "Not found"],
  ];
  return (
    <Modal open={open} onClose={onClose} width={700}
      title="Bulk inventory upload"
      subtitle="Upload a CSV to update allotment across many products at once. Changes synchronise to SnApp on commit."
      footer={stage === "preview"
        ? <>
            <Btn variant="ghost" onClick={onClose}>Cancel</Btn>
            <Btn variant="primary" icon="check"
              onClick={() => { setStage("done"); window.toast("Bulk upload committed", "success", "3 products updated · 1 row skipped"); }}>
              Commit 3 valid rows
            </Btn>
          </>
        : <Btn variant="ghost" onClick={onClose}>Close</Btn>}>
      {stage === "pick" && (
        <React.Fragment>
          <button onClick={() => setStage("preview")}
            style={{ width: "100%", padding: "36px 20px", borderRadius: "var(--radius-md)", border: "1.5px dashed var(--border-strong)",
              background: "var(--neutral-50)", cursor: "pointer", display: "flex", flexDirection: "column",
              alignItems: "center", gap: 9, fontFamily: "var(--font-sans)" }}>
            <Icon name="upload-cloud" size={30} color="var(--fg3)" />
            <span style={{ fontSize: 15, fontWeight: 600 }}>Choose a CSV file or drag it here</span>
            <span style={{ fontSize: 13, color: "var(--fg2)" }}>Columns: SKU, allotment, valid_from, valid_to</span>
          </button>
          <button onClick={() => window.toast("Template downloaded", "info", "inventory-template.csv")}
            style={{ background: "none", border: 0, cursor: "pointer", color: "var(--orange-link)", fontWeight: 600,
              fontFamily: "var(--font-sans)", fontSize: 13.5, marginTop: 14, padding: 0, display: "inline-flex", alignItems: "center", gap: 6 }}>
            <Icon name="download" size={15} />Download the CSV template
          </button>
        </React.Fragment>
      )}
      {stage === "preview" && (
        <React.Fragment>
          <div style={{ display: "flex", alignItems: "center", gap: 10, padding: 13, background: "var(--info-bg)",
            border: "1px solid #c4d4f7", borderRadius: "var(--radius-md)", fontSize: 13.5, color: "#1a44a8", marginBottom: 16 }}>
            <Icon name="file-check" size={17} />
            <span><strong>allotment-aug-2026.csv</strong> · 4 rows read · 3 valid, 1 skipped</span>
          </div>
          <div style={{ border: "1px solid var(--border)", borderRadius: "var(--radius-md)", overflow: "hidden" }}>
            <table style={{ width: "100%", borderCollapse: "collapse" }}>
              <thead><tr>{["SKU", "Product", "Current", "New", "Status"].map((h, i) => (
                <th key={h} style={{ ...TH, textAlign: i > 1 ? "right" : "left", padding: "9px 14px", background: "var(--neutral-50)" }}>{h}</th>
              ))}</tr></thead>
              <tbody>
                {preview.map(r => (
                  <tr key={r[0]}>
                    {r.map((c, i) => (
                      <td key={i} style={{ padding: "10px 14px", fontSize: 13.5, borderBottom: "1px solid var(--border)",
                        textAlign: i > 1 ? "right" : "left",
                        fontFamily: i === 0 ? "var(--font-mono)" : "var(--font-sans)",
                        color: c === "Not found" ? "var(--danger)" : "var(--fg1)",
                        fontWeight: c === "Not found" ? 600 : 400 }}>{c}</td>
                    ))}
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </React.Fragment>
      )}
      {stage === "done" && (
        <div style={{ textAlign: "center", padding: "24px 0" }}>
          <div style={{ width: 56, height: 56, borderRadius: 999, background: "var(--success-bg)", display: "flex",
            alignItems: "center", justifyContent: "center", margin: "0 auto 14px" }}>
            <Icon name="check" size={28} color="var(--success)" strokeWidth={2.5} /></div>
          <div style={{ fontSize: 17, fontWeight: 700 }}>Upload committed</div>
          <p className="caption" style={{ marginTop: 6 }}>3 products updated and synchronised to the SnApp Ticketing System.</p>
        </div>
      )}
    </Modal>
  );
}

/* ---------------- Promotions ---------------- */
function PromotionsScreen() {
  const [creating, setCreating] = React.useState(false);
  const [submitted, setSubmitted] = React.useState(null);
  const tone = { Approved: "success", "Pending SDC approval": "warning", Rejected: "danger", Submitted: "info" };
  const rows = (submitted ? [submitted] : []).concat(window.SELLER_PROMOS);

  if (creating) return <PromotionRequest onCancel={() => setCreating(false)}
    onSubmit={(p) => { setSubmitted(p); setCreating(false); }} />;

  return (
    <div style={{ padding: 32, display: "flex", flexDirection: "column", gap: 20 }}>
      <div style={{ display: "flex", alignItems: "flex-start", gap: 12, padding: 16, background: "var(--info-bg)", border: "1px solid #c4d4f7", borderRadius: "var(--radius-md)" }}>
        <Icon name="info" size={19} color="#1a44a8" style={{ marginTop: 1 }} />
        <div style={{ fontSize: 13.5, color: "#1a44a8", lineHeight: 1.55 }}>
          Promotions are managed centrally by SDC. You can raise a promotion request here - it becomes live only after SDC admin configuration and approval.
        </div>
      </div>

      <Card pad={0}>
        <div style={{ padding: "16px 20px", borderBottom: "1px solid var(--border)", display: "flex", alignItems: "center", gap: 12 }}>
          <div style={{ fontWeight: 600 }}>Your promotion requests</div>
          <div style={{ marginLeft: "auto" }}><Btn size="sm" variant="primary" icon="plus" onClick={() => setCreating(true)}>Request a promotion</Btn></div>
        </div>
        <div style={{ overflowX: "auto" }}>
          <table style={{ width: "100%", borderCollapse: "collapse", minWidth: 880 }}>
            <thead><tr>
              <th style={TH}>Reference</th><th style={TH}>Name</th><th style={TH}>Mechanic</th>
              <th style={TH}>Value</th><th style={TH}>Applies to</th><th style={TH}>Period</th><th style={TH}>Status</th>
            </tr></thead>
            <tbody>
              {rows.map(p => (
                <tr key={p.ref}>
                  <td style={{ ...TD, fontFamily: "var(--font-mono)", fontWeight: 600, fontSize: 13.5 }}>{p.ref}</td>
                  <td style={{ ...TD, fontWeight: 600 }}>{p.name}</td>
                  <td style={TD}>{p.mech}</td>
                  <td style={{ ...TD, fontWeight: 600 }}>{p.value}</td>
                  <td style={{ ...TD, color: "var(--fg2)" }}>{p.scope}</td>
                  <td style={{ ...TD, color: "var(--fg2)" }}>{p.period}</td>
                  <td style={TD}><Badge tone={tone[p.status] || "neutral"}>{p.status}</Badge></td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </Card>
    </div>
  );
}

function PromotionRequest({ onCancel, onSubmit }) {
  const [f, setF] = React.useState({ name: "", mech: "Percentage", value: "", scope: "Cable Car Sky Pass", period: "", rationale: "" });
  const set = (k) => (e) => setF(p => ({ ...p, [k]: e.target.value }));
  const ok = f.name.trim() && f.value.trim() && f.period.trim();
  return (
    <div style={{ padding: 32, maxWidth: 760, margin: "0 auto" }}>
      <button onClick={onCancel} style={{ background: "none", border: 0, cursor: "pointer", color: "var(--orange-link)", fontWeight: 500, fontFamily: "var(--font-sans)", fontSize: 14, display: "inline-flex", alignItems: "center", gap: 6, marginBottom: 18, padding: 0 }}><Icon name="arrow-left" size={16} />Back to promotions</button>
      <h2 style={{ marginBottom: 4 }}>Request a promotion</h2>
      <p className="caption" style={{ marginBottom: 22 }}>Submitted to SDC for review. All promotions are configured and approved centrally before going live.</p>
      <Card pad={20}>
        <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
          <Field label="Promotion name" required value={f.name} onChange={set("name")} placeholder="e.g. Early-bird October" />
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16 }}>
            <Field label="Mechanic" as="select" value={f.mech} onChange={set("mech")}>
              <option>Percentage</option><option>Fixed amount</option><option>Complimentary benefit</option>
              <option>Bundle</option><option>Card-based</option><option>Coupon</option>
            </Field>
            <Field label="Value" required value={f.value} onChange={set("value")} placeholder="e.g. 12% or S$5" />
          </div>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16 }}>
            <Field label="Applies to" as="select" value={f.scope} onChange={set("scope")}>
              <option>All products</option>
              {window.SELLER_PRODUCTS.map(p => <option key={p.id}>{p.name}</option>)}
            </Field>
            <Field label="Period" required value={f.period} onChange={set("period")} placeholder="e.g. 1-31 Oct 2026" />
          </div>
          <Field label="Business rationale" as="textarea" optional value={f.rationale} onChange={set("rationale")} placeholder="Why this promotion, and the expected uplift…" />
        </div>
        <div style={{ display: "flex", gap: 12, marginTop: 20 }}>
          <Btn variant="primary" icon="send" disabled={!ok}
            onClick={() => ok && onSubmit({ ref: "PRM-2046", name: f.name, mech: f.mech, value: f.value, scope: f.scope, period: f.period, status: "Pending SDC approval" })}>
            Submit for SDC approval
          </Btn>
          <Btn variant="ghost" onClick={onCancel}>Cancel</Btn>
        </div>
      </Card>
    </div>
  );
}

/* ---------------- Reports ---------------- */
/* Report definitions - each "Generate" opens a real extract */
const SELLER_REPORT_DATA = {
  "Product performance report": {
    columns: ["Product", "Units", "Revenue (S$)", "Conversion", "Trend"],
    rows: window.PRODUCT_PERF ? window.PRODUCT_PERF.map(p =>
      [p.name, p.units.toLocaleString(), p.revenue.toLocaleString(), `${p.conv}%`, `${p.trend >= 0 ? "+" : ""}${p.trend}%`]) : [],
    summary: [["Units sold", "742"], ["Revenue", "S$35,159"], ["Avg conversion", "3.3%"]],
  },
  "eTicket tracking report": {
    columns: ["Product", "Issued", "Redeemed", "Unredeemed", "Expired"],
    rows: [["Cable Car Sky Pass", "1,284", "1,102", "168", "14"],
           ["Cable Car + Luge Combo", "860", "704", "148", "8"],
           ["Sky Dining Experience", "142", "119", "23", "0"],
           ["Group Charter (20 pax)", "18", "16", "2", "0"]],
    summary: [["Issued", "2,304"], ["Redeemed", "1,941"], ["Redemption rate", "84.2%"]],
  },
  "Inventory status report": {
    columns: ["Product", "Allotment", "Available", "Sold", "Utilisation"],
    rows: window.SELLER_PRODUCTS ? window.SELLER_PRODUCTS.map(p =>
      [p.name, p.allot.toLocaleString(), p.stock.toLocaleString(), (p.allot - p.stock).toLocaleString(),
       `${Math.round(((p.allot - p.stock) / p.allot) * 100)}%`]) : [],
    summary: [["Total allotment", "5,800"], ["Available", "3,360"], ["Utilisation", "42%"]],
  },
  "Settlement summary": {
    columns: ["Period", "Gross (S$)", "Commission (S$)", "Charges (S$)", "Payable (S$)"],
    rows: [["Jul 2026 W1", "12,480.00", "1,497.60", "74.88", "10,907.52"],
           ["Jul 2026 W2", "14,220.00", "1,706.40", "85.32", "12,428.28"],
           ["Jul 2026 W3", "11,860.00", "1,423.20", "71.16", "10,365.64"],
           ["Jul 2026 W4", "9,650.00", "1,158.00", "57.90", "8,434.10"]],
    summary: [["Gross", "S$48,210"], ["Commission", "S$5,785"], ["Payable", "S$42,135"]],
  },
};

function ReportsScreen() {
  const [range, setRange] = React.useState("MTD");
  const [report, setReport] = React.useState(null);
  const max = Math.max(...window.PRODUCT_PERF.map(p => p.revenue));
  const data = report ? SELLER_REPORT_DATA[report.name] : null;
  return (
    <div style={{ padding: 32, display: "flex", flexDirection: "column", gap: 20 }}>
      <Card pad={20}>
        <div style={{ display: "flex", alignItems: "center", gap: 12, flexWrap: "wrap" }}>
          <div>
            <div style={{ fontWeight: 600, fontSize: 16 }}>Reporting period</div>
            <div className="caption">Day-to-date, month-to-date, year-to-date and year-on-year views.</div>
          </div>
          <div style={{ marginLeft: "auto", display: "flex", gap: 6 }}>
            {["DTD", "MTD", "YTD", "YoY"].map(r => (
              <button key={r} onClick={() => setRange(r)}
                style={{ padding: "8px 15px", borderRadius: "var(--radius-md)", cursor: "pointer", fontFamily: "var(--font-sans)", fontSize: 13.5,
                  fontWeight: range === r ? 600 : 500, border: "1px solid " + (range === r ? "var(--black)" : "var(--border)"),
                  background: range === r ? "var(--black)" : "#fff", color: range === r ? "#fff" : "var(--fg2)" }}>{r}</button>
            ))}
          </div>
          <ExportButtons name={`Sales summary (${range})`} rows={window.PRODUCT_PERF.length} />
        </div>
      </Card>

      <Card pad={20}>
        <div style={{ fontWeight: 600, fontSize: 16, marginBottom: 4 }}>Product performance · {range}</div>
        <p className="caption" style={{ marginBottom: 18 }}>Revenue by SKU at your contracted settlement rates.</p>
        <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
          {window.PRODUCT_PERF.map(p => (
            <div key={p.name} style={{ display: "flex", alignItems: "center", gap: 16 }}>
              <span style={{ width: 210, fontSize: 14, fontWeight: 500, flex: "none" }}>{p.name}</span>
              <div style={{ flex: 1, height: 26, background: "var(--neutral-100)", borderRadius: "var(--radius-sm)", overflow: "hidden" }}>
                <div style={{ width: `${(p.revenue / max) * 100}%`, height: "100%", background: p.revenue === max ? "var(--action)" : "var(--orange-700)", borderRadius: "var(--radius-sm)" }}></div>
              </div>
              <span style={{ width: 92, textAlign: "right", fontSize: 14, fontWeight: 600 }}>S${p.revenue.toLocaleString()}</span>
              <span style={{ width: 72, textAlign: "right", fontSize: 13, fontWeight: 600, color: p.trend >= 0 ? "var(--success)" : "var(--danger)" }}>
                {p.trend >= 0 ? "+" : ""}{p.trend}%
              </span>
            </div>
          ))}
        </div>
      </Card>

      <Card pad={0}>
        <div style={{ padding: "16px 20px", borderBottom: "1px solid var(--border)", fontWeight: 600 }}>Available reports</div>
        {window.SELLER_REPORTS.map((r, i) => (
          <div key={r.name} style={{ display: "flex", alignItems: "center", gap: 16, padding: "15px 20px", borderBottom: i < window.SELLER_REPORTS.length - 1 ? "1px solid var(--border)" : 0 }}>
            <div style={{ width: 38, height: 38, borderRadius: "var(--radius-md)", background: "var(--orange-50)", display: "flex", alignItems: "center", justifyContent: "center", flex: "none" }}><Icon name="bar-chart-3" size={19} color="var(--orange-900)" /></div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 14.5, fontWeight: 600 }}>{r.name}{r.sno !== "-" && <span style={{ color: "var(--fg3)", fontWeight: 400, fontSize: 12.5 }}> · S/No. {r.sno}</span>}</div>
              <div style={{ fontSize: 13, color: "var(--fg2)", marginTop: 2 }}>{r.desc}</div>
            </div>
            <Btn size="sm" variant="secondary" icon="eye" onClick={() => setReport(r)}>Generate</Btn>
          </div>
        ))}
      </Card>

      {data && <ReportPreview open={!!report} onClose={() => setReport(null)} report={report}
        columns={data.columns} rows={data.rows} summary={data.summary} />}
    </div>
  );
}

Object.assign(window, { OrdersScreen, OrderDetailScreen, InventoryScreen, PromotionsScreen, ReportsScreen, TH, TD });
