/* Sentosa Marketplace - SDC Admin: dashboard, partner onboarding, product approvals
   S/No. 94    Comprehensive visual dashboard (DTD / MTD / YTD / YoY, role-configurable, exportable)
   S/No. 94(b) AI auto-generated insights and visual summaries (Reply No. 4 Q7)
   S/No. 61,62 Registration approval workflow, automated agreement management
   S/No. 133,134 Configurable multi-level approval chains, workflow tracking and notifications
   Reply No. 4 Q10: partner submits KYC → sales team notified → admin approves → auto-activation,
                    automated agreement signing and eWallet linkage */

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

function tone(s) {
  return { Live: "success", Published: "success", Active: "success", Confirmed: "success", Approved: "success",
    "Pending review": "warning", "Pending approval": "warning", "Information requested": "warning", Draft: "neutral",
    Dormant: "neutral", Completed: "neutral", Rejected: "danger", New: "info", Running: "info",
    "Quote sent": "info", "In discussion": "info" }[s] || "neutral";
}

function AKpi({ label, value, delta, up, icon, sub }) {
  return (
    <Card pad={18}>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start" }}>
        <div style={{ fontSize: 13, color: "var(--fg2)", fontWeight: 500 }}>{label}</div>
        <div style={{ width: 34, height: 34, borderRadius: "var(--radius-md)", background: "var(--orange-50)",
          display: "flex", alignItems: "center", justifyContent: "center" }}><Icon name={icon} size={18} color="var(--orange-900)" /></div>
      </div>
      <div style={{ fontSize: 26, fontWeight: 700, margin: "10px 0 4px" }}>{value}</div>
      {delta
        ? <div style={{ display: "flex", alignItems: "center", gap: 4, fontSize: 13, color: up ? "var(--success)" : "var(--danger)", fontWeight: 600 }}>
            <Icon name={up ? "trending-up" : "trending-down"} size={15} />{delta}<span style={{ color: "var(--fg3)", fontWeight: 400 }}>{sub || "vs last period"}</span>
          </div>
        : sub && <div style={{ fontSize: 12.5, color: "var(--fg2)" }}>{sub}</div>}
    </Card>
  );
}

