// =================================================================
// screens-authority.jsx — Authority Engine
//
//   AuthorityEngineScreen   /authority
//     Tab 1: Signal Gap Diagnosis  — AI-powered gap analysis
//     Tab 2: Surface Map           — Browse & assign authority platforms
//     Tab 3: Proof Assets          — Create & manage authority content
//     Tab 4: Distribution          — Platform-specific variants
// =================================================================

// ---------- helpers ----------

const fmtDateA = (iso) => {
  if (!iso) return "—";
  try { return new Date(iso).toLocaleDateString("en-US", { month: "short", day: "numeric", year: "numeric" }); }
  catch { return "—"; }
};

const impactColor = (v) => ({
  high: "var(--good)", medium: "var(--accent)", low: "var(--muted)"
})[v] || "var(--muted)";

const difficultyColor = (v) => ({
  low: "var(--good)", medium: "var(--warn)", high: "var(--bad)"
})[v] || "var(--muted)";

const statusColor = (v) => ({
  completed: "good", in_progress: "accent", pending: "neutral",
  failed: "bad", draft: "neutral", review: "accent",
  approved: "good", published: "good", archived: "neutral",
})[v] || "neutral";

const ASSET_LABELS = {
  case_study: "Case Study", founder_pov: "Founder POV", technical_explainer: "Technical Explainer",
  product_demo_script: "Demo Script", video_storyboard: "Video Storyboard", faq_content: "FAQ",
  investor_note: "Investor Note", security_page: "Security Page", developer_docs: "Dev Docs",
  testimonial: "Testimonial", industry_report: "Industry Report", procurement_note: "Procurement Note",
  press_note: "Press Release", linkedin_post: "LinkedIn Post", carousel: "Carousel",
  video_script: "Video Script", pdf_one_pager: "One-Pager",
};

const PRIORITY_COLORS = { p1: "var(--bad)", p2: "var(--warn)", p3: "var(--muted)" };
const PRIORITY_LABELS = { p1: "P1 — Must have", p2: "P2 — Should have", p3: "P3 — Optional" };

const PRESENCE_COLORS = {
  present: "var(--good)", in_progress: "var(--accent)", not_present: "var(--muted)"
};
const PRESENCE_LABELS = {
  present: "Present", in_progress: "In Progress", not_present: "Not Present"
};

const PLATFORM_TYPE_LABELS = {
  company_data: "Company Data", software_review: "Software Review", product_launch: "Product Launch",
  developer_authority: "Developer", ai_data_authority: "AI / Data", documentation: "Documentation",
  package_ecosystem: "Package Ecosystem", marketplace: "Marketplace", community: "Community",
  security_trust: "Security & Trust", talent_platform: "Talent", b2b_directory: "B2B Directory",
  export_trade: "Export / Trade", certification: "Certification", regulatory: "Regulatory",
  media: "Media", social_content: "Social", thought_leadership: "Thought Leadership",
  review_trust: "Reviews & Trust", app_trust: "App Trust",
};

const GapBadge = ({ status }) => {
  const colors = { present: "var(--good)", partial: "var(--warn)", missing: "var(--bad)" };
  const labels = { present: "Present", partial: "Partial", missing: "Missing" };
  return (
    <span style={{
      display: "inline-flex", alignItems: "center", gap: 5,
      fontSize: 12, fontWeight: 600,
      color: colors[status] || "var(--muted)",
    }}>
      <span style={{
        width: 7, height: 7, borderRadius: "50%",
        background: colors[status] || "var(--muted)",
        display: "inline-block", flexShrink: 0,
      }}/>
      {labels[status] || status}
    </span>
  );
};

// ---------- API helpers ----------

const useAuthoritySurfaces = () => {
  const [surfaces, setSurfaces] = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  const load = React.useCallback(async () => {
    setLoading(true);
    try {
      const data = await window.api.tcall("listAuthoritySurfaces");
      setSurfaces(data || []);
    } catch { setSurfaces([]); }
    setLoading(false);
  }, []);
  React.useEffect(() => { load(); }, [load]);
  React.useEffect(() => {
    const h = () => load();
    window.addEventListener("tenant-changed", h);
    return () => window.removeEventListener("tenant-changed", h);
  }, [load]);
  return { surfaces, loading, reload: load };
};

const useAssignments = () => {
  const [assignments, setAssignments] = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  const load = React.useCallback(async () => {
    setLoading(true);
    try {
      const data = await window.api.tcall("listSurfaceAssignments");
      setAssignments(data || []);
    } catch { setAssignments([]); }
    setLoading(false);
  }, []);
  React.useEffect(() => { load(); }, [load]);
  React.useEffect(() => {
    const h = () => load();
    window.addEventListener("tenant-changed", h);
    return () => window.removeEventListener("tenant-changed", h);
  }, [load]);
  return { assignments, loading, reload: load };
};

const useDiagnoses = () => {
  const [diagnoses, setDiagnoses] = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  const load = React.useCallback(async () => {
    setLoading(true);
    try {
      const data = await window.api.tcall("listDiagnoses");
      setDiagnoses(data || []);
    } catch { setDiagnoses([]); }
    setLoading(false);
  }, []);
  React.useEffect(() => { load(); }, [load]);
  React.useEffect(() => {
    const h = () => load();
    window.addEventListener("tenant-changed", h);
    return () => window.removeEventListener("tenant-changed", h);
  }, [load]);
  return { diagnoses, loading, reload: load };
};

const useProofAssets = () => {
  const [assets, setAssets] = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  const load = React.useCallback(async () => {
    setLoading(true);
    try {
      const data = await window.api.tcall("listProofAssets");
      setAssets(data || []);
    } catch { setAssets([]); }
    setLoading(false);
  }, []);
  React.useEffect(() => { load(); }, [load]);
  React.useEffect(() => {
    const h = () => load();
    window.addEventListener("tenant-changed", h);
    return () => window.removeEventListener("tenant-changed", h);
  }, [load]);
  return { assets, loading, reload: load };
};

// =================================================================
// Tab 1 — Signal Gap Diagnosis
// =================================================================

