/* ===========================================================================
   launch-hubs-a.jsx — Pipelines + Marketing hubs.
   Registers into window.LCC_PAGES. Uses helpers from launch-app.jsx.
   =========================================================================== */
const { LccPage, LccTabs, LCC_TABS, Section, Avatar, Bar, EngineChip } = window;

/* ---------------------------------------------------------------------------
   PIPELINES — one stage board, audience switcher, + Talent Advance + Analytics.
   Absorbs People + Artist/Sponsor/Vendor/Crew/Partner + BKK + Pipeline Analytics.
   --------------------------------------------------------------------------- */
const AUDIENCES = [
  { id: "artist", label: "Artists" }, { id: "sponsor", label: "Sponsors" }, { id: "vendor", label: "Vendors" },
  { id: "crew", label: "Crew" }, { id: "partner", label: "Partners" },
];
const STAGE_TONE = { Inquiry: "var(--pvt-text-dim)", Review: "#E0B638", Confirmed: "#10B5C7", Advanced: "#D8288C" };

function StageBoard() {
  const [aud, setAud] = React.useState("artist");
  const [items, setItems] = window.useDB("pipelineItems");
  const [stages] = window.useDB("pipelineStages");
  const team = window.ARGT_DB.get("launchTeam") || [];
  const here = items.filter((i) => i.audience === aud);
  const [drag, setDrag] = React.useState(null);
  const [over, setOver] = React.useState(null);
  const [edit, setEdit] = React.useState(null);
  const moveTo = (id, st) => setItems((xs) => xs.map((x) => x.id === id ? { ...x, stage: st, updatedAt: "now" } : x));
  const saveEdit = () => {
    setItems((xs) => xs.map((x) => x.id === edit.id ? { ...edit, updatedAt: "now" } : x));
    if (window.argtPing) window.argtPing(edit.name + " updated");
    setEdit(null);
  };
  const removeItem = () => {
    setItems((xs) => xs.filter((x) => x.id !== edit.id));
    if (window.argtPing) window.argtPing(edit.name + " removed from pipeline");
    setEdit(null);
  };

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
      <div style={{ display: "flex", gap: 6, flexWrap: "wrap", alignItems: "center" }}>
        {AUDIENCES.map((a) => (
          <button key={a.id} className={"pill" + (a.id === aud ? " active" : "")} onClick={() => setAud(a.id)}>
            {a.label} <span style={{ opacity: 0.7 }}>{items.filter((i) => i.audience === a.id).length}</span>
          </button>
        ))}
        <span style={{ marginLeft: "auto", fontSize: 11, color: "var(--pvt-text-dim)" }}>Drag a card to move it between stages</span>
      </div>
      <div style={{ display: "grid", gridTemplateColumns: "repeat(4, minmax(0,1fr))", gap: 12 }}>
        {stages.map((st) => {
          const col = here.filter((i) => i.stage === st);
          return (
            <div key={st}
              onDragOver={(e) => { e.preventDefault(); if (over !== st) setOver(st); }}
              onDragLeave={() => setOver((o) => o === st ? null : o)}
              onDrop={() => { if (drag) moveTo(drag, st); setDrag(null); setOver(null); }}
              style={{ background: over === st ? "var(--pvt-surface-mid)" : "var(--pvt-surface)", border: "1px solid " + (over === st ? "var(--role-accent)" : "var(--pvt-border-light)"), borderRadius: "var(--r-lg)", padding: 12, display: "flex", flexDirection: "column", gap: 10, minHeight: 220, transition: "border-color 120ms, background 120ms" }}>
              <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", padding: "2px 4px" }}>
                <span style={{ display: "inline-flex", alignItems: "center", gap: 7, fontFamily: "var(--pvt-font-display)", fontSize: 13 }}>
                  <span style={{ width: 8, height: 8, borderRadius: "50%", background: STAGE_TONE[st] }} />{st}
                </span>
                <span className="micro">{col.length}</span>
              </div>
              {col.map((it) => {
                const owner = team.find((m) => m.name.split(" ")[0] === it.owner) || { name: it.owner };
                return (
                  <div key={it.id} draggable
                    onDragStart={(e) => { setDrag(it.id); e.dataTransfer.effectAllowed = "move"; }}
                    onDragEnd={() => { setDrag(null); setOver(null); }}
                    onClick={() => setEdit({ ...it })}
                    title="Drag to move · click to edit"
                    style={{ background: "var(--pvt-surface-mid)", border: "1px solid var(--pvt-border-light)", borderRadius: "var(--r-md)", padding: 12, cursor: "grab", opacity: drag === it.id ? 0.4 : 1, display: "flex", flexDirection: "column", gap: 8 }}>
                    <div style={{ fontFamily: "var(--pvt-font-display)", fontSize: 13.5, lineHeight: 1.2 }}>{it.name}</div>
                    <div style={{ fontSize: 11, color: "var(--pvt-text-dim)" }}>{it.meta}</div>
                    <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginTop: 2 }}>
                      <span style={{ fontSize: 12, fontFamily: "var(--pvt-font-display)", color: "var(--role-accent-bright)" }}>{it.value}</span>
                      <span style={{ display: "flex", alignItems: "center", gap: 6 }}><Avatar name={owner.name} color={owner.color} size={22} /><span style={{ fontSize: 10.5, color: "var(--pvt-text-dim)" }}>{it.updatedAt}</span></span>
                    </div>
                  </div>
                );
              })}
              {col.length === 0 && <div style={{ flex: 1, display: "grid", placeItems: "center", color: "var(--pvt-text-dim)", fontSize: 12 }}>Empty</div>}
            </div>
          );
        })}
      </div>
      <LccModal open={!!edit} title="Pipeline card" onClose={() => setEdit(null)} onSubmit={saveEdit} submitLabel="Save">
        {edit && (<>
          <LccField label="Name"><input style={lccInput()} value={edit.name} onChange={(e) => setEdit({ ...edit, name: e.target.value })} /></LccField>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
            <LccField label="Stage"><select style={lccInput()} value={edit.stage} onChange={(e) => setEdit({ ...edit, stage: e.target.value })}>{stages.map((st) => <option key={st} value={st}>{st}</option>)}</select></LccField>
            <LccField label="Owner"><select style={lccInput()} value={edit.owner} onChange={(e) => setEdit({ ...edit, owner: e.target.value })}>{team.map((m) => <option key={m.id} value={m.name.split(" ")[0]}>{m.name.split(" ")[0]}</option>)}</select></LccField>
          </div>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
            <LccField label="Detail / value"><input style={lccInput()} value={edit.value} onChange={(e) => setEdit({ ...edit, value: e.target.value })} /></LccField>
            <LccField label="Note"><input style={lccInput()} value={edit.meta} onChange={(e) => setEdit({ ...edit, meta: e.target.value })} /></LccField>
          </div>
          <button className="pill" onClick={removeItem} style={{ alignSelf: "flex-start", color: "#F25BA7", borderColor: "rgba(216,40,132,0.4)" }}>Remove from pipeline</button>
        </>)}
      </LccModal>
    </div>
  );
}