/* ---------------- Dashboard ---------------- */
function AdminDashboard({ onNav }) {
  const [range, setRange] = React.useState("YTD");
  const series = window.REVENUE_SERIES;
  const max = Math.max(...series.map(s => s[1]));
  const insightTone = { up: ["var(--success-bg)", "#0f5e35", "trending-up"], warn: ["var(--warning-bg)", "#7a5a00", "alert-triangle"], flat: ["var(--info-bg)", "#1a44a8", "info"] };

  return (
    <div style={{ padding: 32, display: "flex", flexDirection: "column", gap: 22 }}>
      {/* Range control - S/No. 94 */}
      <Card pad={18}>
        <div style={{ display: "flex", alignItems: "center", gap: 12, flexWrap: "wrap" }}>
          <div>
            <div style={{ fontWeight: 600, fontSize: 15.5 }}>Marketplace performance</div>
            <div className="caption">Day-to-date, month-to-date, year-to-date and year-on-year, with custom date ranges.</div>
          </div>
          <div style={{ marginLeft: "auto", display: "flex", gap: 6, flexWrap: "wrap" }}>
            {["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={`Marketplace performance (${range})`} rows={6412} />
        </div>
      </Card>

      <div style={{ display: "grid", gridTemplateColumns: "repeat(4,1fr)", gap: 18 }}>
        <AKpi label={`Gross merchandise value · ${range}`} value="S$3.38m" delta="+18.2%" up icon="dollar-sign" />
        <AKpi label="Orders" value="6,412" delta="+11.4%" up icon="receipt-text" />
        <AKpi label="Active trade accounts" value="488" delta="+24" up icon="users" sub="of 512 registered" />
        <AKpi label="Island partners live" value="41" sub="3 applications pending" icon="store" />
      </div>

      {/* AI auto-insights - S/No. 94(b) */}
      <Card pad={20}>
        <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 6 }}>
          <AdminAiChip />
          <div style={{ fontWeight: 600, fontSize: 16 }}>Auto-generated insights</div>
          <span className="caption" style={{ margin: 0, marginLeft: "auto" }}>Refreshed 12 minutes ago</span>
        </div>
        <p className="caption" style={{ marginBottom: 16 }}>
          Generated from marketplace transaction data. All AI processing and data resides in Singapore.
        </p>
        <div style={{ display: "grid", gridTemplateColumns: "repeat(3,1fr)", gap: 14 }}>
          {window.AI_INSIGHTS.map(ins => {
            const [bg, fg, ic] = insightTone[ins.tone];
            return (
              <div key={ins.title} style={{ padding: 16, background: bg, borderRadius: "var(--radius-md)", border: "1px solid rgba(0,0,0,.06)" }}>
                <div style={{ display: "flex", gap: 9, alignItems: "flex-start", marginBottom: 7 }}>
                  <Icon name={ic} size={17} color={fg} style={{ marginTop: 1, flex: "none" }} />
                  <div style={{ fontSize: 14, fontWeight: 600, lineHeight: 1.35 }}>{ins.title}</div>
                </div>
                <div style={{ fontSize: 13, color: "var(--fg2)", lineHeight: 1.55 }}>{ins.body}</div>
              </div>
            );
          })}
        </div>
      </Card>

      <div style={{ display: "grid", gridTemplateColumns: "1.6fr 1fr", gap: 18, alignItems: "start" }}>
        <Card pad={20}>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 20 }}>
            <div><div style={{ fontWeight: 600, fontSize: 16 }}>Monthly GMV</div><div className="caption">FY2026 · S$ thousands</div></div>
            <Badge tone="brand" dot={false}>{range}</Badge>
          </div>
          <div style={{ display: "flex", alignItems: "flex-end", gap: 8, height: 190, paddingTop: 8 }}>
            {series.map(([m, v]) => (
              <div key={m} style={{ flex: 1, display: "flex", flexDirection: "column", alignItems: "center", gap: 7, height: "100%", justifyContent: "flex-end" }}>
                {v > 0 && <div style={{ fontSize: 11, fontWeight: 600, color: "var(--fg2)" }}>{v}</div>}
                <div style={{ width: "100%", maxWidth: 34, height: v > 0 ? `${(v / max) * 100}%` : 3,
                  background: v === max ? "var(--action)" : v > 0 ? "var(--orange-700)" : "var(--neutral-100)",
                  borderRadius: "var(--radius-sm) var(--radius-sm) 0 0" }}></div>
                <div style={{ fontSize: 11.5, color: "var(--fg2)" }}>{m}</div>
              </div>
            ))}
          </div>
        </Card>

        <Card pad={20}>
          <div style={{ fontWeight: 600, fontSize: 16, marginBottom: 14 }}>Needs your action</div>
          <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
            {[["3 partner applications awaiting review", "user-plus", "onboarding"],
              ["3 products awaiting approval", "clipboard-check", "approvals"],
              ["1 promotion pending approval", "tag", "promotions"],
              ["1 new MICE enquiry unassigned", "calendar-days", "mice"]].map(([label, ic, target]) => (
              <button key={label} onClick={() => onNav(target)}
                style={{ display: "flex", alignItems: "center", gap: 11, padding: "12px 13px", border: "1px solid var(--border)",
                  borderRadius: "var(--radius-md)", background: "#fff", cursor: "pointer", textAlign: "left", fontFamily: "var(--font-sans)", width: "100%" }}>
                <Icon name={ic} size={18} color="var(--orange-900)" />
                <span style={{ flex: 1, fontSize: 13.5, fontWeight: 500 }}>{label}</span>
                <Icon name="chevron-right" size={16} color="var(--fg3)" />
              </button>
            ))}
          </div>
        </Card>
      </div>
    </div>
  );
}