const DiagnosisTab = () => {
  const { diagnoses, loading, reload } = useDiagnoses();
  const [selected, setSelected] = React.useState(null);
  const [showing, setShowing] = React.useState("list"); // list | new | detail
  const [competitorUrls, setCompetitorUrls] = React.useState("");
  const [running, setRunning] = React.useState(false);

  const latestCompleted = diagnoses.find(d => d.status === "completed");

  const startDiagnosis = async () => {
    setRunning(true);
    try {
      const urls = competitorUrls.split("\n").map(u => u.trim()).filter(Boolean);
      await window.api.tcall("createDiagnosis", { competitor_urls: urls });
      window.__toast("Diagnosis started — AI is scanning your authority signals. This takes ~30 seconds.");
      setShowing("list");
      setCompetitorUrls("");
      setTimeout(() => reload(), 8000);
      setTimeout(() => reload(), 20000);
      setTimeout(() => reload(), 35000);
    } catch (e) {
      window.__toast("Failed to start diagnosis: " + (e?.detail || e?.message || "Unknown error"), "error");
    }
    setRunning(false);
  };

  const viewDiagnosis = (d) => { setSelected(d); setShowing("detail"); };

  if (showing === "new") {
    return (
      <div style={{ display: "flex", flexDirection: "column", gap: "var(--gap)" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
          <Btn kind="ghost" size="sm" onClick={() => setShowing("list")}>← Back</Btn>
          <span style={{ fontWeight: 600, fontSize: 15 }}>New Signal Gap Diagnosis</span>
        </div>
        <Card>
          <div style={{ display: "flex", flexDirection: "column", gap: 18 }}>
            <div>
              <div style={{ fontWeight: 600, fontSize: 14, marginBottom: 4 }}>What is a Signal Gap Diagnosis?</div>
              <div style={{ color: "var(--muted)", fontSize: 13.5, lineHeight: 1.6 }}>
                AI scans your brand's current authority footprint, benchmarks it against competitors, and identifies
                missing proof assets, weak platform presence, and executive authority gaps. Takes ~30 seconds.
              </div>
            </div>
            <div>
              <label style={{ fontWeight: 500, fontSize: 13, display: "block", marginBottom: 6 }}>
                Competitor URLs <span style={{ color: "var(--muted)", fontWeight: 400 }}>(one per line, optional)</span>
              </label>
              <textarea
                value={competitorUrls}
                onChange={e => setCompetitorUrls(e.target.value)}
                placeholder={"https://competitor-a.com\nhttps://competitor-b.com"}
                rows={4}
                style={{
                  width: "100%", boxSizing: "border-box", resize: "vertical",
                  padding: "10px 12px", borderRadius: "var(--r-md)",
                  border: "1px solid var(--line)", background: "var(--input-bg)",
                  color: "var(--ink)", fontSize: 13.5, fontFamily: "var(--mono)",
                  outline: "none",
                }}
              />
              <div style={{ color: "var(--muted)", fontSize: 12.5, marginTop: 4 }}>
                Adding competitor URLs enables peer benchmarking. Skip to diagnose your brand only.
              </div>
            </div>
            <div style={{ display: "flex", gap: 10 }}>
              <Btn kind="primary" loading={running} onClick={startDiagnosis}>Run AI Diagnosis</Btn>
              <Btn kind="ghost" onClick={() => setShowing("list")}>Cancel</Btn>
            </div>
          </div>
        </Card>
      </div>
    );
  }

  if (showing === "detail" && selected) {
    const d = selected;
    const gapEntries = d.gap_map ? Object.entries(d.gap_map) : [];
    return (
      <div style={{ display: "flex", flexDirection: "column", gap: "var(--gap)" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
          <Btn kind="ghost" size="sm" onClick={() => setShowing("list")}>← Back</Btn>
          <span style={{ fontWeight: 600, fontSize: 15 }}>Diagnosis — {fmtDateA(d.created_at)}</span>
          <StatusDot tone={statusColor(d.status)}>{d.status}</StatusDot>
        </div>

        {d.summary && (
          <Card>
            <div style={{ fontWeight: 600, fontSize: 13.5, marginBottom: 8, color: "var(--muted)" }}>EXECUTIVE SUMMARY</div>
            <div style={{ fontSize: 14, lineHeight: 1.7, color: "var(--ink)" }}>{d.summary}</div>
          </Card>
        )}

        {gapEntries.length > 0 && (
          <Card>
            <div style={{ fontWeight: 600, fontSize: 13.5, marginBottom: 14, color: "var(--muted)" }}>SIGNAL GAP MAP</div>
            <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(200px, 1fr))", gap: 12 }}>
              {gapEntries.map(([key, status]) => (
                <div key={key} style={{
                  padding: "12px 14px", borderRadius: "var(--r-md)",
                  background: "var(--panel-2)", border: "1px solid var(--line-2)",
                }}>
                  <div style={{ fontSize: 12, color: "var(--muted)", marginBottom: 6, textTransform: "uppercase", letterSpacing: ".04em" }}>
                    {key.replace(/_/g, " ")}
                  </div>
                  <GapBadge status={status}/>
                </div>
              ))}
            </div>
          </Card>
        )}

        {d.competitor_benchmark && (
          <Card>
            <div style={{ fontWeight: 600, fontSize: 13.5, marginBottom: 12, color: "var(--muted)" }}>COMPETITOR BENCHMARK</div>
            {d.competitor_benchmark.competitor_summary && (
              <div style={{ fontSize: 13.5, color: "var(--ink-2)", marginBottom: 14, lineHeight: 1.6 }}>
                {d.competitor_benchmark.competitor_summary}
              </div>
            )}
            {d.competitor_benchmark.your_relative_gaps?.length > 0 && (
              <div>
                <div style={{ fontWeight: 500, fontSize: 13, marginBottom: 8 }}>Your relative gaps vs competitors:</div>
                <ul style={{ margin: 0, paddingLeft: 20, color: "var(--ink-2)", fontSize: 13.5, lineHeight: 1.8 }}>
                  {d.competitor_benchmark.your_relative_gaps.map((g, i) => <li key={i}>{g}</li>)}
                </ul>
              </div>
            )}
          </Card>
        )}

        {d.executive_authority_gaps?.length > 0 && (
          <Card>
            <div style={{ fontWeight: 600, fontSize: 13.5, marginBottom: 14, color: "var(--muted)" }}>AUTHORITY GAPS</div>
            <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
              {d.executive_authority_gaps.map((g, i) => (
                <div key={i} style={{
                  padding: "12px 14px", borderRadius: "var(--r-md)",
                  background: "var(--panel-2)", border: "1px solid var(--line-2)",
                  display: "flex", gap: 12, alignItems: "flex-start",
                }}>
                  <div style={{
                    marginTop: 2, flexShrink: 0, width: 8, height: 8, borderRadius: "50%",
                    background: impactColor(g.impact),
                  }}/>
                  <div style={{ flex: 1 }}>
                    <div style={{ fontSize: 13.5, color: "var(--ink)", marginBottom: 4 }}>{g.gap}</div>
                    <div style={{ fontSize: 12.5, color: "var(--muted)" }}>Fix: {g.fix}</div>
                  </div>
                  <span style={{ fontSize: 11.5, fontWeight: 600, color: impactColor(g.impact), flexShrink: 0 }}>
                    {(g.impact || "").toUpperCase()}
                  </span>
                </div>
              ))}
            </div>
          </Card>
        )}

        {d.missing_proof_assets?.length > 0 && (
          <Card>
            <div style={{ fontWeight: 600, fontSize: 13.5, marginBottom: 14, color: "var(--muted)" }}>MISSING PROOF ASSETS</div>
            <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
              {d.missing_proof_assets.map((a, i) => (
                <div key={i} style={{
                  padding: "10px 14px", borderRadius: "var(--r-md)",
                  background: "var(--panel-2)", display: "flex", gap: 12, alignItems: "center",
                }}>
                  <span style={{
                    fontSize: 11.5, fontWeight: 600, color: impactColor(a.urgency),
                    background: "var(--panel)", border: "1px solid var(--line-2)",
                    padding: "2px 8px", borderRadius: 999,
                  }}>
                    {(a.asset_type || "").replace(/_/g, " ").toUpperCase()}
                  </span>
                  <span style={{ flex: 1, fontSize: 13.5, color: "var(--ink-2)" }}>{a.reason}</span>
                  <span style={{ fontSize: 11.5, fontWeight: 600, color: impactColor(a.urgency) }}>
                    {(a.urgency || "").toUpperCase()}
                  </span>
                </div>
              ))}
            </div>
          </Card>
        )}

        {d.priority_surfaces?.length > 0 && (
          <Card>
            <div style={{ fontWeight: 600, fontSize: 13.5, marginBottom: 14, color: "var(--muted)" }}>PRIORITY SURFACES</div>
            <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
              {d.priority_surfaces.map((s, i) => (
                <div key={i} style={{
                  padding: "10px 14px", borderRadius: "var(--r-md)",
                  background: "var(--panel-2)", display: "flex", gap: 12, alignItems: "center",
                }}>
                  <span style={{
                    fontSize: 12, fontWeight: 700,
                    color: PRIORITY_COLORS[s.priority?.toLowerCase()] || "var(--muted)",
                    minWidth: 30,
                  }}>{s.priority}</span>
                  <span style={{ fontWeight: 600, fontSize: 13.5, minWidth: 140 }}>{s.surface_name}</span>
                  <span style={{ flex: 1, fontSize: 13, color: "var(--muted)" }}>{s.rationale}</span>
                </div>
              ))}
            </div>
          </Card>
        )}
      </div>
    );
  }

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: "var(--gap)" }}>
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 12 }}>
        <div>
          <div style={{ fontWeight: 600, fontSize: 15 }}>Signal Gap Diagnosis</div>
          <div style={{ color: "var(--muted)", fontSize: 13, marginTop: 2 }}>
            AI scans your brand and competitors to map authority signal gaps.
          </div>
        </div>
        <Btn kind="primary" size="sm" onClick={() => setShowing("new")}>+ Run Diagnosis</Btn>
      </div>

      {loading ? (
        <Card><div style={{ color: "var(--muted)", fontSize: 13.5, padding: "20px 0" }}>Loading…</div></Card>
      ) : diagnoses.length === 0 ? (
        <Card>
          <div style={{ textAlign: "center", padding: "40px 0" }}>
            <div style={{ fontSize: 32, marginBottom: 12 }}>🔬</div>
            <div style={{ fontWeight: 600, fontSize: 15, marginBottom: 6 }}>No diagnoses yet</div>
            <div style={{ color: "var(--muted)", fontSize: 13.5, marginBottom: 20 }}>
              Run your first AI signal gap analysis to see where your brand is missing authority.
            </div>
            <Btn kind="primary" onClick={() => setShowing("new")}>Run First Diagnosis</Btn>
          </div>
        </Card>
      ) : (
        <Card padded={false}>
          <DataTable
            rows={diagnoses}
            keyField="id"
            defaultSort={{ key: "created_at", dir: "desc" }}
            onRowClick={(r) => r.status === "completed" && viewDiagnosis(r)}
            columns={[
              { key: "created_at", label: "Date", render: (r) => fmtDateA(r.created_at) },
              { key: "status", label: "Status", render: (r) => (
                <StatusDot tone={statusColor(r.status)}>{r.status}</StatusDot>
              )},
              { key: "summary", label: "Summary", render: (r) => (
                <span style={{ color: "var(--ink-2)", fontSize: 13 }}>
                  {r.summary ? r.summary.slice(0, 120) + (r.summary.length > 120 ? "…" : "") : (
                    r.status === "pending" || r.status === "in_progress"
                      ? <span style={{ color: "var(--muted)" }}>AI analysis in progress…</span>
                      : "—"
                  )}
                </span>
              )},
              { key: "id", label: "", align: "right", render: (r) => r.status === "completed"
                  ? <Btn kind="ghost" size="sm" onClick={() => viewDiagnosis(r)}>View →</Btn>
                  : null },
            ]}
          />
        </Card>
      )}
    </div>
  );
};