function TalentAdvance() {
  const [rows, setRows] = window.useDB("talentAdvance");
  const tone = { ready: "approved", "in-progress": "review", "at-risk": "rejected" };
  const CYCLE = { travel: ["pending", "booked", "n/a"], hospitality: ["pending", "done"], techNeeds: ["pending", "received"] };
  const cycle = (id, field) => setRows((xs) => xs.map((r) => {
    if (r.id !== id) return r;
    const opts = CYCLE[field]; const i = opts.indexOf(r[field]);
    return { ...r, [field]: opts[(i + 1) % opts.length] };
  }));
  const cycleStatus = (id) => setRows((xs) => xs.map((r) => r.id === id ? { ...r, status: ({ ready: "in-progress", "in-progress": "at-risk", "at-risk": "ready" })[r.status] } : r));
  const cell = (r, field) => {
    const v = r[field];
    const ok = v === "done" || v === "signed" || v === "received" || v === "booked";
    const na = v === "n/a";
    return <button onClick={() => cycle(r.id, field)} title="Click to advance" style={{ background: "none", border: 0, padding: 0, cursor: "pointer", textAlign: "left", fontSize: 11.5, fontWeight: 700, color: na ? "var(--pvt-text-dim)" : ok ? "#10B5C7" : "#E0B638", textTransform: "capitalize", fontFamily: "var(--pvt-font-body)" }}>{v}</button>;
  };
  return (
    <Section title="Confirmed artists advancing" action={<span className="micro">{rows.length} ARTISTS · TAP A CELL</span>}>
      <div style={{ display: "grid", gridTemplateColumns: "1.4fr .8fr .7fr .7fr .8fr .8fr auto", gap: 10, padding: "0 6px 10px", fontSize: 10, fontWeight: 800, letterSpacing: "0.06em", textTransform: "uppercase", color: "var(--pvt-text-dim)", borderBottom: "1px solid var(--pvt-border-light)" }}>
        <span>Artist</span><span>Set</span><span>Fee</span><span>Travel</span><span>Hosp.</span><span>Tech</span><span>Status</span>
      </div>
      <div className="stat-rows" style={{ marginTop: 8 }}>
        {rows.map((r) => (
          <div key={r.id} className="stat-row" style={{ display: "grid", gridTemplateColumns: "1.4fr .8fr .7fr .7fr .8fr .8fr auto", gap: 10, alignItems: "center" }}>
            <div><div style={{ fontFamily: "var(--pvt-font-display)", fontSize: 13 }}>{r.artist}</div><div style={{ fontSize: 11, color: "var(--pvt-text-dim)" }}>{r.stage} · {r.setTime}</div></div>
            <span style={{ fontSize: 11.5, color: "var(--pvt-muted)" }}>{r.setTime.split(" ")[0]}</span>
            <span style={{ fontSize: 12, fontFamily: "var(--pvt-font-display)" }}>{r.fee}</span>
            {cell(r, "travel")}{cell(r, "hospitality")}{cell(r, "techNeeds")}
            <button onClick={() => cycleStatus(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>
          </div>
        ))}
      </div>
    </Section>
  );
}

function PipelineAnalytics() {
  const [items] = window.useDB("pipelineItems");
  const [stages] = window.useDB("pipelineStages");
  const byStage = stages.map((s) => ({ stage: s, n: items.filter((i) => i.stage === s).length }));
  const max = Math.max(...byStage.map((b) => b.n), 1);
  const total = items.length;
  const advanced = items.filter((i) => i.stage === "Advanced").length;
  return (
    <div style={{ display: "grid", gridTemplateColumns: "minmax(0,1fr) 300px", gap: 16, alignItems: "start" }}>
      <Section title="Funnel across all pipelines">
        <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
          {byStage.map((b) => (
            <div key={b.stage} style={{ display: "grid", gridTemplateColumns: "100px 1fr 40px", gap: 12, alignItems: "center" }}>
              <span style={{ fontSize: 12.5, color: "var(--pvt-muted)" }}>{b.stage}</span>
              <div style={{ height: 26, borderRadius: 8, background: "var(--pvt-surface-light)", overflow: "hidden" }}>
                <div style={{ height: "100%", width: (b.n / max * 100) + "%", borderRadius: 8, background: STAGE_TONE[b.stage], minWidth: 4 }} />
              </div>
              <span style={{ fontFamily: "var(--pvt-font-display)", fontSize: 15, textAlign: "right" }}>{b.n}</span>
            </div>
          ))}
        </div>
      </Section>
      <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
        <Kpi label="In pipeline" num={String(total)} delta="All audiences" glyph="users" />
        <Kpi label="Advanced" num={String(advanced)} delta={Math.round(advanced / total * 100) + "% conversion"} deltaDir="up" glyph="trophy" />
      </div>
    </div>
  );
}

function PipelinesHub({ tab, go }) {
  const [items, setItems] = window.useDB("pipelineItems");
  const [showAdd, setShowAdd] = React.useState(false);
  const [d, setD] = React.useState({ audience: "artist", name: "", meta: "", value: "" });
  const add = () => {
    if (!d.name.trim()) return;
    setItems((xs) => [...xs, { id: d.audience + "-" + Date.now(), audience: d.audience, name: d.name.trim(), stage: "Inquiry", owner: "Kam", value: d.value || "\u2014", meta: d.meta, updatedAt: "now" }]);
    if (window.argtPing) window.argtPing(d.name.trim() + " added to pipeline");
    setShowAdd(false); setD({ audience: "artist", name: "", meta: "", value: "" });
  };
  return (
    <LccPage eyebrow="PIPELINES" title="Pipelines"
      lede="Every audience moves through the same four stages: inquiry, review, confirmed, advanced. Switch the audience, drag work forward, and track confirmed talent down to set times and contracts."
      actions={<><button className="pill" onClick={act("Pipeline exported to CSV")}>Export</button><button className="pill active" onClick={() => setShowAdd(true)}>Add to pipeline</button></>}>
      <LccTabs tabs={LCC_TABS.pipelines} active={tab} onChange={(t) => go("pipelines", t)} />
      {tab === "board" && <StageBoard />}
      {tab === "talent" && <TalentAdvance />}
      {tab === "analytics" && <PipelineAnalytics />}
      <LccModal open={showAdd} title="Add to pipeline" onClose={() => setShowAdd(false)} onSubmit={add} submitLabel="Add">
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
          <LccField label="Audience"><select style={lccInput()} value={d.audience} onChange={(e) => setD({ ...d, audience: e.target.value })}>{AUDIENCES.map((a) => <option key={a.id} value={a.id}>{a.label}</option>)}</select></LccField>
          <LccField label="Detail / value"><input style={lccInput()} placeholder="$24,000 or Main \u00b7 Sat" value={d.value} onChange={(e) => setD({ ...d, value: e.target.value })} /></LccField>
        </div>
        <LccField label="Name"><input style={lccInput()} placeholder="Who or what?" value={d.name} onChange={(e) => setD({ ...d, name: e.target.value })} /></LccField>
        <LccField label="Note"><input style={lccInput()} placeholder="Genre, category, etc." value={d.meta} onChange={(e) => setD({ ...d, meta: e.target.value })} /></LccField>
      </LccModal>
    </LccPage>
  );
}

/* ---------------------------------------------------------------------------
   MARKETING — Comms calendar · Content studio · Planners · Public surfaces.
   --------------------------------------------------------------------------- */
const CHANNEL_TONE = { Instagram: "#D8288C", Email: "#10B5C7", TikTok: "#7A4FBF", Press: "#E0B638" };
function CommsCalendar() {
  const [posts, setPosts] = window.useDB("commsCalendar");
  const tone = { approved: "approved", scheduled: "review", draft: "draft" };
  const cycle = (id) => setPosts((xs) => xs.map((p) => p.id === id ? { ...p, status: ({ draft: "scheduled", scheduled: "approved", approved: "draft" })[p.status] } : p));
  const [edit, setEdit] = React.useState(null);
  const team = window.ARGT_DB.get("launchTeam") || [];
  const save = () => { setPosts((xs) => xs.map((p) => p.id === edit.id ? { ...edit } : p)); if (window.argtPing) window.argtPing("Post updated"); setEdit(null); };
  const del = (id) => setPosts((xs) => xs.filter((p) => p.id !== id));
  return (
    <Section title="Comms calendar" action={<span className="micro">{posts.length} SCHEDULED</span>}>
      <div className="stat-rows">
        {posts.map((p) => (
          <div key={p.id} className="stat-row" style={{ display: "grid", gridTemplateColumns: "64px 110px 1fr auto auto auto", gap: 14, alignItems: "center", cursor: "pointer" }} onClick={() => setEdit({ ...p })} title="Click to edit post">
            <span style={{ fontFamily: "var(--pvt-font-display)", fontSize: 13 }}>{p.scheduledAt}</span>
            <span style={{ display: "inline-flex", alignItems: "center", gap: 7, fontSize: 11.5, fontWeight: 700 }}><span style={{ width: 8, height: 8, borderRadius: "50%", background: CHANNEL_TONE[p.channel] }} />{p.channel}</span>
            <span style={{ fontSize: 13, color: "var(--pvt-muted)" }}>{p.title}</span>
            <span style={{ fontSize: 11, color: "var(--pvt-text-dim)" }}>{p.owner}</span>
            <button onClick={(e) => { e.stopPropagation(); cycle(p.id); }} title="Click to change status" style={{ background: "none", border: 0, padding: 0, cursor: "pointer" }}><Badge kind={tone[p.status]}>{p.status}</Badge></button>
            <SmallBtn title="Delete post" danger onClick={() => del(p.id)}>×</SmallBtn>
          </div>
        ))}
      </div>
      <LccModal open={!!edit} title="Edit post" onClose={() => setEdit(null)} onSubmit={save} submitLabel="Save">
        {edit && (<>
          <LccField label="What's the post?"><input style={lccInput()} value={edit.title} onChange={(e) => setEdit({ ...edit, title: e.target.value })} /></LccField>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 12 }}>
            <LccField label="Date"><input style={lccInput()} value={edit.scheduledAt} onChange={(e) => setEdit({ ...edit, scheduledAt: e.target.value })} /></LccField>
            <LccField label="Channel"><select style={lccInput()} value={edit.channel} onChange={(e) => setEdit({ ...edit, channel: e.target.value })}><option>Instagram</option><option>Email</option><option>TikTok</option><option>Press</option></select></LccField>
            <LccField label="Owner"><select style={lccInput()} value={edit.owner} onChange={(e) => setEdit({ ...edit, owner: e.target.value })}>{team.map((m) => <option key={m.id} value={m.name.split(" ")[0]}>{m.name.split(" ")[0]}</option>)}</select></LccField>
          </div>
        </>)}
      </LccModal>
    </Section>
  );
}

