/* ===========================================================================
   launch-hubs-b.jsx — Finance + On-Site hubs.
   On-Site is mobile-first (phones at the festival): big targets, stacked cards.
   =========================================================================== */
const { LccPage: LccPageB, LccTabs: LccTabsB, LCC_TABS: TABS_B, Section: SectionB, money, moneyK } = window;

/* ---------------------------------------------------------------------------
   FINANCE — budget vs actuals, money in, money out.
   --------------------------------------------------------------------------- */
function FinanceOverview({ go }) {
  const [cats, setCats] = window.useDB("budgetCategories");
  const [edit, setEdit] = React.useState(null);
  const rev = cats.filter((c) => c.kind === "revenue");
  const cost = cats.filter((c) => c.kind === "cost");
  const revIn = rev.reduce((s, c) => s + c.currentCents, 0);
  const revTgt = rev.reduce((s, c) => s + c.targetCents, 0);
  const costOut = cost.reduce((s, c) => s + c.currentCents, 0);
  const costTgt = cost.reduce((s, c) => s + c.targetCents, 0);
  const save = () => { setCats((xs) => xs.map((c) => c.id === edit.id ? { ...c, label: edit.label, currentCents: Math.round((+edit._cur || 0) * 100), targetCents: Math.round((+edit._tgt || 0) * 100) } : c)); if (window.argtPing) window.argtPing(edit.label + " updated"); setEdit(null); };
  const del = () => { setCats((xs) => xs.filter((c) => c.id !== edit.id)); setEdit(null); };
  const Line = ({ c, tone }) => (
    <div onClick={() => setEdit({ ...c, _cur: c.currentCents / 100, _tgt: c.targetCents / 100 })} title="Click to edit line" style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12, alignItems: "center", padding: "10px 12px", background: "var(--pvt-surface-mid)", borderRadius: "var(--r-md)", cursor: "pointer" }}>
      <div style={{ minWidth: 0 }}>
        <div style={{ fontSize: 13, color: "var(--pvt-muted)" }}>{c.label}</div>
        <div style={{ marginTop: 6 }}><window.Bar pct={c.currentCents / c.targetCents * 100} color={tone} /></div>
      </div>
      <div style={{ textAlign: "right" }}><span style={{ fontFamily: "var(--pvt-font-display)", fontSize: 15 }}>{moneyK(c.currentCents)}</span><span style={{ fontSize: 12, color: "var(--pvt-text-dim)" }}> / {moneyK(c.targetCents)}</span></div>
    </div>
  );
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
      <div className="grid-cols-3">
        <Kpi label="Revenue in" num={moneyK(revIn)} delta={"of " + moneyK(revTgt) + " · " + Math.round(revIn / revTgt * 100) + "%"} deltaDir="up" glyph="wallet" onClick={go ? () => go("finance", "receivables") : undefined} />
        <Kpi label="Costs committed" num={moneyK(costOut)} delta={"of " + moneyK(costTgt) + " budget"} deltaDir="down" glyph="chart" onClick={go ? () => go("finance", "payables") : undefined} />
        <Kpi label="Net position" num={moneyK(revIn - costOut)} delta={revIn - costOut >= 0 ? "Surplus to date" : "Deficit to date"} deltaDir={revIn - costOut >= 0 ? "up" : "down"} glyph="shield" />
      </div>
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16, alignItems: "start" }}>
        <SectionB title="Revenue"><div style={{ display: "flex", flexDirection: "column", gap: 8 }}>{rev.map((c) => <Line key={c.id} c={c} tone="#10B5C7" />)}</div></SectionB>
        <SectionB title="Costs"><div style={{ display: "flex", flexDirection: "column", gap: 8 }}>{cost.map((c) => <Line key={c.id} c={c} tone="#F25BA7" />)}</div></SectionB>
      </div>
      <LccModal open={!!edit} title="Edit budget line" onClose={() => setEdit(null)} onSubmit={save} submitLabel="Save">
        {edit && (<>
          <LccField label="Label"><input style={lccInput()} value={edit.label} onChange={(e) => setEdit({ ...edit, label: e.target.value })} /></LccField>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
            <LccField label="Committed / received ($)"><input style={lccInput()} value={edit._cur} onChange={(e) => setEdit({ ...edit, _cur: e.target.value })} /></LccField>
            <LccField label="Target ($)"><input style={lccInput()} value={edit._tgt} onChange={(e) => setEdit({ ...edit, _tgt: e.target.value })} /></LccField>
          </div>
          <button className="pill" onClick={del} style={{ alignSelf: "flex-start", color: "#F25BA7", borderColor: "rgba(216,40,132,0.4)" }}>Delete line</button>
        </>)}
      </LccModal>
    </div>
  );
}