// =================================================================
// Tab 2 — Authority Surface Map
// =================================================================

const SurfaceMapTab = () => {
  const { surfaces, loading: surfacesLoading } = useAuthoritySurfaces();
  const { assignments, loading: assignLoading, reload: reloadAssign } = useAssignments();
  const [filterType, setFilterType] = React.useState("All");
  const [filterAssignment, setFilterAssignment] = React.useState("All");
  const [filterPriority, setFilterPriority] = React.useState("All");
  const [query, setQuery] = React.useState("");
  const [assigning, setAssigning] = React.useState(null);
  const [saving, setSaving] = React.useState(false);
  const [form, setForm] = React.useState({ priority: "p2", presence_status: "not_present", rationale: "", notes: "" });

  const assignedIds = new Set(assignments.map(a => a.surface_id));

  const types = ["All", ...new Set(surfaces.map(s => PLATFORM_TYPE_LABELS[s.platform_type] || s.platform_type))];

  const filtered = surfaces.filter(s => {
    const label = PLATFORM_TYPE_LABELS[s.platform_type] || s.platform_type;
    const matchType = filterType === "All" || label === filterType;
    const assigned = assignments.find(a => a.surface_id === s.id);
    const matchAssignment = filterAssignment === "All"
      || (filterAssignment === "Assigned" && assignedIds.has(s.id))
      || (filterAssignment === "Unassigned" && !assignedIds.has(s.id));
    const matchPriority = filterPriority === "All"
      || (assigned && assigned.priority === filterPriority.toLowerCase());
    const matchQuery = !query || s.name.toLowerCase().includes(query.toLowerCase());
    return matchType && matchAssignment && matchPriority && matchQuery;
  });

  const openAssign = (surface) => {
    const existing = assignments.find(a => a.surface_id === surface.id);
    if (existing) {
      setForm({
        priority: existing.priority,
        presence_status: existing.presence_status,
        rationale: existing.rationale || "",
        notes: existing.notes || "",
      });
      setAssigning({ surface, existing });
    } else {
      setForm({ priority: "p2", presence_status: "not_present", rationale: "", notes: "" });
      setAssigning({ surface, existing: null });
    }
  };

  const saveAssignment = async () => {
    setSaving(true);
    try {
      if (assigning.existing) {
        await window.api.tcall("updateSurfaceAssignment", form, { id: assigning.existing.id });
        window.__toast("Assignment updated");
      } else {
        await window.api.tcall("createSurfaceAssignment", { surface_id: assigning.surface.id, ...form });
        window.__toast(`${assigning.surface.name} added to your surface map`);
      }
      await reloadAssign();
    } catch (e) {
      window.__toast("Save failed: " + (e?.detail || e?.message || "error"), "error");
    }
    setSaving(false);
    setAssigning(null);
  };

  const removeAssignment = async (assignmentId) => {
    try {
      await window.api.tcall("deleteSurfaceAssignment", null, { id: assignmentId });
      window.__toast("Surface removed from your map");
      await reloadAssign();
    } catch (e) {
      window.__toast("Remove failed", "error");
    }
  };

  const enriched = filtered.map(s => ({ ...s, _assignment: assignments.find(a => a.surface_id === s.id) || null }));

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: "var(--gap)" }}>
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 12 }}>
        <div>
          <div style={{ fontWeight: 600, fontSize: 15 }}>Authority Surface Map</div>
          <div style={{ color: "var(--muted)", fontSize: 13, marginTop: 2 }}>
            {assignments.length} surfaces assigned · {surfaces.length} in catalog
          </div>
        </div>
      </div>

      {/* Filters */}
      <div style={{ display: "flex", gap: 10, alignItems: "center", flexWrap: "wrap" }}>
        <div style={{ width: 150 }}><Select value={filterAssignment} onChange={setFilterAssignment} options={["All", "Assigned", "Unassigned"]}/></div>
        <div style={{ width: 120 }}><Select value={filterPriority} onChange={setFilterPriority} options={["All", "p1", "p2", "p3"]}/></div>
        <div style={{ width: 170 }}><Select value={filterType} onChange={setFilterType} options={types}/></div>
        <Input prefix={<IconSearch size={14}/>} placeholder="Search surface…" value={query}
          onChange={e => setQuery(e.target.value)} style={{ width: 200 }}/>
        <span style={{ flex: 1 }}/>
        {!(surfacesLoading || assignLoading) && (
          <span style={{ fontSize: 12.5, color: "var(--muted)" }}>{filtered.length} surface{filtered.length !== 1 ? "s" : ""}</span>
        )}
      </div>

      <Card padded={false}>
        {surfacesLoading || assignLoading ? (
          <div style={{ padding: "48px 20px", textAlign: "center", color: "var(--muted)", fontSize: 13.5 }}>Loading surfaces…</div>
        ) : (
          <DataTable
            rows={enriched}
            keyField="id"
            defaultSort={{ key: "name", dir: "asc" }}
            empty="No surfaces match your filter."
            columns={[
              { key: "name", label: "Platform", render: (r) => (
                <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                  {r._assignment && (
                    <span style={{
                      fontSize: 11, fontWeight: 700,
                      color: PRIORITY_COLORS[r._assignment.priority] || "var(--muted)",
                      background: "var(--panel-2)", border: "1px solid var(--line-2)",
                      padding: "1px 6px", borderRadius: 999, flexShrink: 0,
                    }}>{(r._assignment.priority || "").toUpperCase()}</span>
                  )}
                  <div>
                    <div style={{ fontWeight: 600, color: "var(--ink)" }}>{r.name}</div>
                    {r.url && (
                      <div style={{ fontSize: 11.5, color: "var(--muted)", marginTop: 1 }}>
                        {r.url.replace(/^https?:\/\//, "").replace(/\/$/, "")}
                      </div>
                    )}
                  </div>
                </div>
              )},
              { key: "platform_type", label: "Type", render: (r) => (
                <span style={{ fontSize: 12, color: "var(--muted)", background: "var(--panel-2)", padding: "2px 8px", borderRadius: 999, whiteSpace: "nowrap" }}>
                  {PLATFORM_TYPE_LABELS[r.platform_type] || r.platform_type}
                </span>
              )},
              { key: "stakeholder_lenses", label: "Stakeholders", sortable: false, render: (r) => (
                <span style={{ fontSize: 12.5, color: "var(--ink-2)" }}>
                  {(r.stakeholder_lenses || []).map(l => l.replace(/_/g, " ")).join(", ") || "—"}
                </span>
              )},
              { key: "score_impact", label: "Impact", render: (r) => (
                <span style={{ color: impactColor(r.score_impact), fontWeight: 600, fontSize: 12.5 }}>
                  {(r.score_impact || "—").toUpperCase()}
                </span>
              )},
              { key: "difficulty", label: "Difficulty", render: (r) => (
                <span style={{ color: difficultyColor(r.difficulty), fontSize: 12.5 }}>
                  {r.difficulty || "—"}
                </span>
              )},
              { key: "cost", label: "Cost", render: (r) => (
                <span style={{ fontSize: 12.5, color: "var(--ink-2)", textTransform: "capitalize" }}>{r.cost || "—"}</span>
              )},
              { key: "_status", label: "Status", sortable: false, render: (r) => r._assignment ? (
                <StatusDot tone={r._assignment.presence_status === "present" ? "good" : r._assignment.presence_status === "in_progress" ? "accent" : "neutral"}>
                  {PRESENCE_LABELS[r._assignment.presence_status] || r._assignment.presence_status}
                </StatusDot>
              ) : (
                <span style={{ color: "var(--muted)", fontSize: 12.5 }}>Not assigned</span>
              )},
              { key: "_actions", label: "", sortable: false, render: (r) => (
                <div style={{ display: "inline-flex", gap: 6 }}>
                  <Btn kind={r._assignment ? "ghost" : "soft"} size="sm" onClick={() => openAssign(r)}>
                    {r._assignment ? "Edit" : "+ Assign"}
                  </Btn>
                  {r._assignment && (
                    <Btn kind="ghost" size="sm" onClick={() => removeAssignment(r._assignment.id)}
                         style={{ color: "var(--bad)" }}>✕</Btn>
                  )}
                </div>
              )},
            ]}
          />
        )}
      </Card>

      {assigning && (
        <Modal title={assigning.existing ? `Edit: ${assigning.surface.name}` : `Assign: ${assigning.surface.name}`}
               onClose={() => setAssigning(null)}>
          <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
            {assigning.surface.authority_value && (
              <div style={{ padding: "10px 12px", background: "var(--panel-2)", borderRadius: "var(--r-md)", fontSize: 13, color: "var(--ink-2)", lineHeight: 1.6 }}>
                {assigning.surface.authority_value}
              </div>
            )}
            <FormField label="Priority">
              <Select value={form.priority} onChange={v => setForm(f => ({ ...f, priority: v }))} options={[
                { value: "p1", label: "P1 — Must be present (directly affects trust)" },
                { value: "p2", label: "P2 — Should be present (improves authority)" },
                { value: "p3", label: "P3 — Optional (good for long-term visibility)" },
              ]}/>
            </FormField>
            <FormField label="Presence Status">
              <Select value={form.presence_status} onChange={v => setForm(f => ({ ...f, presence_status: v }))} options={[
                { value: "not_present", label: "Not Present" },
                { value: "in_progress", label: "In Progress" },
                { value: "present", label: "Present" },
              ]}/>
            </FormField>
            <FormField label="Rationale" hint="Why is this surface important for this client?">
              <Input value={form.rationale} onChange={e => setForm(f => ({ ...f, rationale: e.target.value }))}
                     placeholder="e.g. Primary investor validation surface for Series A fundraise"/>
            </FormField>
            <FormField label="Notes">
              <Input value={form.notes} onChange={e => setForm(f => ({ ...f, notes: e.target.value }))}
                     placeholder="e.g. Need 3 customer reviews before submitting"/>
            </FormField>
            {assigning.surface.risk_notes && (
              <Banner tone="warn" icon="⚠️">
                <strong>Risk note:</strong> {assigning.surface.risk_notes}
              </Banner>
            )}
            <div style={{ display: "flex", gap: 10, justifyContent: "flex-end" }}>
              <Btn kind="ghost" onClick={() => setAssigning(null)}>Cancel</Btn>
              <Btn kind="primary" loading={saving} onClick={saveAssignment}>
                {assigning.existing ? "Update" : "Assign Surface"}
              </Btn>
            </div>
          </div>
        </Modal>
      )}
    </div>
  );
};