const STUDIO_STAGES = [ { id: "brief", label: "Brief" }, { id: "in-progress", label: "In progress" }, { id: "approved", label: "Approved" }, { id: "published", label: "Published" } ];
function ContentStudio() {
  const [assets, setAssets] = window.useDB("contentStudio");
  const [drag, setDrag] = React.useState(null);
  const [over, setOver] = React.useState(null);
  const [edit, setEdit] = React.useState(null);
  const moveTo = (id, st) => setAssets((xs) => xs.map((a) => a.id === id ? { ...a, stage: st } : a));
  const saveEdit = () => {
    setAssets((xs) => xs.map((a) => a.id === edit.id ? { ...edit } : a));
    if (window.argtPing) window.argtPing(edit.title + " updated");
    setEdit(null);
  };
  return (
    <div style={{ display: "grid", gridTemplateColumns: "repeat(4, minmax(0,1fr))", gap: 12 }}>
      {STUDIO_STAGES.map((st) => {
        const col = assets.filter((a) => a.stage === st.id);
        return (
          <div key={st.id}
            onDragOver={(e) => { e.preventDefault(); if (over !== st.id) setOver(st.id); }}
            onDragLeave={() => setOver((o) => o === st.id ? null : o)}
            onDrop={() => { if (drag) moveTo(drag, st.id); setDrag(null); setOver(null); }}
            style={{ background: over === st.id ? "var(--pvt-surface-mid)" : "var(--pvt-surface)", border: "1px solid " + (over === st.id ? "var(--role-accent)" : "var(--pvt-border-light)"), borderRadius: "var(--r-lg)", padding: 12, display: "flex", flexDirection: "column", gap: 10, minHeight: 200, transition: "border-color 120ms, background 120ms" }}>
            <div style={{ display: "flex", justifyContent: "space-between", padding: "2px 4px" }}><span style={{ fontFamily: "var(--pvt-font-display)", fontSize: 13 }}>{st.label}</span><span className="micro">{col.length}</span></div>
            {col.map((a) => (
              <div key={a.id} draggable
                onDragStart={(e) => { setDrag(a.id); e.dataTransfer.effectAllowed = "move"; }}
                onDragEnd={() => { setDrag(null); setOver(null); }}
                onClick={() => setEdit({ ...a })}
                title="Drag to move · click to edit"
                style={{ background: "var(--pvt-surface-mid)", border: "1px solid var(--pvt-border-light)", borderRadius: "var(--r-md)", padding: 12, cursor: "grab", opacity: drag === a.id ? 0.4 : 1, display: "flex", flexDirection: "column", gap: 8 }}>
                <div style={{ fontFamily: "var(--pvt-font-display)", fontSize: 13, lineHeight: 1.2 }}>{a.title}</div>
                <div style={{ display: "flex", justifyContent: "space-between", fontSize: 11, color: "var(--pvt-text-dim)" }}><span>{a.type}</span><span>{a.due}</span></div>
              </div>
            ))}
          </div>
        );
      })}
      <LccModal open={!!edit} title="Content asset" onClose={() => setEdit(null)} onSubmit={saveEdit} submitLabel="Save">
        {edit && (<>
          <LccField label="Title"><input style={lccInput()} value={edit.title} onChange={(e) => setEdit({ ...edit, title: e.target.value })} /></LccField>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 12 }}>
            <LccField label="Type"><select style={lccInput()} value={edit.type} onChange={(e) => setEdit({ ...edit, type: e.target.value })}><option>Graphic</option><option>Video</option><option>Deck</option><option>Copy</option></select></LccField>
            <LccField label="Stage"><select style={lccInput()} value={edit.stage} onChange={(e) => setEdit({ ...edit, stage: e.target.value })}>{STUDIO_STAGES.map((s) => <option key={s.id} value={s.id}>{s.label}</option>)}</select></LccField>
            <LccField label="Due"><input style={lccInput()} value={edit.due} onChange={(e) => setEdit({ ...edit, due: e.target.value })} /></LccField>
          </div>
        </>)}
      </LccModal>
    </div>
  );
}