function Invoices({ kind, title }) {
  const [inv, setInv] = window.useDB("budgetInvoices");
  const [show, setShow] = React.useState("all");
  const base = inv.filter((i) => i.kind === kind);
  const rows = show === "outstanding" ? base.filter((r) => r.status !== "paid") : base;
  const tone = { paid: "approved", pending: "pending", draft: "draft" };
  const total = base.reduce((s, r) => s + r.amountCents, 0);
  const outstanding = base.filter((r) => r.status !== "paid").reduce((s, r) => s + r.amountCents, 0);
  const outCount = base.filter((r) => r.status !== "paid").length;
  const catOptions = (window.ARGT_DB.get("budgetCategories") || []).filter((c) => c.kind === (kind === "receivable" ? "revenue" : "cost")).map((c) => c.label);
  const cycle = (id) => setInv((xs) => xs.map((r) => r.id === id ? { ...r, status: ({ draft: "pending", pending: "paid", paid: "draft" })[r.status], dueDate: r.status === "pending" ? "Paid" : (r.dueDate === "Paid" ? "TBD" : r.dueDate) } : r));
  const [edit, setEdit] = React.useState(null);
  const openEdit = (r) => setEdit({ ...r, _amt: r.amountCents / 100 });
  const openAdd = () => setEdit({ id: "inv" + Date.now(), kind, counterparty: "", category: catOptions[0] || "", _amt: 0, dueDate: "TBD", status: "draft", isNew: true });
  const save = () => {
    const rec = { id: edit.id, kind: edit.kind || kind, counterparty: (edit.counterparty || "").trim() || "Untitled", category: edit.category || "", amountCents: Math.round((+edit._amt || 0) * 100), dueDate: edit.dueDate || "TBD", status: edit.status };
    setInv((xs) => edit.isNew ? [...xs, rec] : xs.map((r) => r.id === edit.id ? rec : r));
    if (window.argtPing) window.argtPing(edit.isNew ? "Invoice added" : "Invoice updated");
    setEdit(null);
  };
  const del = (id) => setInv((xs) => xs.filter((r) => r.id !== id));
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
      <div className="grid-cols-2">
        <Kpi label="Total" num={moneyK(total)} delta={base.length + " invoices"} glyph="file" onClick={() => setShow("all")} />
        <Kpi label="Outstanding" num={moneyK(outstanding)} delta={kind === "receivable" ? "Awaiting payment" : "Owed out"} deltaDir="down" glyph="wallet" onClick={outCount ? () => setShow("outstanding") : undefined} />
      </div>
      <SectionB title={title} action={<div style={{ display: "flex", gap: 6, alignItems: "center" }}><button className={"pill" + (show === "all" ? " active" : "")} onClick={() => setShow("all")}>All</button><button className={"pill" + (show === "outstanding" ? " active" : "")} onClick={() => setShow("outstanding")}>Outstanding{outCount ? " · " + outCount : ""}</button><button className="pill active" onClick={openAdd}>Add invoice</button></div>}>
        <div className="stat-rows">
          {rows.map((r) => (
            <div key={r.id} className="stat-row" style={{ display: "grid", gridTemplateColumns: "1fr auto auto auto auto", gap: 14, alignItems: "center", cursor: "pointer" }} onClick={() => openEdit(r)} title="Click to edit invoice">
              <div style={{ minWidth: 0 }}>
                <div style={{ fontFamily: "var(--pvt-font-display)", fontSize: 13.5 }}>{r.counterparty}</div>
                <div style={{ fontSize: 11, color: "var(--pvt-text-dim)", marginTop: 2 }}>{r.category || "Unassigned"}</div>
              </div>
              <span style={{ fontSize: 12, color: "var(--pvt-text-dim)" }}>{r.dueDate}</span>
              <span style={{ fontFamily: "var(--pvt-font-display)", fontSize: 14 }}>{money(r.amountCents)}</span>
              <button onClick={(e) => { e.stopPropagation(); cycle(r.id); }} title="Click to change status" style={{ background: "none", border: 0, padding: 0, cursor: "pointer" }}><Badge kind={tone[r.status]}>{r.status}</Badge></button>
              <SmallBtn title="Delete invoice" danger onClick={() => del(r.id)}>×</SmallBtn>
            </div>
          ))}
          {rows.length === 0 && <div style={{ padding: 18, textAlign: "center", fontSize: 12.5, color: "var(--pvt-text-dim)" }}>{show === "outstanding" ? "Nothing outstanding — all settled." : "No invoices yet. Add one above."}</div>}
        </div>
      </SectionB>
      <LccModal open={!!edit} title={edit && edit.isNew ? "Add invoice" : "Edit invoice"} onClose={() => setEdit(null)} onSubmit={save} submitLabel={edit && edit.isNew ? "Add" : "Save"}>
        {edit && (<>
          <LccField label={kind === "receivable" ? "Payer" : "Payee"}><input style={lccInput()} placeholder="Counterparty name" value={edit.counterparty} onChange={(e) => setEdit({ ...edit, counterparty: e.target.value })} /></LccField>
          <LccField label="Budget line"><select style={lccInput()} value={edit.category || ""} onChange={(e) => setEdit({ ...edit, category: e.target.value })}><option value="">Unassigned</option>{catOptions.map((c) => <option key={c} value={c}>{c}</option>)}</select></LccField>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 12 }}>
            <LccField label="Amount ($)"><input style={lccInput()} value={edit._amt} onChange={(e) => setEdit({ ...edit, _amt: e.target.value })} /></LccField>
            <LccField label="Due"><input style={lccInput()} value={edit.dueDate} onChange={(e) => setEdit({ ...edit, dueDate: e.target.value })} /></LccField>
            <LccField label="Status"><select style={lccInput()} value={edit.status} onChange={(e) => setEdit({ ...edit, status: e.target.value })}><option value="draft">Draft</option><option value="pending">Pending</option><option value="paid">Paid</option></select></LccField>
          </div>
        </>)}
      </LccModal>
    </div>
  );
}