// =================================================================
// Tab 3 — Proof Assets
// =================================================================

const ProofAssetsTab = () => {
  const { assets, loading, reload } = useProofAssets();
  const [showing, setShowing] = React.useState("list"); // list | new | detail
  const [selected, setSelected] = React.useState(null);
  const [creating, setCreating] = React.useState(false);
  const [generatingVariants, setGeneratingVariants] = React.useState(false);
  const [filterType, setFilterType] = React.useState("All");
  const [filterStatus, setFilterStatus] = React.useState("All");
  const [form, setForm] = React.useState({
    asset_type: "case_study",
    title: "",
    source_material: "",
    generate_ai: true,
  });

  const ASSET_TYPES = Object.entries(ASSET_LABELS);
  const typeLabels = ["All", ...ASSET_TYPES.map(([, l]) => l)];
  const typeValueFromLabel = (label) => {
    const entry = ASSET_TYPES.find(([, l]) => l === label);
    return entry ? entry[0] : null;
  };

  const filtered = assets.filter(a => {
    const typeMatch = filterType === "All" || ASSET_LABELS[a.asset_type] === filterType;
    const statusMatch = filterStatus === "All" || a.status === filterStatus.toLowerCase();
    return typeMatch && statusMatch;
  });

  const createAsset = async () => {
    if (!form.title.trim()) { window.__toast("Title is required", "error"); return; }
    setCreating(true);
    try {
      await window.api.tcall("createProofAsset", form);
      window.__toast(form.generate_ai
        ? "Asset created — AI is generating content (~20 seconds). Refresh to see it."
        : "Asset created as draft.");
      setShowing("list");
      setForm({ asset_type: "case_study", title: "", source_material: "", generate_ai: true });
      setTimeout(() => reload(), 8000);
      setTimeout(() => reload(), 25000);
    } catch (e) {
      window.__toast("Failed: " + (e?.detail || e?.message || "error"), "error");
    }
    setCreating(false);
  };

  const regenerate = async (assetId) => {
    try {
      await window.api.tcall("generateAssetContent", null, { id: assetId });
      window.__toast("Regenerating content… refresh in ~20 seconds.");
      setTimeout(() => reload(), 20000);
    } catch (e) {
      window.__toast("Failed: " + (e?.detail || e?.message || "error"), "error");
    }
  };

  const generateVariants = async (assetId) => {
    setGeneratingVariants(true);
    try {
      await window.api.tcall("generateAssetVariants", {}, { id: assetId });
      window.__toast("Distribution variants generated — 8 formats created.");
      await reload();
      // Re-select to see new variants
      const refreshed = await window.api.tcall("getProofAsset", null, { id: assetId });
      setSelected(refreshed);
    } catch (e) {
      window.__toast("Failed: " + (e?.detail || e?.message || "error"), "error");
    }
    setGeneratingVariants(false);
  };

  const deleteAsset = async (assetId) => {
    if (!window.confirm("Delete this asset and all its variants?")) return;
    try {
      await window.api.tcall("deleteProofAsset", null, { id: assetId });
      window.__toast("Asset deleted");
      setShowing("list");
      await reload();
    } catch (e) {
      window.__toast("Delete failed", "error");
    }
  };

  const viewAsset = async (a) => {
    try {
      const fresh = await window.api.tcall("getProofAsset", null, { id: a.id });
      setSelected(fresh || a);
    } catch { setSelected(a); }
    setShowing("detail");
  };

  const updateStatus = async (assetId, status) => {
    try {
      await window.api.tcall("updateProofAsset", { status }, { id: assetId });
      window.__toast(`Status updated to ${status}`);
      await reload();
      const refreshed = await window.api.tcall("getProofAsset", null, { id: assetId });
      setSelected(refreshed);
    } catch (e) {
      window.__toast("Update failed", "error");
    }
  };

  if (showing === "new") {
    return (
      <div style={{ display: "flex", flexDirection: "column", gap: "var(--gap)" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
          <Btn kind="ghost" size="sm" onClick={() => setShowing("list")}>← Back</Btn>
          <span style={{ fontWeight: 600, fontSize: 15 }}>New Proof Asset</span>
        </div>
        <Card>
          <div style={{ display: "flex", flexDirection: "column", gap: 18 }}>
            <FormField label="Asset Type">
              <Select value={form.asset_type} onChange={v => setForm(f => ({ ...f, asset_type: v }))} options={ASSET_TYPES.map(([v, l]) => ({ value: v, label: l }))}/>
            </FormField>
            <FormField label="Title">
              <Input
                value={form.title}
                onChange={e => setForm(f => ({ ...f, title: e.target.value }))}
                placeholder={`e.g. How ${ASSET_LABELS[form.asset_type] || "we"} helped a fintech scale 3x`}
              />
            </FormField>
            <FormField
              label="Source Material"
              hint="Paste raw content: call notes, bullet points, product details, client story. The more you provide, the better the output."
            >
              <textarea
                value={form.source_material}
                onChange={e => setForm(f => ({ ...f, source_material: e.target.value }))}
                placeholder="Paste raw material here — client notes, key outcomes, product details, founder voice notes…"
                rows={8}
                style={{
                  width: "100%", boxSizing: "border-box", resize: "vertical",
                  padding: "10px 12px", borderRadius: "var(--r-md)",
                  border: "1px solid var(--line)", background: "var(--input-bg)",
                  color: "var(--ink)", fontSize: 13.5, lineHeight: 1.6, outline: "none",
                }}
              />
            </FormField>
            <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
              <input
                type="checkbox"
                id="gen-ai"
                checked={form.generate_ai}
                onChange={e => setForm(f => ({ ...f, generate_ai: e.target.checked }))}
              />
              <label htmlFor="gen-ai" style={{ fontSize: 13.5, cursor: "pointer" }}>
                Generate content with AI immediately
              </label>
            </div>
            <Banner tone="info" icon="ℹ️">
              AI generates a draft based on your source material. All content must be reviewed before publishing.
              Never publish AI-generated claims without verification.
            </Banner>
            <div style={{ display: "flex", gap: 10 }}>
              <Btn kind="primary" loading={creating} onClick={createAsset}>Create Asset</Btn>
              <Btn kind="ghost" onClick={() => setShowing("list")}>Cancel</Btn>
            </div>
          </div>
        </Card>
      </div>
    );
  }

  if (showing === "detail" && selected) {
    const a = selected;
    return (
      <div style={{ display: "flex", flexDirection: "column", gap: "var(--gap)" }}>
        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 10 }}>
          <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
            <Btn kind="ghost" size="sm" onClick={() => setShowing("list")}>← Back</Btn>
            <span style={{ fontWeight: 600, fontSize: 15 }}>{a.title}</span>
            <StatusDot tone={statusColor(a.status)}>{a.status}</StatusDot>
          </div>
          <div style={{ display: "flex", gap: 8 }}>
            {a.status === "draft" && (
              <Btn kind="soft" size="sm" onClick={() => updateStatus(a.id, "review")}>Submit for Review</Btn>
            )}
            {a.status === "review" && (
              <Btn kind="primary" size="sm" onClick={() => updateStatus(a.id, "approved")}>Approve</Btn>
            )}
            {a.status === "approved" && (
              <Btn kind="primary" size="sm" onClick={() => updateStatus(a.id, "published")}>Mark Published</Btn>
            )}
            <Btn kind="ghost" size="sm" onClick={() => regenerate(a.id)}>Regenerate</Btn>
            <Btn kind="ghost" size="sm" style={{ color: "var(--bad)" }} onClick={() => deleteAsset(a.id)}>Delete</Btn>
          </div>
        </div>

        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "var(--gap)" }}>
          <Card>
            <div style={{ fontWeight: 600, fontSize: 13, color: "var(--muted)", marginBottom: 12, textTransform: "uppercase", letterSpacing: ".04em" }}>
              Asset Content
              {a.ai_generated && (
                <span style={{ marginLeft: 8, fontSize: 11, background: "var(--accent-soft)", color: "var(--accent)", padding: "2px 6px", borderRadius: 999 }}>AI Generated</span>
              )}
            </div>
            {a.content ? (
              <div style={{ fontSize: 13.5, lineHeight: 1.7, color: "var(--ink-2)", whiteSpace: "pre-wrap", maxHeight: 400, overflowY: "auto" }}>
                {a.content}
              </div>
            ) : (
              <div style={{ color: "var(--muted)", fontSize: 13, fontStyle: "italic" }}>
                {a.ai_generated === false ? "No content yet. Click Regenerate to generate with AI." : "AI generation in progress…"}
              </div>
            )}
          </Card>
          <div style={{ display: "flex", flexDirection: "column", gap: "var(--gap)" }}>
            <Card>
              <div style={{ fontWeight: 600, fontSize: 13, color: "var(--muted)", marginBottom: 12, textTransform: "uppercase", letterSpacing: ".04em" }}>Source Material</div>
              {a.source_material ? (
                <div style={{ fontSize: 13, lineHeight: 1.6, color: "var(--ink-2)", whiteSpace: "pre-wrap", maxHeight: 150, overflowY: "auto" }}>{a.source_material}</div>
              ) : (
                <div style={{ color: "var(--muted)", fontSize: 13 }}>No source material provided.</div>
              )}
            </Card>
            <Card>
              <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 12 }}>
                <div style={{ fontWeight: 600, fontSize: 13, color: "var(--muted)", textTransform: "uppercase", letterSpacing: ".04em" }}>
                  Distribution Variants ({(a.variants || []).length})
                </div>
                {a.content && (
                  <Btn kind="soft" size="sm" loading={generatingVariants} onClick={() => generateVariants(a.id)}>
                    {(a.variants || []).length > 0 ? "Regenerate" : "Generate 8 Variants"}
                  </Btn>
                )}
              </div>
              {(a.variants || []).length === 0 ? (
                <div style={{ color: "var(--muted)", fontSize: 13 }}>
                  Generate variants to repurpose this asset into LinkedIn posts, carousels, video scripts, investor notes, and more.
                </div>
              ) : (
                <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
                  {(a.variants || []).map(v => (
                    <div key={v.id} style={{
                      padding: "10px 12px", background: "var(--panel-2)",
                      borderRadius: "var(--r-md)", border: "1px solid var(--line-2)",
                    }}>
                      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: v.content ? 6 : 0 }}>
                        <span style={{ fontWeight: 600, fontSize: 13 }}>{v.variant_label}</span>
                        <StatusDot tone={statusColor(v.status)}>{v.status}</StatusDot>
                      </div>
                      {v.content && (
                        <div style={{ fontSize: 12.5, color: "var(--ink-2)", lineHeight: 1.5, maxHeight: 80, overflowY: "auto" }}>
                          {v.content.slice(0, 200)}{v.content.length > 200 ? "…" : ""}
                        </div>
                      )}
                    </div>
                  ))}
                </div>
              )}
            </Card>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: "var(--gap)" }}>
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 12 }}>
        <div>
          <div style={{ fontWeight: 600, fontSize: 15 }}>Proof Assets</div>
          <div style={{ color: "var(--muted)", fontSize: 13, marginTop: 2 }}>
            Convert internal knowledge into external authority content.
          </div>
        </div>
        <Btn kind="primary" size="sm" onClick={() => setShowing("new")}>+ Create Asset</Btn>
      </div>

      {/* Filters */}
      <div style={{ display: "flex", gap: 10, alignItems: "center", flexWrap: "wrap" }}>
        <div style={{ width: 160 }}><Select value={filterStatus} onChange={setFilterStatus} options={["All", "Draft", "Review", "Approved", "Published"]}/></div>
        <div style={{ width: 180 }}><Select value={filterType} onChange={v => setFilterType(v)} options={typeLabels}/></div>
        <span style={{ flex: 1 }}/>
        {!loading && <span style={{ fontSize: 12.5, color: "var(--muted)" }}>{filtered.length} asset{filtered.length !== 1 ? "s" : ""}</span>}
      </div>

      <Card padded={false}>
        {loading ? (
          <div style={{ padding: "48px 20px", textAlign: "center", color: "var(--muted)", fontSize: 13.5 }}>Loading assets…</div>
        ) : filtered.length === 0 ? (
          <div style={{ textAlign: "center", padding: "48px 20px" }}>
            <div style={{ fontSize: 32, marginBottom: 12 }}>✍️</div>
            <div style={{ fontWeight: 600, fontSize: 15, marginBottom: 6 }}>No proof assets yet</div>
            <div style={{ color: "var(--muted)", fontSize: 13.5, marginBottom: 20 }}>
              Create your first authority asset — case studies, founder POVs, technical explainers, and more.
            </div>
            <Btn kind="primary" onClick={() => setShowing("new")}>Create First Asset</Btn>
          </div>
        ) : (
          <DataTable
            rows={filtered}
            keyField="id"
            defaultSort={{ key: "created_at", dir: "desc" }}
            onRowClick={(r) => viewAsset(r)}
            columns={[
              { key: "title", label: "Asset", render: (r) => (
                <div>
                  <strong style={{ display: "block" }}>{r.title}</strong>
                  <span style={{ fontSize: 12, color: "var(--muted)" }}>{ASSET_LABELS[r.asset_type] || r.asset_type}</span>
                </div>
              )},
              { key: "status", label: "Status", render: (r) => (
                <StatusDot tone={statusColor(r.status)}>{r.status}</StatusDot>
              )},
              { key: "ai_generated", label: "Source", render: (r) => (
                <span style={{ fontSize: 12.5, color: "var(--muted)" }}>{r.ai_generated ? "AI Generated" : "Manual"}</span>
              )},
              { key: "variants", label: "Variants", align: "right", render: (r) => (
                <span style={{ fontSize: 12.5, color: (r.variants || []).length > 0 ? "var(--good)" : "var(--muted)" }}>
                  {(r.variants || []).length > 0 ? `${r.variants.length} variant${r.variants.length !== 1 ? "s" : ""}` : "—"}
                </span>
              )},
              { key: "created_at", label: "Created", render: (r) => (
                <span style={{ color: "var(--muted)", fontSize: 12.5 }}>{fmtDateA(r.created_at)}</span>
              )},
              { key: "_actions", label: "", sortable: false, render: (r) => (
                <Btn kind="ghost" size="sm" onClick={(e) => { e.stopPropagation(); viewAsset(r); }}>View →</Btn>
              )},
            ]}
          />
        )}
      </Card>
    </div>
  );
};