function AdminAiChip() {
  return (
    <span style={{ display: "inline-flex", alignItems: "center", gap: 5, fontSize: 11.5, fontWeight: 700, letterSpacing: ".04em",
      padding: "3px 9px", borderRadius: "var(--radius-pill)", background: "var(--orange-50)", color: "#9A4F0C",
      border: "1px solid #E8CFB4", flex: "none" }}>
      <Icon name="sparkles" size={13} />AI
    </span>
  );
}

/* ---------------- Partner onboarding ---------------- */
function OnboardingScreen({ decided, onDecide }) {
  const [open, setOpen] = React.useState(null);
  const app = open ? window.PARTNER_APPS.find(a => a.ref === open) : null;
  if (app) return <PartnerApplication a={app} decided={decided[app.ref]} onBack={() => setOpen(null)} onDecide={onDecide} />;

  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 }}>
          Partners register with KYC documents; the SDC sales team is notified for manual review. On approval the account is
          auto-activated with automated agreement signing and eWallet linkage.
        </div>
      </div>

      <Card pad={0}>
        <div style={{ padding: "16px 20px", borderBottom: "1px solid var(--border)", fontWeight: 600 }}>Applications</div>
        <div style={{ overflowX: "auto" }}>
          <table style={{ width: "100%", borderCollapse: "collapse", minWidth: 900 }}>
            <thead><tr>
              <th style={ATH}>Reference</th><th style={ATH}>Applicant</th><th style={ATH}>UEN</th>
              <th style={ATH}>Category</th><th style={{ ...ATH, textAlign: "right" }}>Products</th>
              <th style={ATH}>Submitted</th><th style={ATH}>Status</th><th style={ATH}></th>
            </tr></thead>
            <tbody>
              {window.PARTNER_APPS.map(a => {
                const st = decided[a.ref] || a.status;
                return (
                  <tr key={a.ref}>
                    <td style={{ ...ATD, fontFamily: "var(--font-mono)", fontWeight: 600, fontSize: 13.5 }}>{a.ref}</td>
                    <td style={{ ...ATD, fontWeight: 600 }}>{a.name}</td>
                    <td style={{ ...ATD, fontFamily: "var(--font-mono)", fontSize: 13, color: "var(--fg2)" }}>{a.uen}</td>
                    <td style={ATD}>{a.category}</td>
                    <td style={{ ...ATD, textAlign: "right" }}>{a.products}</td>
                    <td style={{ ...ATD, color: "var(--fg2)" }}>{a.submitted}</td>
                    <td style={ATD}><Badge tone={tone(st)}>{st}</Badge></td>
                    <td style={{ ...ATD, textAlign: "right" }}>
                      <button onClick={() => setOpen(a.ref)} 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 }}>Review<Icon name="chevron-right" size={15} /></button>
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
      </Card>
    </div>
  );
}