function FinanceHub({ tab, go }) {
  const [, setCats] = window.useDB("budgetCategories");
  const [showAdd, setShowAdd] = React.useState(false);
  const [d, setD] = React.useState({ kind: "revenue", label: "", target: "" });
  const add = () => {
    if (!d.label.trim()) return;
    setCats((xs) => [...xs, { id: "b" + Date.now(), kind: d.kind, label: d.label.trim(), targetCents: Math.round((+d.target || 0) * 100), currentCents: 0 }]);
    if (window.argtPing) window.argtPing("Line item added to budget");
    setShowAdd(false); setD({ kind: "revenue", label: "", target: "" });
  };
  return (
    <LccPageB eyebrow="FINANCE" title="Budget & cashflow"
      lede="Line-item budget against actuals. Sponsor revenue coming in, talent and production going out, with every invoice tracked to its due date."
      actions={<><button className="pill" onClick={act("Budget exported to CSV")}>Export</button><button className="pill active" onClick={() => setShowAdd(true)}>Add line item</button></>}>
      <LccTabsB tabs={TABS_B.finance} active={tab} onChange={(t) => go("finance", t)} />
      {tab === "overview" && <FinanceOverview go={go} />}
      {tab === "receivables" && <Invoices kind="receivable" title="Money in · receivables" />}
      {tab === "payables" && <Invoices kind="payable" title="Money out · payables" />}
      <LccModal open={showAdd} title="Add budget line item" onClose={() => setShowAdd(false)} onSubmit={add} submitLabel="Add line item">
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
          <LccField label="Type"><select style={lccInput()} value={d.kind} onChange={(e) => setD({ ...d, kind: e.target.value })}><option value="revenue">Revenue</option><option value="cost">Cost</option></select></LccField>
          <LccField label="Target ($)"><input style={lccInput()} placeholder="50000" value={d.target} onChange={(e) => setD({ ...d, target: e.target.value })} /></LccField>
        </div>
        <LccField label="Label"><input style={lccInput()} placeholder="e.g. Merchandise, Insurance" value={d.label} onChange={(e) => setD({ ...d, label: e.target.value })} /></LccField>
      </LccModal>
    </LccPageB>
  );
}