// =================================================================
// =================================================================
// CatalogTab — surface catalog management (superadmin / consultant)
// =================================================================

const PLATFORM_TYPES = [
  "company_data","software_review","product_launch","developer_authority","ai_data_authority",
  "documentation","package_ecosystem","marketplace","community","security_trust","talent_platform",
  "b2b_directory","export_trade","certification","regulatory","media","social_content",
  "thought_leadership","review_trust","app_trust",
];
const PRIORITIES = ["p1","p2","p3"];
const IMPACTS = ["high","medium","low"];
const DIFFICULTIES = ["low","medium","high"];
const COSTS = ["free","paid","premium"];
const OWNER_TYPES = ["client","consultant","partner"];
const COMMON_VERTICALS = [
  "financial_services","payments","wealthtech","insurtech","regtech","lending_bnpl","neobanking",
  "open_banking","remittance","b2b_saas","enterprise_saas","ecommerce","healthtech","edtech","all",
];
const COMMON_REGIONS = ["global","india","gcc","uk","europe","usa","apac","mena","africa","latam"];
const STAKEHOLDER_OPTIONS = ["investor","enterprise_buyer","technical_buyer","consumer","regulator_partner","talent"];

const TagInput = ({ value, onChange, suggestions = [] }) => {
  const [input, setInput] = React.useState("");
  const add = (v) => {
    const tag = v.trim().toLowerCase().replace(/\s+/g, "_");
    if (tag && !value.includes(tag)) onChange([...value, tag]);
    setInput("");
  };
  return (
    <div style={{ display: "flex", flexWrap: "wrap", gap: 6, padding: "6px 8px", border: "1px solid var(--line)", borderRadius: "var(--r-sm)", background: "var(--panel)", minHeight: 38 }}>
      {value.map(t => (
        <span key={t} style={{ display: "inline-flex", alignItems: "center", gap: 4, padding: "2px 8px", borderRadius: 12, background: "var(--accent-soft)", color: "var(--accent)", fontSize: 12, fontWeight: 600 }}>
          {t}
          <button onClick={() => onChange(value.filter(x => x !== t))} style={{ background: "none", border: "none", cursor: "pointer", padding: 0, color: "var(--accent)", fontSize: 13, lineHeight: 1 }}>×</button>
        </span>
      ))}
      <input
        value={input}
        onChange={e => setInput(e.target.value)}
        onKeyDown={e => { if (e.key === "Enter" || e.key === ",") { e.preventDefault(); add(input); } }}
        placeholder="type + enter"
        style={{ border: "none", outline: "none", background: "transparent", fontSize: 12.5, minWidth: 80, color: "var(--ink)" }}
      />
      {suggestions.length > 0 && input.length === 0 && (
        <div style={{ width: "100%", display: "flex", flexWrap: "wrap", gap: 4, marginTop: 4 }}>
          {suggestions.filter(s => !value.includes(s)).map(s => (
            <button key={s} onClick={() => add(s)} style={{ padding: "2px 8px", borderRadius: 10, border: "1px solid var(--line)", background: "var(--hover)", color: "var(--muted)", fontSize: 11, cursor: "pointer" }}>
              + {s}
            </button>
          ))}
        </div>
      )}
    </div>
  );
};