function PartnerApplication({ a, decided, onBack, onDecide }) {
  const [doc, setDoc] = React.useState(null);
  const [info, setInfo] = React.useState(false);
  const status = decided || a.status;
  const approved = status === "Approved";
  return (
    <div style={{ padding: 32, maxWidth: 1000, 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 applications</button>

      <div style={{ display: "flex", alignItems: "flex-start", gap: 16, flexWrap: "wrap", marginBottom: 22 }}>
        <div style={{ flex: 1, minWidth: 260 }}>
          <h2 style={{ margin: 0 }}>{a.name}</h2>
          <div className="caption" style={{ marginTop: 4 }}>{a.ref} · UEN {a.uen} · {a.category} · submitted {a.submitted}</div>
        </div>
        <Badge tone={tone(status)}>{status}</Badge>
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "1fr 320px", gap: 22, alignItems: "start" }}>
        <div style={{ display: "flex", flexDirection: "column", gap: 18 }}>
          <Card pad={20}>
            <div style={{ fontWeight: 600, fontSize: 16, marginBottom: 4 }}>KYC documents</div>
            <p className="caption" style={{ marginBottom: 16 }}>Submitted with the registration. All mandatory documents must be verified before approval.</p>
            <div style={{ display: "flex", flexDirection: "column", gap: 9 }}>
              {a.docs.map(([name, ok]) => (
                <div key={name} style={{ display: "flex", alignItems: "center", gap: 11, padding: "11px 13px",
                  border: "1px solid var(--border)", borderRadius: "var(--radius-md)" }}>
                  <Icon name={ok ? "file-check" : "file-x"} size={18} color={ok ? "var(--success)" : "var(--danger)"} />
                  <span style={{ flex: 1, fontSize: 14, fontWeight: 500 }}>{name}</span>
                  {ok ? <Badge tone="success">Verified</Badge> : <Badge tone="danger">Missing</Badge>}
                  {ok && <Btn size="sm" variant="ghost" icon="eye" ariaLabel={`View ${name}`} onClick={() => setDoc(name)}>View</Btn>}
                </div>
              ))}
            </div>
          </Card>

          <Card pad={20}>
            <div style={{ fontWeight: 600, fontSize: 16, marginBottom: 10 }}>Sales team note</div>
            <p style={{ fontSize: 14, color: "var(--fg2)", lineHeight: 1.6, margin: 0 }}>{a.note}</p>
            <div style={{ marginTop: 14, display: "flex", gap: 20, fontSize: 13.5, flexWrap: "wrap" }}>
              <span><span style={{ color: "var(--fg2)" }}>Contact</span> <strong>{a.contact}</strong></span>
              <span><span style={{ color: "var(--fg2)" }}>Products proposed</span> <strong>{a.products}</strong></span>
            </div>
          </Card>

          {/* Post-approval automation - Reply 4 Q10 */}
          <Card pad={20}>
            <div style={{ fontWeight: 600, fontSize: 16, marginBottom: 4 }}>On approval</div>
            <p className="caption" style={{ marginBottom: 16 }}>These steps run automatically once the application is approved.</p>
            <div style={{ display: "flex", flexDirection: "column", gap: 0 }}>
              {[["Account activated", approved], ["Partner agreement issued for signature", approved],
                ["eWallet linked to the partner account", approved], ["Seller portal access granted", approved]].map(([label, done], i, arr) => (
                <div key={label} style={{ display: "flex", gap: 12 }}>
                  <div style={{ display: "flex", flexDirection: "column", alignItems: "center", flex: "none" }}>
                    <span style={{ width: 20, height: 20, borderRadius: 999, display: "flex", alignItems: "center", justifyContent: "center",
                      background: done ? "var(--success)" : "var(--neutral-100)", border: done ? 0 : "1.5px solid var(--border-strong)" }}>
                      {done && <Icon name="check" size={12} color="#fff" strokeWidth={3} />}
                    </span>
                    {i < arr.length - 1 && <span style={{ width: 2, flex: 1, minHeight: 18, background: "var(--border)" }}></span>}
                  </div>
                  <div style={{ paddingBottom: i < arr.length - 1 ? 14 : 0, fontSize: 14,
                    fontWeight: done ? 600 : 500, color: done ? "var(--fg1)" : "var(--fg2)" }}>{label}</div>
                </div>
              ))}
            </div>
          </Card>
        </div>

        <Card pad={20} style={{ position: "sticky", top: 88 }}>
          <div style={{ fontWeight: 600, fontSize: 15, marginBottom: 14 }}>Decision</div>
          {status === "Approved" ? (
            <div style={{ display: "flex", gap: 10, padding: 14, background: "var(--success-bg)", borderRadius: "var(--radius-md)",
              fontSize: 13.5, color: "#0f5e35", lineHeight: 1.5 }}>
              <Icon name="check-circle" size={17} style={{ marginTop: 1, flex: "none" }} />
              Approved. The account is active, the agreement has been issued for signature and the eWallet is linked.
            </div>
          ) : status === "Rejected" ? (
            <div style={{ display: "flex", gap: 10, padding: 14, background: "var(--danger-bg)", borderRadius: "var(--radius-md)",
              fontSize: 13.5, color: "#8f1c17", lineHeight: 1.5 }}>
              <Icon name="x-circle" size={17} style={{ marginTop: 1, flex: "none" }} />
              Rejected. The applicant has been notified with the reason recorded in the audit trail.
            </div>
          ) : (
            <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
              <Btn variant="primary" full icon="check" onClick={() => onDecide(a.ref, "Approved")}>Approve application</Btn>
              <Btn variant="secondary" full icon="message-square" onClick={() => setInfo(true)}>Request information</Btn>
              <Btn variant="ghost" full icon="x" onClick={() => onDecide(a.ref, "Rejected")}>Reject</Btn>
            </div>
          )}
          <p className="caption" style={{ marginTop: 14, marginBottom: 0 }}>
            Every decision is written to the audit trail with the reviewing officer and timestamp.
          </p>
        </Card>
      </div>

      <DocPreview open={!!doc} onClose={() => setDoc(null)} title={doc || ""} kind="KYC document"
        meta={[["Applicant", a.name], ["UEN", a.uen], ["Received", a.submitted], ["Verified by", "Agnes Lim"]]} />

      <RequestInfoModal open={info} onClose={() => setInfo(false)} subject={a.name}
        options={["Updated GST registration", "Current public liability insurance", "Safety certification",
                  "Proof of operating licence", "Bank account verification"]} />
    </div>
  );
}