/* ---------------------------------------------------------------------------
   ON-SITE — mobile-first festival weekend control.
   --------------------------------------------------------------------------- */
function DayOfCommand() {
  const [stages, setStages] = window.useDB("dayOfStages");
  const tone = { live: ["#10B5C7", "Live"], changeover: ["#E0B638", "Changeover"], hold: ["#F25BA7", "Hold"] };
  const cycle = (id) => setStages((xs) => xs.map((s) => s.id === id ? { ...s, status: ({ live: "changeover", changeover: "hold", hold: "live" })[s.status] } : s));
  const [edit, setEdit] = React.useState(null);
  const save = () => { setStages((xs) => edit.isNew ? [...xs, { ...edit, headcount: +edit.headcount || 0 }] : xs.map((s) => s.id === edit.id ? { ...edit, headcount: +edit.headcount || 0 } : s)); if (window.argtPing) window.argtPing(edit.stage + " updated"); setEdit(null); };
  const del = (id) => setStages((xs) => xs.filter((s) => s.id !== id));
  const addStage = () => setEdit({ id: "st" + Date.now(), stage: "New stage", status: "hold", current: "—", next: "TBD", nextAt: "TBD", headcount: 0, isNew: true });
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 12 }}>
        <span className="micro">TAP A CARD TO EDIT · TAP THE STATUS TO ADVANCE</span>
        <button className="pill active" onClick={addStage}>Add stage</button>
      </div>
      <div className="lcc-onsite-grid">
        {stages.map((s) => {
          const [c, l] = tone[s.status];
          return (
            <div key={s.id} className="card" onClick={() => setEdit({ ...s })} title="Tap to edit this stage" style={{ borderColor: s.status === "hold" ? "rgba(242,91,167,0.35)" : "var(--pvt-border-light)", display: "flex", flexDirection: "column", gap: 12, cursor: "pointer" }}>
              <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between" }}>
                <span style={{ fontFamily: "var(--pvt-font-display)", fontSize: 18 }}>{s.stage}</span>
                <button onClick={(e) => { e.stopPropagation(); cycle(s.id); }} title="Advance stage status" style={{ background: "none", border: 0, cursor: "pointer", display: "inline-flex", alignItems: "center", gap: 6, fontSize: 11, fontWeight: 800, textTransform: "uppercase", letterSpacing: "0.05em", color: c, fontFamily: "var(--pvt-font-body)" }}><span style={{ width: 8, height: 8, borderRadius: "50%", background: c }} />{l}</button>
              </div>
              <div style={{ background: "var(--pvt-surface-mid)", borderRadius: "var(--r-md)", padding: "12px 14px" }}>
                <div style={{ fontSize: 10.5, color: "var(--pvt-text-dim)", textTransform: "uppercase", letterSpacing: "0.08em", fontWeight: 700 }}>On stage</div>
                <div style={{ fontFamily: "var(--pvt-font-display)", fontSize: 17, marginTop: 2 }}>{s.current}</div>
              </div>
              <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", fontSize: 12.5 }}>
                <span style={{ color: "var(--pvt-muted)" }}>Next: <b style={{ fontFamily: "var(--pvt-font-display)" }}>{s.next}</b> · {s.nextAt}</span>
                <span style={{ color: "var(--pvt-text-dim)" }}>{s.headcount.toLocaleString()} here</span>
              </div>
            </div>
          );
        })}
      </div>
      <LccModal open={!!edit} title={edit && edit.isNew ? "Add stage" : "Edit stage"} onClose={() => setEdit(null)} onSubmit={save} submitLabel={edit && edit.isNew ? "Add" : "Save"}>
        {edit && (<>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
            <LccField label="Stage name"><input style={lccInput()} value={edit.stage} onChange={(e) => setEdit({ ...edit, stage: e.target.value })} /></LccField>
            <LccField label="Status"><select style={lccInput()} value={edit.status} onChange={(e) => setEdit({ ...edit, status: e.target.value })}><option value="live">Live</option><option value="changeover">Changeover</option><option value="hold">Hold</option></select></LccField>
          </div>
          <LccField label="On stage now"><input style={lccInput()} value={edit.current} onChange={(e) => setEdit({ ...edit, current: e.target.value })} /></LccField>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 12 }}>
            <LccField label="Next act"><input style={lccInput()} value={edit.next} onChange={(e) => setEdit({ ...edit, next: e.target.value })} /></LccField>
            <LccField label="Next at"><input style={lccInput()} value={edit.nextAt} onChange={(e) => setEdit({ ...edit, nextAt: e.target.value })} /></LccField>
            <LccField label="Headcount"><input style={lccInput()} value={edit.headcount} onChange={(e) => setEdit({ ...edit, headcount: e.target.value })} /></LccField>
          </div>
          {!edit.isNew && <button className="pill" onClick={() => { del(edit.id); setEdit(null); }} style={{ alignSelf: "flex-start", color: "#F25BA7", borderColor: "rgba(216,40,132,0.4)" }}>Remove stage</button>}
        </>)}
      </LccModal>
    </div>
  );
}