function Planners() {
  const [seqs, setSeqs] = window.useDB("emailSequences");
  const [out, setOut] = window.useDB("outreach");
  const stone = { active: "approved", scheduled: "review", draft: "draft", paused: "pending" };
  const otone = { confirmed: "approved", replied: "review", sent: "draft" };
  const pauseSeq = (id) => setSeqs((xs) => xs.map((s) => s.id === id ? { ...s, status: s.status === "paused" ? "active" : "paused" } : s));
  const cycleOut = (id) => setOut((xs) => xs.map((o) => o.id === id ? { ...o, status: ({ sent: "replied", replied: "confirmed", confirmed: "sent" })[o.status] } : o));
  return (
    <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16, alignItems: "start" }}>
      <Section title="Email sequences">
        <div className="stat-rows">
          {seqs.map((s) => (
            <div key={s.id} className="stat-row" style={{ display: "grid", gridTemplateColumns: "1fr auto auto auto", gap: 12, alignItems: "center" }}>
              <div><div style={{ fontFamily: "var(--pvt-font-display)", fontSize: 13 }}>{s.name}</div><div style={{ fontSize: 11, color: "var(--pvt-text-dim)" }}>{s.audience} · {s.sends} sends</div></div>
              <span style={{ fontSize: 11, color: "var(--pvt-text-dim)" }}>{s.nextSend}</span>
              <Badge kind={stone[s.status]}>{s.status}</Badge>
              <button className="pill" onClick={() => pauseSeq(s.id)} style={{ minWidth: 72, justifyContent: "center" }}>{s.status === "paused" ? "Activate" : "Pause"}</button>
            </div>
          ))}
        </div>
      </Section>
      <Section title="Press & community outreach">
        <div className="stat-rows">
          {out.map((o) => (
            <div key={o.id} className="stat-row" style={{ display: "grid", gridTemplateColumns: "auto 1fr auto", gap: 12, alignItems: "center" }}>
              <span style={{ fontSize: 10, fontWeight: 800, textTransform: "uppercase", letterSpacing: "0.05em", color: o.kind === "Press" ? "#E0B638" : "#10B5C7", width: 64 }}>{o.kind}</span>
              <div><div style={{ fontFamily: "var(--pvt-font-display)", fontSize: 13 }}>{o.contact}</div><div style={{ fontSize: 11, color: "var(--pvt-text-dim)" }}>{o.note}</div></div>
              <button onClick={() => cycleOut(o.id)} title="Click to change status" style={{ background: "none", border: 0, padding: 0, cursor: "pointer" }}><Badge kind={otone[o.status]}>{o.status}</Badge></button>
            </div>
          ))}
        </div>
      </Section>
    </div>
  );
}