/* Request further information - used by both approval queues */
function RequestInfoModal({ open, onClose, subject, options }) {
  const [picked, setPicked] = React.useState([]);
  const [note, setNote] = React.useState("");
  React.useEffect(() => { if (open) { setPicked([]); setNote(""); } }, [open]);
  const toggle = (o) => setPicked(p => p.includes(o) ? p.filter(x => x !== o) : [...p, o]);
  return (
    <Modal open={open} onClose={onClose} width={580}
      title="Request further information"
      subtitle={`A notification is sent to ${subject} and the item stays in the queue.`}
      footer={<>
        <Btn variant="ghost" onClick={onClose}>Cancel</Btn>
        <Btn variant="primary" icon="send" disabled={picked.length === 0 && !note.trim()}
          onClick={() => { window.toast("Information requested", "info", `${subject} notified · ${picked.length} item${picked.length !== 1 ? "s" : ""} flagged`); onClose(); }}>
          Send request
        </Btn>
      </>}>
      <div style={{ fontSize: 13.5, fontWeight: 600, marginBottom: 10 }}>What is outstanding?</div>
      <div style={{ display: "flex", flexDirection: "column", gap: 8, marginBottom: 18 }}>
        {options.map(o => (
          <label key={o} style={{ display: "flex", alignItems: "center", gap: 10, padding: "11px 13px",
            border: "1px solid var(--border)", borderRadius: "var(--radius-md)", cursor: "pointer", fontSize: 14 }}>
            <input type="checkbox" checked={picked.includes(o)} onChange={() => toggle(o)}
              style={{ width: 17, height: 17, accentColor: "var(--action)" }} />
            {o}
          </label>
        ))}
      </div>
      <Field label="Message" as="textarea" optional value={note} onChange={e => setNote(e.target.value)}
        placeholder="Add any context for the applicant…" />
    </Modal>
  );
}