function CrewCall() {
  const [sheets, setSheets] = window.useDB("crewCallSheets");
  const [edit, setEdit] = React.useState(null);
  const save = () => { setSheets((xs) => edit.isNew ? [...xs, edit] : xs.map((s) => s.id === edit.id ? edit : s)); if (window.argtPing) window.argtPing(edit.isNew ? "Call sheet added" : "Call sheet updated"); setEdit(null); };
  const del = (id) => setSheets((xs) => xs.filter((s) => s.id !== id));
  const add = () => setEdit({ id: "cs" + Date.now(), shift: "New shift", callTime: "TBD", location: "TBD", contact: "TBD", day: "Sat", isNew: true });
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 12 }}>
        <span className="micro">{sheets.length} CALL SHEETS · TAP TO EDIT</span>
        <button className="pill active" onClick={add}>Add call sheet</button>
      </div>
      <div className="lcc-onsite-grid">
        {sheets.map((s) => (
          <div key={s.id} className="card" onClick={() => setEdit({ ...s })} title="Tap to edit" style={{ display: "flex", flexDirection: "column", gap: 10, cursor: "pointer" }}>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline" }}>
              <span style={{ fontFamily: "var(--pvt-font-display)", fontSize: 16 }}>{s.shift}</span>
              <span className="badge approved" style={{ flexShrink: 0 }}>{s.day}</span>
            </div>
            <div className="stat-rows">
              <div className="stat-row"><span className="lab">Call time</span><span className="num">{s.callTime}</span></div>
              <div className="stat-row"><span className="lab">Location</span><span className="num">{s.location}</span></div>
              <div className="stat-row"><span className="lab">Lead</span><span className="num">{s.contact}</span></div>
            </div>
          </div>
        ))}
      </div>
      <LccModal open={!!edit} title={edit && edit.isNew ? "Add call sheet" : "Edit call sheet"} onClose={() => setEdit(null)} onSubmit={save} submitLabel={edit && edit.isNew ? "Add" : "Save"}>
        {edit && (<>
          <div style={{ display: "grid", gridTemplateColumns: "1fr auto", gap: 12 }}>
            <LccField label="Shift"><input style={lccInput()} value={edit.shift} onChange={(e) => setEdit({ ...edit, shift: e.target.value })} /></LccField>
            <LccField label="Day"><select style={lccInput()} value={edit.day} onChange={(e) => setEdit({ ...edit, day: e.target.value })}><option>Fri</option><option>Sat</option><option>Sun</option></select></LccField>
          </div>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
            <LccField label="Call time"><input style={lccInput()} value={edit.callTime} onChange={(e) => setEdit({ ...edit, callTime: e.target.value })} /></LccField>
            <LccField label="Location"><input style={lccInput()} value={edit.location} onChange={(e) => setEdit({ ...edit, location: e.target.value })} /></LccField>
          </div>
          <LccField label="Lead / contact"><input style={lccInput()} value={edit.contact} onChange={(e) => setEdit({ ...edit, contact: e.target.value })} /></LccField>
          {!edit.isNew && <button className="pill" onClick={() => { del(edit.id); setEdit(null); }} style={{ alignSelf: "flex-start", color: "#F25BA7", borderColor: "rgba(216,40,132,0.4)" }}>Remove call sheet</button>}
        </>)}
      </LccModal>
    </div>
  );
}