const EMPTY_FORM = {
  name: "", url: "", platform_type: "community",
  industry_verticals: [], stakeholder_lenses: [],
  authority_value: "", submission_method: "", evidence_needed: "",
  difficulty: "medium", cost: "free", score_impact: "high",
  update_frequency: "", risk_notes: "", owner_type: "consultant",
  priority: "p1", regions: [],
  has_content_api: false, api_docs_url: "", content_api_notes: "",
  is_active: true, auto_assign: true,
};

const SurfaceFormModal = ({ surface, onClose, onSaved }) => {
  const [form, setForm] = React.useState(surface ? {
    ...EMPTY_FORM,
    name: surface.name || "",
    url: surface.url || "",
    platform_type: surface.platform_type || "community",
    industry_verticals: surface.industry_verticals || [],
    stakeholder_lenses: surface.stakeholder_lenses || [],
    authority_value: surface.authority_value || "",
    submission_method: surface.submission_method || "",
    evidence_needed: surface.evidence_needed || "",
    difficulty: surface.difficulty || "medium",
    cost: surface.cost || "free",
    score_impact: surface.score_impact || "high",
    update_frequency: surface.update_frequency || "",
    risk_notes: surface.risk_notes || "",
    owner_type: surface.owner_type || "consultant",
    priority: surface.priority || "p1",
    regions: surface.regions || [],
    has_content_api: surface.has_content_api || false,
    api_docs_url: surface.api_docs_url || "",
    content_api_notes: surface.content_api_notes || "",
    is_active: surface.is_active !== false,
    auto_assign: false,
  } : { ...EMPTY_FORM });

  const [saving, setSaving] = React.useState(false);
  const [err, setErr] = React.useState(null);
  const [planResult, setPlanResult] = React.useState(null);
  const [regenerating, setRegenerating] = React.useState(false);
  const [reviewPlans, setReviewPlans] = React.useState({
    competitor: surface?.competitor_review_plan || null,
    brand: surface?.brand_review_plan || null,
  });
  const [reviewTab, setReviewTab] = React.useState("competitor");
  const isEdit = !!surface;

  const set = (k, v) => setForm(f => ({ ...f, [k]: v }));

  const regeneratePlans = async () => {
    if (!surface?.id) return;
    setRegenerating(true); setErr(null);
    try {
      const updated = await window.api.call("catalogRegenerateReviews", { id: surface.id });
      setReviewPlans({ competitor: updated.competitor_review_plan, brand: updated.brand_review_plan });
      onSaved(updated, null);
    } catch (e) {
      setErr(e?.body?.detail || e?.message || "Regeneration failed");
    }
    setRegenerating(false);
  };

  const save = async () => {
    if (!form.name.trim()) { setErr("Name is required"); return; }
    setSaving(true); setErr(null);
    try {
      let result;
      if (isEdit) {
        result = await window.api.call("catalogUpdateSurface", { id: surface.id }, form);
        onSaved(result, null);
      } else {
        const resp = await window.api.call("catalogCreateSurface", null, form);
        setPlanResult(resp.auto_plan);
        onSaved(resp.surface, resp.auto_plan);
      }
    } catch (e) {
      setErr(e?.body?.detail || e?.message || "Save failed");
    }
    setSaving(false);
  };

  const Field = ({ label, children, half }) => (
    <div style={{ gridColumn: half ? "span 1" : "span 2" }}>
      <div style={{ fontSize: 12, color: "var(--muted)", marginBottom: 5, fontWeight: 500 }}>{label}</div>
      {children}
    </div>
  );

  const input = (k, opts = {}) => (
    <input
      value={form[k]}
      onChange={e => set(k, e.target.value)}
      placeholder={opts.placeholder || ""}
      style={{ width: "100%", padding: "7px 10px", border: "1px solid var(--line)", borderRadius: "var(--r-sm)", background: "var(--panel)", color: "var(--ink)", fontSize: 13, outline: "none", boxSizing: "border-box" }}
    />
  );

  const textarea = (k, rows = 2) => (
    <textarea
      value={form[k]}
      onChange={e => set(k, e.target.value)}
      rows={rows}
      style={{ width: "100%", padding: "7px 10px", border: "1px solid var(--line)", borderRadius: "var(--r-sm)", background: "var(--panel)", color: "var(--ink)", fontSize: 13, outline: "none", boxSizing: "border-box", resize: "vertical", fontFamily: "inherit" }}
    />
  );

  const select = (k, options) => (
    <select
      value={form[k]}
      onChange={e => set(k, e.target.value)}
      style={{ width: "100%", padding: "7px 10px", border: "1px solid var(--line)", borderRadius: "var(--r-sm)", background: "var(--panel)", color: "var(--ink)", fontSize: 13, outline: "none" }}
    >
      {options.map(o => <option key={o} value={o}>{o}</option>)}
    </select>
  );

  const toggle = (k, label) => (
    <label style={{ display: "flex", alignItems: "center", gap: 8, cursor: "pointer", fontSize: 13 }}>
      <input type="checkbox" checked={form[k]} onChange={e => set(k, e.target.checked)} style={{ width: 15, height: 15 }}/>
      {label}
    </label>
  );

  return (
    <div style={{ position: "fixed", inset: 0, background: "rgba(0,0,0,.45)", zIndex: 200, display: "flex", alignItems: "flex-start", justifyContent: "center", padding: "40px 20px", overflowY: "auto" }}>
      <div style={{ background: "var(--panel)", borderRadius: "var(--r-lg)", width: "100%", maxWidth: 720, boxShadow: "var(--shadow-modal)", padding: "var(--pad)" }}>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 20 }}>
          <div>
            <div style={{ fontSize: 17, fontWeight: 700 }}>{isEdit ? "Edit Surface" : "Add Surface to Catalog"}</div>
            <div style={{ fontSize: 12.5, color: "var(--muted)", marginTop: 3 }}>
              {isEdit ? "Update this platform's catalog entry." : "This surface will be added to the global catalog and auto-planned for matching tenants."}
            </div>
          </div>
          <button onClick={onClose} style={{ background: "none", border: "none", fontSize: 20, cursor: "pointer", color: "var(--muted)", padding: "0 4px" }}>×</button>
        </div>

        {err && <div style={{ padding: "10px 14px", background: "var(--bad)", color: "#fff", borderRadius: "var(--r-sm)", fontSize: 13, marginBottom: 16 }}>{err}</div>}

        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14 }}>
          <Field label="Surface Name *">
            {input("name", { placeholder: "e.g. Money20/20 Europe" })}
          </Field>
          <Field label="URL" half>
            {input("url", { placeholder: "https://..." })}
          </Field>
          <Field label="Platform Type" half>
            {select("platform_type", PLATFORM_TYPES)}
          </Field>
          <Field label="Priority" half>
            {select("priority", PRIORITIES)}
          </Field>
          <Field label="Score Impact" half>
            {select("score_impact", IMPACTS)}
          </Field>
          <Field label="Difficulty" half>
            {select("difficulty", DIFFICULTIES)}
          </Field>
          <Field label="Cost" half>
            {select("cost", COSTS)}
          </Field>
          <Field label="Owner Type" half>
            {select("owner_type", OWNER_TYPES)}
          </Field>
          <Field label="Industry Verticals">
            <TagInput value={form.industry_verticals} onChange={v => set("industry_verticals", v)} suggestions={COMMON_VERTICALS}/>
          </Field>
          <Field label="Regions">
            <TagInput value={form.regions} onChange={v => set("regions", v)} suggestions={COMMON_REGIONS}/>
          </Field>
          <Field label="Stakeholder Lenses">
            <TagInput value={form.stakeholder_lenses} onChange={v => set("stakeholder_lenses", v)} suggestions={STAKEHOLDER_OPTIONS}/>
          </Field>
          <Field label="Update Frequency" half>
            {input("update_frequency", { placeholder: "e.g. annually, quarterly" })}
          </Field>
          <Field label="Authority Value">
            {textarea("authority_value", 2)}
          </Field>
          <Field label="Submission Method">
            {textarea("submission_method", 2)}
          </Field>
          <Field label="Evidence Needed">
            {textarea("evidence_needed", 2)}
          </Field>
          <Field label="Risk Notes">
            {textarea("risk_notes", 2)}
          </Field>
          <Field label="Options">
            <div style={{ display: "flex", flexDirection: "column", gap: 10, paddingTop: 4 }}>
              {toggle("is_active", "Active (visible in catalog)")}
              {toggle("has_content_api", "Has Content API")}
              {!isEdit && toggle("auto_assign", "Auto-assign to matching clients on create")}
            </div>
          </Field>
          {form.has_content_api && (
            <Field label="API Docs URL" half>
              {input("api_docs_url", { placeholder: "https://..." })}
            </Field>
          )}
          {form.has_content_api && (
            <Field label="Content API Notes">
              {textarea("content_api_notes", 2)}
            </Field>
          )}
        </div>

        {isEdit && (
          <div style={{ marginTop: 24, borderTop: "1px solid var(--line)", paddingTop: 20 }}>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 14 }}>
              <div>
                <div style={{ fontSize: 14, fontWeight: 700 }}>Review Plans</div>
                <div style={{ fontSize: 12, color: "var(--muted)", marginTop: 2 }}>
                  AI-generated playbooks for competitor monitoring and brand building on this surface
                </div>
              </div>
              <button onClick={regeneratePlans} disabled={regenerating}
                style={{ padding: "6px 14px", borderRadius: "var(--r-sm)", border: "1px solid var(--accent)", background: "transparent", color: "var(--accent)", fontSize: 12, fontWeight: 600, cursor: regenerating ? "wait" : "pointer", opacity: regenerating ? .6 : 1, whiteSpace: "nowrap" }}>
                {regenerating ? "Generating…" : reviewPlans.competitor ? "↺ Regenerate" : "✦ Generate Plans"}
              </button>
            </div>

            {!reviewPlans.competitor && !reviewPlans.brand ? (
              <div style={{ padding: "20px", textAlign: "center", background: "var(--panel-2)", borderRadius: "var(--r-md)", color: "var(--muted)", fontSize: 13 }}>
                No review plans generated yet. Click "Generate Plans" to create AI-powered playbooks for this surface.
              </div>
            ) : (
              <div>
                <div style={{ display: "flex", gap: 0, marginBottom: 12, borderBottom: "1px solid var(--line)" }}>
                  {[["competitor", "Competitor Review"], ["brand", "Brand Review"]].map(([id, label]) => (
                    <button key={id} onClick={() => setReviewTab(id)}
                      style={{ padding: "7px 16px", border: "none", borderBottom: reviewTab === id ? "2px solid var(--accent)" : "2px solid transparent", background: "transparent", color: reviewTab === id ? "var(--accent)" : "var(--muted)", fontSize: 13, fontWeight: reviewTab === id ? 700 : 400, cursor: "pointer", marginBottom: -1 }}>
                      {label}
                    </button>
                  ))}
                </div>
                <pre style={{ whiteSpace: "pre-wrap", fontSize: 12.5, color: "var(--ink)", lineHeight: 1.6, background: "var(--panel-2)", padding: "14px 16px", borderRadius: "var(--r-md)", margin: 0, fontFamily: "inherit", maxHeight: 320, overflowY: "auto" }}>
                  {reviewTab === "competitor" ? (reviewPlans.competitor || "Not generated yet.") : (reviewPlans.brand || "Not generated yet.")}
                </pre>
              </div>
            )}
          </div>
        )}

        <div style={{ display: "flex", justifyContent: "flex-end", gap: 10, marginTop: 20 }}>
          <button onClick={onClose} style={{ padding: "8px 18px", borderRadius: "var(--r-sm)", border: "1px solid var(--line)", background: "var(--panel)", color: "var(--muted)", fontSize: 13, cursor: "pointer" }}>Cancel</button>
          <button onClick={save} disabled={saving} style={{ padding: "8px 20px", borderRadius: "var(--r-sm)", border: "none", background: "var(--accent)", color: "#fff", fontSize: 13, fontWeight: 600, cursor: saving ? "wait" : "pointer", opacity: saving ? .7 : 1 }}>
            {saving ? "Saving…" : isEdit ? "Save Changes" : "Add Surface"}
          </button>
        </div>
      </div>
    </div>
  );
};