/* ---------------- Product approvals ---------------- */
function ApprovalsScreen({ decided, onDecide }) {
  const [open, setOpen] = React.useState(null);
  const p = open ? window.PRODUCT_APPS.find(x => x.ref === open) : null;
  if (p) return <ProductApproval p={p} decided={decided[p.ref]} onBack={() => setOpen(null)} onDecide={onDecide} />;

  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 }}>
          Island partners submit products and proposed bundles through the seller portal. On approval the product is onboarded
          into the SnApp Ticketing System, which remains the single source of truth for catalogue, pricing, inventory and ticket templates.
        </div>
      </div>

      <Card pad={0}>
        <div style={{ padding: "16px 20px", borderBottom: "1px solid var(--border)", fontWeight: 600 }}>Submissions</div>
        <div style={{ overflowX: "auto" }}>
          <table style={{ width: "100%", borderCollapse: "collapse", minWidth: 920 }}>
            <thead><tr>
              <th style={ATH}>Reference</th><th style={ATH}>Product</th><th style={ATH}>Partner</th><th style={ATH}>Type</th>
              <th style={{ ...ATH, textAlign: "right" }}>Trade</th><th style={{ ...ATH, textAlign: "right" }}>Allotment</th>
              <th style={ATH}>Submitted</th><th style={ATH}>Status</th><th style={ATH}></th>
            </tr></thead>
            <tbody>
              {window.PRODUCT_APPS.map(x => {
                const st = decided[x.ref] || x.status;
                return (
                  <tr key={x.ref}>
                    <td style={{ ...ATD, fontFamily: "var(--font-mono)", fontWeight: 600, fontSize: 13.5 }}>{x.ref}</td>
                    <td style={{ ...ATD, fontWeight: 600 }}>{x.name}</td>
                    <td style={{ ...ATD, color: "var(--fg2)" }}>{x.partner}</td>
                    <td style={ATD}>{x.kind === "Bundle" ? <Badge tone="brand" dot={false}>Cross-partner bundle</Badge> : x.type}</td>
                    <td style={{ ...ATD, textAlign: "right" }}>S${x.trade.toFixed(2)}</td>
                    <td style={{ ...ATD, textAlign: "right" }}>{x.allot.toLocaleString()}</td>
                    <td style={{ ...ATD, color: "var(--fg2)" }}>{x.submitted}</td>
                    <td style={ATD}><Badge tone={tone(st)}>{st}</Badge></td>
                    <td style={{ ...ATD, textAlign: "right" }}>
                      <button onClick={() => setOpen(x.ref)} 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 }}>Review<Icon name="chevron-right" size={15} /></button>
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
      </Card>
    </div>
  );
}