function VenueMap() {
  const [zones] = window.useDB("venueZones");
  const tone = { stage: "#D8288C", vendor: "#E0B638", wellness: "#10B5C7", command: "#7A4FBF" };
  return (
    <SectionB title="Harbour Pointe · 5 stages" pad={false}>
      <div style={{ position: "relative", height: 420, margin: "0 18px 18px", borderRadius: "var(--r-lg)", overflow: "hidden",
        background: "radial-gradient(ellipse 460px 280px at 30% 40%, rgba(216,40,132,0.25), transparent 70%), radial-gradient(ellipse 380px 260px at 72% 60%, rgba(0,168,188,0.18), transparent 70%), linear-gradient(135deg, var(--pvt-surface-mid), var(--pvt-surface-light))" }}>
        {zones.map((z) => (
          <React.Fragment key={z.id}>
            <div style={{ position: "absolute", left: z.x + "%", top: z.y + "%", width: z.type === "stage" ? 16 : 12, height: z.type === "stage" ? 16 : 12, borderRadius: "50%", background: tone[z.type], boxShadow: `0 0 0 7px ${tone[z.type]}33`, transform: "translate(-50%,-50%)" }} />
            <span style={{ position: "absolute", left: z.x + "%", top: `calc(${z.y}% + 14px)`, transform: "translateX(-50%)", fontSize: 10, fontWeight: 800, letterSpacing: "0.05em", color: "white", whiteSpace: "nowrap" }}>{z.label}</span>
          </React.Fragment>
        ))}
      </div>
    </SectionB>
  );
}

function IncidentLog() {
  const [incidents, setIncidents] = window.useDB("incidents");
  const sev = { P1: "#F25BA7", P2: "#E0B638", P3: "#10B5C7" };
  const open = incidents.filter((i) => i.status === "open").length;
  const resolve = (id) => setIncidents((xs) => xs.map((x) => x.id === id ? { ...x, status: x.status === "open" ? "resolved" : "open" } : x));
  const delIncident = (id) => setIncidents((xs) => xs.filter((x) => x.id !== id));
  const [showAdd, setShowAdd] = React.useState(false);
  const [openOnly, setOpenOnly] = React.useState(false);
  const shown = openOnly ? incidents.filter((i) => i.status === "open") : incidents;
  const [d, setD] = React.useState({ kind: "Medical", stage: "Main", severity: "P3", notes: "" });
  const log = () => {
    if (!d.notes.trim()) return;
    const t = new Date();
    const at = ((t.getHours() % 12) || 12) + ":" + String(t.getMinutes()).padStart(2, "0") + " " + (t.getHours() >= 12 ? "PM" : "AM");
    setIncidents((xs) => [{ id: "inc" + Date.now(), kind: d.kind, stage: d.stage, severity: d.severity, status: "open", at, notes: d.notes.trim() }, ...xs]);
    if (window.argtPing) window.argtPing(d.severity + " incident logged");
    setShowAdd(false); setD({ kind: "Medical", stage: "Main", severity: "P3", notes: "" });
  };
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
      <div className="grid-cols-2">
        <Kpi label="Open incidents" num={String(open)} delta={openOnly ? "Showing open · clear" : (open ? "Show open only" : "All clear")} deltaDir={open ? "down" : "up"} glyph="shield" onClick={open || openOnly ? () => setOpenOnly((v) => !v) : undefined} />
        <Kpi label="Logged today" num={String(incidents.length)} delta="Across all zones" glyph="bell" />
      </div>
      <SectionB title="Incident log" action={<button className="pill active" onClick={() => setShowAdd(true)}>Log incident</button>}>
        <div className="stat-rows">
          {shown.map((i) => (
            <div key={i.id} className="stat-row" style={{ display: "grid", gridTemplateColumns: "auto auto 1fr auto auto", gap: 12, alignItems: "center" }}>
              <span style={{ fontSize: 11, fontWeight: 800, color: sev[i.severity], width: 26 }}>{i.severity}</span>
              <span style={{ fontSize: 12, color: "var(--pvt-muted)", width: 90 }}>{i.kind} · {i.stage}</span>
              <div><div style={{ fontSize: 12.5, color: "var(--pvt-text)" }}>{i.notes}</div><div style={{ fontSize: 11, color: "var(--pvt-text-dim)" }}>{i.at}</div></div>
              <button className={"pill" + (i.status === "open" ? " active" : "")} onClick={() => resolve(i.id)}>{i.status === "open" ? "Resolve" : "Resolved"}</button>
              <SmallBtn title="Delete incident" danger onClick={() => delIncident(i.id)}>×</SmallBtn>
            </div>
          ))}
          {shown.length === 0 && <div style={{ padding: 18, textAlign: "center", fontSize: 12.5, color: "var(--pvt-text-dim)" }}>No open incidents — all clear.</div>}
        </div>
      </SectionB>
      <LccModal open={showAdd} title="Log incident" onClose={() => setShowAdd(false)} onSubmit={log} submitLabel="Log">
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 12 }}>
          <LccField label="Type"><select style={lccInput()} value={d.kind} onChange={(e) => setD({ ...d, kind: e.target.value })}><option>Medical</option><option>Crowd</option><option>Vendor</option><option>Weather</option><option>Lost</option><option>Security</option></select></LccField>
          <LccField label="Zone"><select style={lccInput()} value={d.stage} onChange={(e) => setD({ ...d, stage: e.target.value })}><option>Main</option><option>Frequency</option><option>Runway</option><option>Lounge</option><option>Block</option><option>Village</option><option>Gate</option></select></LccField>
          <LccField label="Severity"><select style={lccInput()} value={d.severity} onChange={(e) => setD({ ...d, severity: e.target.value })}><option>P1</option><option>P2</option><option>P3</option></select></LccField>
        </div>
        <LccField label="What happened?"><textarea rows={3} style={{ ...lccInput(), resize: "vertical" }} placeholder="Describe the incident and any action taken" value={d.notes} onChange={(e) => setD({ ...d, notes: e.target.value })} /></LccField>
      </LccModal>
    </div>
  );
}