function PublicSurfaces() {
  const [rows, setRows] = window.useDB("publicSurfaces");
  const tone = { live: "approved", qa: "review", draft: "draft" };
  const cycle = (id) => setRows((xs) => xs.map((r) => r.id === id ? { ...r, status: ({ draft: "qa", qa: "live", live: "draft" })[r.status] } : r));
  const toggleVerified = (id) => setRows((xs) => xs.map((r) => r.id === id ? { ...r, verified: !r.verified } : r));
  const verifiedCount = rows.filter((r) => r.verified).length;
  return (
    <Section title="Public surfaces & claims" action={<span className="micro">{verifiedCount}/{rows.length} VERIFIED</span>}>
      <div style={{ display: "grid", gridTemplateColumns: "40px 1fr 1.4fr 1fr auto", gap: 10, padding: "0 6px 10px", fontSize: 10, fontWeight: 800, letterSpacing: "0.06em", textTransform: "uppercase", color: "var(--pvt-text-dim)", borderBottom: "1px solid var(--pvt-border-light)" }}>
        <span>OK</span><span>Page</span><span>Public claim</span><span>Maps to</span><span>Status</span>
      </div>
      <div className="stat-rows" style={{ marginTop: 8 }}>
        {rows.map((r) => (
          <div key={r.id} className="stat-row" style={{ display: "grid", gridTemplateColumns: "40px 1fr 1.4fr 1fr auto", gap: 10, alignItems: "center" }}>
            <span onClick={() => toggleVerified(r.id)} title={r.verified ? "Verified" : "Mark verified"} style={{ width: 22, height: 22, borderRadius: 7, border: "2px solid " + (r.verified ? "var(--role-accent)" : "var(--pvt-border-light)"), background: r.verified ? "var(--role-accent)" : "transparent", display: "grid", placeItems: "center", color: "#fff", fontSize: 13, fontWeight: 800, cursor: "pointer" }}>{r.verified ? "✓" : ""}</span>
            <div><div style={{ fontFamily: "var(--pvt-font-display)", fontSize: 13 }}>{r.page}</div><div style={{ fontSize: 11, color: "var(--pvt-text-dim)" }}>{r.url}</div></div>
            <span style={{ fontSize: 12.5, color: "var(--pvt-muted)" }}>{r.claim}</span>
            <span style={{ fontSize: 12, color: "var(--pvt-text-dim)" }}>{r.mapsTo}</span>
            <button onClick={() => 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>
          </div>
        ))}
      </div>
    </Section>
  );
}

function MarketingHub({ tab, go }) {
  const [posts, setPosts] = window.useDB("commsCalendar");
  const [showAdd, setShowAdd] = React.useState(false);
  const [d, setD] = React.useState({ scheduledAt: "", channel: "Instagram", title: "" });
  const add = () => {
    if (!d.title.trim()) return;
    setPosts((xs) => [...xs, { id: "cc" + Date.now(), scheduledAt: d.scheduledAt || "TBD", channel: d.channel, title: d.title.trim(), status: "draft", owner: "Jordan" }]);
    if (window.argtPing) window.argtPing("Post added to calendar");
    setShowAdd(false); setD({ scheduledAt: "", channel: "Instagram", title: "" });
  };
  return (
    <LccPage eyebrow="MARKETING" title="Marketing"
      lede="Everything that goes out the door. The comms calendar holds the schedule, the studio moves assets brief to published, planners run sequences and outreach, and public surfaces confirms every promise maps to a real page."
      actions={<><button className="pill" onClick={act("Filtered to this week")}>This week</button><button className="pill active" onClick={() => setShowAdd(true)}>New post</button></>}>
      <LccTabs tabs={LCC_TABS.marketing} active={tab} onChange={(t) => go("marketing", t)} />
      {tab === "comms" && <CommsCalendar />}
      {tab === "studio" && <ContentStudio />}
      {tab === "planners" && <Planners />}
      {tab === "public" && <PublicSurfaces />}
      <LccModal open={showAdd} title="New post" onClose={() => setShowAdd(false)} onSubmit={add} submitLabel="Schedule">
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
          <LccField label="Date"><input style={lccInput()} placeholder="Jun 12" value={d.scheduledAt} onChange={(e) => setD({ ...d, scheduledAt: e.target.value })} /></LccField>
          <LccField label="Channel"><select style={lccInput()} value={d.channel} onChange={(e) => setD({ ...d, channel: e.target.value })}><option>Instagram</option><option>Email</option><option>TikTok</option><option>Press</option></select></LccField>
        </div>
        <LccField label="What's the post?"><input style={lccInput()} placeholder="Headline or summary" value={d.title} onChange={(e) => setD({ ...d, title: e.target.value })} /></LccField>
      </LccModal>
    </LccPage>
  );
}

window.LCC_PAGES = Object.assign(window.LCC_PAGES || {}, {
  pipelines: (tab, go) => <PipelinesHub tab={tab} go={go} />,
  marketing: (tab, go) => <MarketingHub tab={tab} go={go} />,
});