function ProductApproval({ p, decided, onBack, onDecide }) {
  const [changes, setChanges] = React.useState(false);
  const status = decided || p.status;
  const approved = status === "Approved";
  const margin = Math.round((1 - p.trade / p.rack) * 100);
  return (
    <div style={{ padding: 32, maxWidth: 1000, 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 submissions</button>

      <div style={{ display: "flex", alignItems: "flex-start", gap: 16, flexWrap: "wrap", marginBottom: 22 }}>
        <div style={{ flex: 1, minWidth: 260 }}>
          <h2 style={{ margin: 0 }}>{p.name}</h2>
          <div className="caption" style={{ marginTop: 4 }}>{p.ref} · {p.partner} · submitted {p.submitted}</div>
        </div>
        <Badge tone={tone(status)}>{status}</Badge>
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "1fr 320px", gap: 22, alignItems: "start" }}>
        <div style={{ display: "flex", flexDirection: "column", gap: 18 }}>
          <Card pad={20}>
            <div style={{ fontWeight: 600, fontSize: 16, marginBottom: 16 }}>Submitted configuration</div>
            <div style={{ display: "grid", gridTemplateColumns: "repeat(2,1fr)", gap: 14 }}>
              {[["Type", p.type], ["Trade rate", `S$${p.trade.toFixed(2)}`], ["Rack rate", `S$${p.rack.toFixed(2)}`],
                ["Trade discount", `${margin}%`], ["Allotment", p.allot.toLocaleString()], ["Validity", "90 days from issue"]].map(([k, v]) => (
                <div key={k} style={{ padding: 13, border: "1px solid var(--border)", borderRadius: "var(--radius-md)" }}>
                  <div style={{ fontSize: 12.5, color: "var(--fg2)" }}>{k}</div>
                  <div style={{ fontSize: 16, fontWeight: 600, marginTop: 3 }}>{v}</div>
                </div>
              ))}
            </div>
          </Card>

          {p.components && (
            <Card pad={20}>
              <div style={{ fontWeight: 600, fontSize: 16, marginBottom: 4 }}>Bundle components</div>
              <p className="caption" style={{ marginBottom: 14 }}>
                Cross-partner bundle spanning two island partners. Non-hotel bundling is in Phase 1 scope; settlement is recorded per component.
              </p>
              <div style={{ display: "flex", flexDirection: "column", gap: 9 }}>
                {p.components.map(c => (
                  <div key={c} style={{ display: "flex", alignItems: "center", gap: 11, padding: "11px 13px",
                    border: "1px solid var(--border)", borderRadius: "var(--radius-md)", fontSize: 14 }}>
                    <Icon name="package" size={17} color="var(--orange-700)" />{c}
                  </div>
                ))}
              </div>
            </Card>
          )}

          <Card pad={20}>
            <div style={{ fontWeight: 600, fontSize: 16, marginBottom: 4 }}>Approval chain</div>
            <p className="caption" style={{ marginBottom: 16 }}>Configurable multi-level approval with role-based routing and full audit trail.</p>
            <div style={{ display: "flex", flexDirection: "column", gap: 0 }}>
              {[["Submitted by partner", true], ["SDC commercial review", approved],
                ["Onboarded into SnApp Ticketing System", approved], ["Published to the marketplace", approved]].map(([label, done], i, arr) => (
                <div key={label} style={{ display: "flex", gap: 12 }}>
                  <div style={{ display: "flex", flexDirection: "column", alignItems: "center", flex: "none" }}>
                    <span style={{ width: 20, height: 20, borderRadius: 999, display: "flex", alignItems: "center", justifyContent: "center",
                      background: done ? "var(--success)" : "var(--neutral-100)", border: done ? 0 : "1.5px solid var(--border-strong)" }}>
                      {done && <Icon name="check" size={12} color="#fff" strokeWidth={3} />}
                    </span>
                    {i < arr.length - 1 && <span style={{ width: 2, flex: 1, minHeight: 18, background: "var(--border)" }}></span>}
                  </div>
                  <div style={{ paddingBottom: i < arr.length - 1 ? 14 : 0, fontSize: 14,
                    fontWeight: done ? 600 : 500, color: done ? "var(--fg1)" : "var(--fg2)" }}>{label}</div>
                </div>
              ))}
            </div>
          </Card>
        </div>

        <Card pad={20} style={{ position: "sticky", top: 88 }}>
          <div style={{ fontWeight: 600, fontSize: 15, marginBottom: 14 }}>Decision</div>
          {approved ? (
            <div style={{ display: "flex", gap: 10, padding: 14, background: "var(--success-bg)", borderRadius: "var(--radius-md)",
              fontSize: 13.5, color: "#0f5e35", lineHeight: 1.5 }}>
              <Icon name="check-circle" size={17} style={{ marginTop: 1, flex: "none" }} />
              Approved and onboarded into SnApp. Inventory now synchronises in real time with the marketplace.
            </div>
          ) : status === "Rejected" ? (
            <div style={{ display: "flex", gap: 10, padding: 14, background: "var(--danger-bg)", borderRadius: "var(--radius-md)",
              fontSize: 13.5, color: "#8f1c17", lineHeight: 1.5 }}>
              <Icon name="x-circle" size={17} style={{ marginTop: 1, flex: "none" }} />
              Rejected. The partner has been notified and the product returned to draft.
            </div>
          ) : (
            <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
              <Btn variant="primary" full icon="check" onClick={() => onDecide(p.ref, "Approved")}>Approve &amp; onboard to SnApp</Btn>
              <Btn variant="secondary" full icon="message-square" onClick={() => setChanges(true)}>Request changes</Btn>
              <Btn variant="ghost" full icon="x" onClick={() => onDecide(p.ref, "Rejected")}>Reject</Btn>
            </div>
          )}
        </Card>
      </div>

      <RequestInfoModal open={changes} onClose={() => setChanges(false)} subject={p.partner}
        options={["Trade rate is below the contracted floor", "Rack rate does not match the published price",
                  "Allotment exceeds the agreed cap", "Product description needs plain-language revision",
                  "Ticket template not supplied"]} />
    </div>
  );
}

Object.assign(window, { RequestInfoModal, AdminDashboard, OnboardingScreen, ApprovalsScreen, AdminAiChip, AKpi, ATH, ATD, tone });