function Weather() {
  const [days, setDays] = window.useDB("weather");
  const ARMED = "Lightning hold plan armed";
  const toggle = (id) => setDays((xs) => xs.map((d) => d.id === id ? { ...d, trigger: d.trigger === "none" ? ARMED : "none" } : d));
  return (
    <div className="lcc-onsite-grid">
      {days.map((d) => {
        const armed = d.trigger !== "none";
        return (
        <div key={d.id} className="card" style={{ display: "flex", flexDirection: "column", gap: 12, borderColor: armed ? "rgba(224,182,56,0.4)" : "var(--pvt-border-light)" }}>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline" }}>
            <span style={{ fontFamily: "var(--pvt-font-display)", fontSize: 15 }}>{d.day}</span>
            <span style={{ fontFamily: "var(--pvt-font-display)", fontSize: 28 }}>{d.temp}</span>
          </div>
          <div style={{ fontSize: 13, color: "var(--pvt-muted)" }}>{d.forecast}</div>
          <div className="stat-rows">
            <div className="stat-row"><span className="lab">Wind</span><span className="num">{d.wind}</span></div>
            <div className="stat-row"><span className="lab">Precip</span><span className="num">{d.precip}</span></div>
          </div>
          <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 10, marginTop: "auto", paddingTop: 4 }}>
            <span style={{ fontSize: 12, fontWeight: 700, color: armed ? "#E0B638" : "var(--pvt-text-dim)", display: "flex", gap: 6, alignItems: "center", minWidth: 0 }}><Icon name="shield" size={14} />{armed ? "Lightning hold armed" : "Contingency disarmed"}</span>
            <button className="pill" onClick={() => toggle(d.id)} style={armed ? { background: "#E0B638", color: "#0c0a18", borderColor: "#E0B638" } : {}}>{armed ? "Disarm" : "Arm"}</button>
          </div>
        </div>
        );
      })}
    </div>
  );
}