const CatalogTab = () => {
  const [surfaces, setSurfaces] = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  const [search, setSearch] = React.useState("");
  const [filterType, setFilterType] = React.useState("all");
  const [showForm, setShowForm] = React.useState(false);
  const [editing, setEditing] = React.useState(null);
  const [lastPlan, setLastPlan] = React.useState(null);

  const load = React.useCallback(async () => {
    setLoading(true);
    try {
      const data = await window.api.call("catalogListSurfaces");
      setSurfaces(data || []);
    } catch { setSurfaces([]); }
    setLoading(false);
  }, []);

  React.useEffect(() => { load(); }, [load]);

  const onSaved = (surface, plan) => {
    if (plan) setLastPlan(plan);
    setSurfaces(prev => {
      const idx = prev.findIndex(s => s.id === surface.id);
      if (idx >= 0) { const next = [...prev]; next[idx] = surface; return next; }
      return [surface, ...prev];
    });
    setShowForm(false);
    setEditing(null);
  };

  const types = React.useMemo(() => ["all", ...new Set(surfaces.map(s => s.platform_type))].sort(), [surfaces]);

  const filtered = surfaces.filter(s => {
    if (filterType !== "all" && s.platform_type !== filterType) return false;
    if (search && !s.name.toLowerCase().includes(search.toLowerCase())) return false;
    return true;
  });

  const priBg = { p1: "var(--bad)", p2: "var(--warn)", p3: "var(--muted)" };

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
      {lastPlan && (
        <div style={{ padding: "12px 16px", background: "var(--good-soft)", borderRadius: "var(--r-md)", display: "flex", justifyContent: "space-between", alignItems: "center" }}>
          <div style={{ fontSize: 13.5, color: "var(--good)", fontWeight: 600 }}>
            Surface added — auto-planned for {lastPlan.tenants_assigned} tenant{lastPlan.tenants_assigned !== 1 ? "s" : ""} with matching industry
          </div>
          <button onClick={() => setLastPlan(null)} style={{ background: "none", border: "none", cursor: "pointer", color: "var(--good)", fontSize: 16 }}>×</button>
        </div>
      )}

      <div style={{ display: "flex", gap: 10, alignItems: "center" }}>
        <input
          value={search} onChange={e => setSearch(e.target.value)}
          placeholder="Search surfaces…"
          style={{ flex: 1, padding: "7px 12px", border: "1px solid var(--line)", borderRadius: "var(--r-sm)", background: "var(--panel)", color: "var(--ink)", fontSize: 13, outline: "none" }}
        />
        <select value={filterType} onChange={e => setFilterType(e.target.value)}
          style={{ padding: "7px 10px", border: "1px solid var(--line)", borderRadius: "var(--r-sm)", background: "var(--panel)", color: "var(--ink)", fontSize: 13, outline: "none" }}>
          {types.map(t => <option key={t} value={t}>{t === "all" ? "All types" : PLATFORM_TYPE_LABELS[t] || t}</option>)}
        </select>
        <button onClick={() => { setEditing(null); setShowForm(true); }}
          style={{ padding: "7px 16px", borderRadius: "var(--r-sm)", border: "none", background: "var(--accent)", color: "#fff", fontSize: 13, fontWeight: 600, cursor: "pointer", whiteSpace: "nowrap" }}>
          + Add Surface
        </button>
      </div>

      <div style={{ fontSize: 12.5, color: "var(--muted)" }}>
        {filtered.length} of {surfaces.length} surfaces
      </div>

      {loading ? (
        <div style={{ textAlign: "center", padding: 40, color: "var(--muted)", fontSize: 13.5 }}>Loading catalog…</div>
      ) : (
        <div style={{ border: "1px solid var(--line)", borderRadius: "var(--r-md)", overflow: "hidden" }}>
          <table style={{ width: "100%", borderCollapse: "collapse", fontSize: 13 }}>
            <thead>
              <tr style={{ background: "var(--panel-2)", borderBottom: "1px solid var(--line)" }}>
                {["Surface", "Type", "Priority", "Impact", "Regions", "Verticals", "Status", ""].map(h => (
                  <th key={h} style={{ padding: "10px 12px", textAlign: "left", fontWeight: 600, fontSize: 12, color: "var(--muted)", whiteSpace: "nowrap" }}>{h}</th>
                ))}
              </tr>
            </thead>
            <tbody>
              {filtered.map((s, i) => (
                <tr key={s.id} style={{ borderBottom: "1px solid var(--line-2)", background: i % 2 === 0 ? "var(--panel)" : "var(--panel-2)" }}>
                  <td style={{ padding: "10px 12px", fontWeight: 600 }}>
                    <div>{s.name}</div>
                    {s.url && <div style={{ fontSize: 11, color: "var(--muted)", marginTop: 2 }}>{s.url}</div>}
                  </td>
                  <td style={{ padding: "10px 12px", color: "var(--muted)", fontSize: 12 }}>{PLATFORM_TYPE_LABELS[s.platform_type] || s.platform_type}</td>
                  <td style={{ padding: "10px 12px" }}>
                    <span style={{ padding: "2px 8px", borderRadius: 10, background: priBg[s.priority] + "22", color: priBg[s.priority], fontSize: 11, fontWeight: 700 }}>
                      {(s.priority || "").toUpperCase()}
                    </span>
                  </td>
                  <td style={{ padding: "10px 12px", color: impactColor(s.score_impact), fontWeight: 600, fontSize: 12 }}>{s.score_impact}</td>
                  <td style={{ padding: "10px 12px", fontSize: 11.5, color: "var(--muted)", maxWidth: 120 }}>
                    {(s.regions || []).join(", ") || "—"}
                  </td>
                  <td style={{ padding: "10px 12px", fontSize: 11.5, color: "var(--muted)", maxWidth: 160 }}>
                    {(s.industry_verticals || []).slice(0, 3).join(", ")}{(s.industry_verticals || []).length > 3 ? "…" : ""}
                  </td>
                  <td style={{ padding: "10px 12px" }}>
                    <span style={{ fontSize: 11, fontWeight: 600, color: s.is_active ? "var(--good)" : "var(--muted)" }}>
                      {s.is_active ? "Active" : "Inactive"}
                    </span>
                  </td>
                  <td style={{ padding: "10px 12px" }}>
                    <button onClick={() => { setEditing(s); setShowForm(true); }}
                      style={{ padding: "4px 12px", borderRadius: "var(--r-sm)", border: "1px solid var(--line)", background: "var(--panel)", color: "var(--ink)", fontSize: 12, cursor: "pointer" }}>
                      Edit
                    </button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}

      {showForm && (
        <SurfaceFormModal
          surface={editing}
          onClose={() => { setShowForm(false); setEditing(null); }}
          onSaved={onSaved}
        />
      )}
    </div>
  );
};

// Main: AuthorityEngineScreen
// =================================================================

const AuthorityEngineScreen = () => {
  const [tab, setTab] = React.useState("diagnosis");
  const { assignments } = useAssignments();
  const { assets } = useProofAssets();
  const { diagnoses } = useDiagnoses();

  const role = window.session?.role;
  const canManageCatalog = role === "superadmin" || role === "consultant";

  const p1Count = assignments.filter(a => a.priority === "p1").length;
  const presentCount = assignments.filter(a => a.presence_status === "present").length;
  const approvedAssets = assets.filter(a => a.status === "approved" || a.status === "published").length;
  const latestDiagnosis = diagnoses.find(d => d.status === "completed");

  const TABS = [
    { id: "diagnosis", label: "Signal Diagnosis" },
    { id: "surfaces", label: "Surface Map" },
    { id: "assets", label: "Proof Assets" },
    ...(canManageCatalog ? [{ id: "catalog", label: "Manage Catalog" }] : []),
  ];

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: "var(--gap)" }}>
      <ScreenHeader
        title="Authority Engine"
        subtitle="Identify authority signal gaps, publish proof assets on the right surfaces, and track credibility improvement."
      />

      {/* KPI strip */}
      <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: "var(--gap)" }}>
        {[
          { label: "Surfaces Assigned", value: assignments.length, sub: `${p1Count} P1 surfaces` },
          { label: "Present on Platform", value: presentCount, sub: `of ${assignments.length} assigned` },
          { label: "Proof Assets", value: assets.length, sub: `${approvedAssets} approved / published` },
          { label: "Diagnoses Run", value: diagnoses.length, sub: latestDiagnosis ? `Last: ${fmtDateA(latestDiagnosis.created_at)}` : "None yet" },
        ].map(kpi => (
          <Card key={kpi.label}>
            <div style={{ display: "flex", flexDirection: "column", gap: 4 }}>
              <div style={{ fontSize: 12.5, color: "var(--muted)", letterSpacing: ".02em" }}>{kpi.label}</div>
              <div style={{ fontSize: 28, fontWeight: 700, color: "var(--ink)", fontFamily: "var(--mono)", letterSpacing: "-.03em" }}>
                {kpi.value}
              </div>
              <div style={{ fontSize: 12, color: "var(--muted)" }}>{kpi.sub}</div>
            </div>
          </Card>
        ))}
      </div>

      {/* Tabs */}
      <div style={{ display: "flex", gap: 0, borderBottom: "1px solid var(--line)", marginBottom: -4 }}>
        {TABS.map(t => (
          <button key={t.id} onClick={() => setTab(t.id)} style={{
            padding: "10px 18px", background: "none", border: "none",
            borderBottom: tab === t.id ? "2px solid var(--accent)" : "2px solid transparent",
            color: tab === t.id ? "var(--accent)" : "var(--muted)",
            fontWeight: tab === t.id ? 600 : 400,
            fontSize: 13.5, cursor: "pointer", transition: "color .15s",
          }}>
            {t.label}
          </button>
        ))}
      </div>

      {/* Tab content */}
      <div>
        {tab === "diagnosis" && <DiagnosisTab/>}
        {tab === "surfaces" && <SurfaceMapTab/>}
        {tab === "assets" && <ProofAssetsTab/>}
        {tab === "catalog" && <CatalogTab/>}
      </div>
    </div>
  );
};