function TicketPhases() {
  const [phases, setPhases] = window.useDB("ticketPhases");
  const tone = { live: ["#10B5C7", "Live"], ready: ["#E0B638", "Ready"], pending: ["var(--pvt-text-dim)", "Pending"] };
  const goLive = (id) => setPhases((xs) => xs.map((p) => p.id === id ? { ...p, status: p.status === "ready" ? "live" : p.status } : p));
  return (
    <SectionB title="Ticket phase readiness" action={<span className="micro">FOUNDERS → GATE CASCADE</span>}>
      <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
        {phases.map((p) => {
          const [c, l] = tone[p.status];
          return (
            <div key={p.id} style={{ display: "grid", gridTemplateColumns: "120px 1fr auto auto", gap: 14, alignItems: "center", padding: "14px 16px", background: "var(--pvt-surface-mid)", borderRadius: "var(--r-md)" }}>
              <span style={{ fontFamily: "var(--pvt-font-display)", fontSize: 15 }}>{p.phase}</span>
              <div><window.Bar pct={p.sold} color={c === "var(--pvt-text-dim)" ? "var(--pvt-surface-light)" : c} /><div style={{ fontSize: 11, color: "var(--pvt-text-dim)", marginTop: 5 }}>{p.sold}% of {p.allocation.toLocaleString()} allocation</div></div>
              <span style={{ display: "inline-flex", alignItems: "center", gap: 6, fontSize: 11, fontWeight: 800, textTransform: "uppercase", color: c }}>{l}</span>
              <button className={"pill" + (p.status === "ready" ? " active" : "")} disabled={p.status !== "ready"} onClick={() => goLive(p.id)} style={p.status !== "ready" ? { opacity: 0.5, cursor: "default" } : {}}>{p.status === "live" ? "Live" : "Go live " + p.goLive}</button>
            </div>
          );
        })}
      </div>
    </SectionB>
  );
}

function Recap() {
  return (
    <SectionB title="Post-event recap builder">
      <div style={{ display: "grid", gridTemplateColumns: "repeat(2, 1fr)", gap: 12 }}>
        {[
          { l: "Attendance", v: "—", n: "Captured at gates" },
          { l: "Ticket revenue", v: "—", n: "Final settlement" },
          { l: "Sponsor recaps", v: "0 sent", n: "Auto-generated decks" },
          { l: "Clean Earth raised", v: "—", n: "10% of every ticket" },
        ].map((m, i) => (
          <div key={i} style={{ padding: "16px 18px", background: "var(--pvt-surface-mid)", borderRadius: "var(--r-md)" }}>
            <div style={{ fontSize: 11, color: "var(--pvt-text-dim)", textTransform: "uppercase", letterSpacing: "0.08em", fontWeight: 700 }}>{m.l}</div>
            <div style={{ fontFamily: "var(--pvt-font-display)", fontSize: 28, margin: "4px 0 2px" }}>{m.v}</div>
            <div style={{ fontSize: 12, color: "var(--pvt-text-dim)" }}>{m.n}</div>
          </div>
        ))}
      </div>
      <p style={{ fontSize: 12.5, color: "var(--pvt-muted)", margin: "14px 0 0", lineHeight: 1.5 }}>Recap unlocks after the festival weekend. Metrics populate from gate scans, settlement, and sponsor deliverables, then export to per-sponsor recap decks.</p>
    </SectionB>
  );
}

function OnSiteHub({ tab, go }) {
  return (
    <LccPageB eyebrow="ON-SITE · MOBILE-FIRST" title="Festival weekend"
      lede="Live control for the three days on the ground. Stage status, crew call sheets, the grounds map, incident triage, weather triggers, and the ticket phase cascade, built for a phone in your hand."
      actions={<button className="pill active" onClick={act("Radio dispatch opened on all channels")}>Radio dispatch</button>}>
      <LccTabsB tabs={TABS_B.onsite} active={tab} onChange={(t) => go("onsite", t)} />
      {tab === "command" && <DayOfCommand />}
      {tab === "crew" && <CrewCall />}
      {tab === "map" && <VenueMap />}
      {tab === "incidents" && <IncidentLog />}
      {tab === "weather" && <Weather />}
      {tab === "phases" && <TicketPhases />}
      {tab === "recap" && <Recap />}
    </LccPageB>
  );
}

window.LCC_PAGES = Object.assign(window.LCC_PAGES || {}, {
  finance: (tab, go) => <FinanceHub tab={tab} go={go} />,
  onsite: (tab, go) => <OnSiteHub tab={tab} go={go} />,
});
