// =================================================================
// screens-brand.jsx — Brand Dashboard
//
//   BrandDashboardScreen   /brand-dashboard
//     Score card: CredAxis index, band, 3 component bars
//     Tab 1: My Platforms    — assigned surfaces with presence status
//     Tab 2: Suggested       — unassigned fintech surfaces by P1/P2/P3
//     Tab 3: Peer Benchmark  — peer group selector + ranked table
// =================================================================

// ---- constants ----

const BD_BAND_LABEL = {
  category_authority:     "Category Authority",
  emerging_authority:     "Emerging Authority",
  visible_underleveraged: "Visible but Underleveraged",
  low_trust_density:      "Low Trust Density",
  weak_authority:         "Weak Authority",
};

const BD_BAND_TONE = {
  category_authority:     "good",
  emerging_authority:     "accent",
  visible_underleveraged: "warn",
  low_trust_density:      "warn",
  weak_authority:         "bad",
};

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

const BD_PRESENCE_LABEL = { present: "Present", in_progress: "In Progress", not_present: "Not Present" };
const BD_PRESENCE_TONE = { present: "good", in_progress: "accent", not_present: "neutral" };

const BD_TYPE_LABEL = {
  company_data: "Company Data", software_review: "Reviews", product_launch: "Product Launch",
  developer_authority: "Developer", marketplace: "Marketplace", community: "Community",
  certification: "Certification", regulatory: "Regulatory", media: "Media",
  social_content: "Social", thought_leadership: "Thought Leadership",
  review_trust: "Reviews & Trust", app_trust: "App Trust", b2b_directory: "B2B Directory",
  security_trust: "Security & Trust",
};

const BD_REGIONS = ["all", "global", "india", "gcc", "europe", "usa"];
const BD_REGION_LABEL = {
  all: "All Regions", global: "Global", india: "India",
  gcc: "GCC", europe: "Europe", usa: "USA",
};

const bdScoreColor = (s) => {
  if (s == null) return "var(--muted)";
  return s >= 75 ? "var(--good)" : s >= 60 ? "var(--accent)" : s >= 50 ? "var(--warn)" : "var(--bad)";
};

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

// ---- Score Gauge SVG ----
const BrandScoreGauge = ({ score, size = 180 }) => {
  const S = Math.max(0, Math.min(100, score ?? 0));
  const r = size * 0.375;
  const cx = size / 2, cy = size * 0.56;
  const circ = 2 * Math.PI * r;
  const arcFrac = 0.72;
  const arcLen = circ * arcFrac;
  const color = bdScoreColor(score);
  const rotStart = 234;

  return (
    <svg width={size} height={size * 0.72} viewBox={`0 0 ${size} ${size * 0.72}`}>
      <circle cx={cx} cy={cy} r={r} fill="none"
        stroke="var(--line-2)" strokeWidth={14} strokeLinecap="round"
        strokeDasharray={`${arcLen} ${circ - arcLen}`}
        transform={`rotate(${rotStart} ${cx} ${cy})`}
      />
      {S > 0 && (
        <circle cx={cx} cy={cy} r={r} fill="none"
          stroke={color} strokeWidth={14} strokeLinecap="round"
          strokeDasharray={`${arcLen * S / 100} ${circ}`}
          transform={`rotate(${rotStart} ${cx} ${cy})`}
          style={{ transition: "stroke-dasharray .5s ease" }}
        />
      )}
      <text x={cx} y={cy + 10} textAnchor="middle"
        fill={color} fontSize={size * 0.22} fontWeight="800"
        fontFamily="var(--mono)" style={{ letterSpacing: "-.03em" }}>
        {score != null ? Math.round(S) : "—"}
      </text>
      <text x={cx} y={cy + 26} textAnchor="middle"
        fill="var(--muted)" fontSize={size * 0.072} fontWeight={500}>
        / 100
      </text>
    </svg>
  );
};

// ---- Data hooks ----

const useBrandAssessments = () => {
  const [state, setState] = React.useState({ assessment: null, companyName: {}, loading: true });
  const load = React.useCallback(async () => {
    setState(s => ({ ...s, loading: true }));
    try {
      const [assessments, companies] = await Promise.all([
        window.api.tcall("listAssessments"),
        window.api.tcall("listCompanies"),
      ]);
      const companyName = Object.fromEntries((companies || []).map(c => [c.id, c.name]));
      const completed = (assessments || [])
        .filter(a => a.status === "completed" && a.final_score != null)
        .sort((a, b) => new Date(b.completed_at || b.created_at) - new Date(a.completed_at || a.created_at));
      setState({ assessment: completed[0] || null, companyName, loading: false });
    } catch {
      setState({ assessment: null, companyName: {}, loading: false });
    }
  }, []);
  React.useEffect(() => { load(); }, [load]);
  React.useEffect(() => {
    const h = () => load();
    window.addEventListener("tenant-changed", h);
    return () => window.removeEventListener("tenant-changed", h);
  }, [load]);
  return { ...state, reload: load };
};

const useBrandAssignments = () => {
  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 useBrandSurfaces = () => {
  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 };
};

// ---- Score Card ----

const ScoreCard = ({ assessment, companyName }) => {
  if (!assessment) {
    return (
      <Card>
        <div style={{ textAlign: "center", padding: "32px 0", color: "var(--muted)", fontSize: 13.5 }}>
          No completed assessment found for this tenant.{" "}
          <span style={{ color: "var(--accent)", cursor: "pointer" }}
            onClick={() => window.__nav("new-assessment")}>
            Start one →
          </span>
        </div>
      </Card>
    );
  }

  const { final_score, score_band, common_authority_score, industry_score, momentum_score } = assessment;
  const bandLabel = BD_BAND_LABEL[score_band] || score_band || "—";
  const bandTone  = BD_BAND_TONE[score_band]  || "neutral";
  const company   = companyName[assessment.company_id] || "Your Company";
  const scoredOn  = bdFmt(assessment.completed_at || assessment.created_at);

  const tones = { good: "var(--good)", accent: "var(--accent)", warn: "var(--warn)", bad: "var(--bad)", neutral: "var(--muted)" };

  return (
    <Card>
      <div style={{ display: "flex", gap: 32, alignItems: "center", flexWrap: "wrap" }}>

        {/* Gauge */}
        <div style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: 8, flexShrink: 0 }}>
          <BrandScoreGauge score={final_score} size={180}/>
          <span style={{
            display: "inline-flex", alignItems: "center", padding: "4px 14px",
            borderRadius: 999, fontSize: 12.5, fontWeight: 600,
            background: `color-mix(in oklab, ${tones[bandTone]} 14%, transparent)`,
            color: tones[bandTone],
          }}>
            {bandLabel}
          </span>
        </div>

        {/* Components */}
        <div style={{ flex: 1, minWidth: 220, display: "flex", flexDirection: "column", gap: 20 }}>
          <div>
            <div style={{ fontWeight: 700, fontSize: 16, color: "var(--ink)" }}>{company}</div>
            <div style={{ fontSize: 12.5, color: "var(--muted)", marginTop: 2 }}>Last scored {scoredOn}</div>
          </div>
          <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
            <ProgressBar
              label="Common Authority"
              value={common_authority_score ?? 0}
              max={60}
              tone={bdScoreColor(((common_authority_score ?? 0) / 60) * 100).replace("var(--", "").replace(")", "") === "good" ? "good" : "accent"}
              format={(v) => v.toFixed(1)}
            />
            <ProgressBar
              label="Industry-Specific"
              value={industry_score ?? 0}
              max={30}
              tone="accent"
              format={(v) => v.toFixed(1)}
            />
            <ProgressBar
              label="Momentum"
              value={momentum_score ?? 0}
              max={10}
              tone="good"
              format={(v) => v.toFixed(1)}
            />
          </div>
        </div>

      </div>
    </Card>
  );
};

// ---- Tab 1: My Platforms ----

const MyPlatformsTab = ({ assignments, loading }) => {
  const [filterPriority, setFilterPriority] = React.useState("all");
  const [filterRegion,   setFilterRegion]   = React.useState("all");

  const present    = assignments.filter(a => a.presence_status === "present").length;
  const inProgress = assignments.filter(a => a.presence_status === "in_progress").length;
  const p1Missing  = assignments.filter(a => a.priority === "p1" && a.presence_status !== "present").length;

  const filtered = assignments.filter(a => {
    const pOk = filterPriority === "all" || a.priority === filterPriority;
    const rOk = filterRegion === "all"
      || (a.surface?.regions || []).includes(filterRegion)
      || (filterRegion === "global" && (a.surface?.regions || []).includes("global"));
    return pOk && rOk;
  });

  if (loading) {
    return <div style={{ padding: 32, color: "var(--muted)", fontSize: 13.5 }}>Loading platforms…</div>;
  }

  if (assignments.length === 0) {
    return (
      <div style={{ textAlign: "center", padding: "48px 0" }}>
        <div style={{ fontSize: 32, marginBottom: 12 }}>🗺️</div>
        <div style={{ fontWeight: 600, fontSize: 15, marginBottom: 6 }}>No platforms assigned yet</div>
        <div style={{ color: "var(--muted)", fontSize: 13.5, marginBottom: 20 }}>
          Add platforms in the Authority Engine to track your presence.
        </div>
        <Btn kind="primary" onClick={() => window.__nav("authority")}>Open Authority Engine</Btn>
      </div>
    );
  }

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: "var(--gap)" }}>

      {/* KPI strip */}
      <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: "var(--gap)" }}>
        {[
          { label: "Total Assigned",   value: assignments.length, tone: "neutral" },
          { label: "Present",          value: present,            tone: "good"    },
          { label: "In Progress",      value: inProgress,         tone: "accent"  },
          { label: "P1 Gaps",          value: p1Missing,          tone: p1Missing > 0 ? "bad" : "good" },
        ].map(k => (
          <div key={k.label} style={{
            padding: "14px 16px", borderRadius: "var(--r-md)",
            background: "var(--panel-2)", border: "1px solid var(--line-2)",
          }}>
            <div style={{ fontSize: 12, color: "var(--muted)", marginBottom: 4 }}>{k.label}</div>
            <div style={{
              fontSize: 26, fontWeight: 700, fontFamily: "var(--mono)",
              color: { neutral: "var(--ink)", good: "var(--good)", accent: "var(--accent)", bad: "var(--bad)" }[k.tone],
            }}>{k.value}</div>
          </div>
        ))}
      </div>

      {/* Filters */}
      <div style={{ display: "flex", gap: 10, flexWrap: "wrap" }}>
        <SegmentedControl
          value={filterPriority}
          onChange={setFilterPriority}
          options={[
            { label: "All", value: "all" },
            { label: "P1", value: "p1" },
            { label: "P2", value: "p2" },
            { label: "P3", value: "p3" },
          ]}
        />
        <div style={{ width: 160 }}>
          <Select
            value={filterRegion}
            onChange={v => setFilterRegion(v)}
            options={BD_REGIONS.map(r => ({ label: BD_REGION_LABEL[r], value: r }))}
          />
        </div>
        <div style={{ flex: 1 }}/>
        <span style={{ fontSize: 12.5, color: "var(--muted)", alignSelf: "center" }}>
          {filtered.length} of {assignments.length}
        </span>
      </div>

      {/* Platform grid */}
      <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(260px, 1fr))", gap: "var(--gap)" }}>
        {filtered.map(a => {
          const s = a.surface || {};
          const regions = s.regions || [];
          return (
            <div key={a.id} style={{
              padding: "14px 16px", borderRadius: "var(--r-md)",
              background: "var(--panel)", border: "1px solid var(--line)",
              display: "flex", flexDirection: "column", gap: 10,
            }}>
              {/* Header */}
              <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", gap: 8 }}>
                <div>
                  <div style={{ fontWeight: 600, fontSize: 13.5 }}>{s.name || "—"}</div>
                  <div style={{ fontSize: 12, color: "var(--muted)", marginTop: 2 }}>
                    {BD_TYPE_LABEL[s.platform_type] || s.platform_type}
                  </div>
                </div>
                <span style={{
                  fontSize: 11, fontWeight: 700, padding: "3px 8px", borderRadius: 999,
                  background: `color-mix(in oklab, ${BD_PRIORITY_COLOR[a.priority]} 14%, transparent)`,
                  color: BD_PRIORITY_COLOR[a.priority], flexShrink: 0,
                }}>
                  {(a.priority || "").toUpperCase()}
                </span>
              </div>

              {/* Region chips */}
              {regions.length > 0 && (
                <div style={{ display: "flex", gap: 4, flexWrap: "wrap" }}>
                  {regions.map(r => (
                    <span key={r} style={{
                      fontSize: 10.5, padding: "2px 7px", borderRadius: 999,
                      background: "var(--panel-2)", color: "var(--ink-2)", border: "1px solid var(--line-2)",
                    }}>{BD_REGION_LABEL[r] || r}</span>
                  ))}
                </div>
              )}

              {/* Presence + link */}
              <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
                <StatusDot tone={BD_PRESENCE_TONE[a.presence_status] || "neutral"}>
                  {BD_PRESENCE_LABEL[a.presence_status] || a.presence_status}
                </StatusDot>
                {a.presence_url && (
                  <a href={a.presence_url} target="_blank" rel="noreferrer"
                    style={{ display: "inline-flex", alignItems: "center", gap: 4, fontSize: 12, color: "var(--accent)", textDecoration: "none" }}>
                    View <IconExternal size={11}/>
                  </a>
                )}
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
};

// ---- Tab 2: Suggested Platforms ----

const SuggestedTab = ({ surfaces, assignments, loading }) => {
  const [filterRegion, setFilterRegion] = React.useState("all");

  const assignedIds = React.useMemo(
    () => new Set(assignments.map(a => a.surface_id)),
    [assignments]
  );

  const fintech = surfaces.filter(s =>
    (s.industry_verticals || []).includes("financial_services") ||
    (s.industry_verticals || []).includes("all")
  );

  const unassigned = fintech.filter(s => !assignedIds.has(s.id));

  const byRegion = (s) => {
    if (filterRegion === "all") return true;
    return (s.regions || []).includes(filterRegion);
  };

  const p1 = unassigned.filter(s => s.priority === "p1" && byRegion(s));
  const p2 = unassigned.filter(s => s.priority === "p2" && byRegion(s));
  const p3 = unassigned.filter(s => s.priority === "p3" && byRegion(s));

  const SurfaceCard = ({ s }) => (
    <div style={{
      padding: "12px 14px", borderRadius: "var(--r-md)",
      background: "var(--panel)", border: "1px solid var(--line)",
      display: "flex", flexDirection: "column", gap: 8,
    }}>
      <div>
        <div style={{ fontWeight: 600, fontSize: 13 }}>{s.name}</div>
        <div style={{ fontSize: 11.5, color: "var(--muted)" }}>
          {BD_TYPE_LABEL[s.platform_type] || s.platform_type}
        </div>
      </div>
      {(s.regions || []).length > 0 && (
        <div style={{ display: "flex", gap: 4, flexWrap: "wrap" }}>
          {(s.regions || []).map(r => (
            <span key={r} style={{
              fontSize: 10, padding: "2px 6px", borderRadius: 999,
              background: "var(--panel-2)", color: "var(--ink-2)", border: "1px solid var(--line-2)",
            }}>{BD_REGION_LABEL[r] || r}</span>
          ))}
        </div>
      )}
      <div style={{ display: "flex", justify: "space-between", alignItems: "center", gap: 8 }}>
        {s.has_content_api && (
          <span style={{ fontSize: 10.5, color: "var(--good)", fontWeight: 600 }}>⚡ API available</span>
        )}
        <a href={s.url || "#"} target="_blank" rel="noreferrer"
          style={{ marginLeft: "auto", display: "inline-flex", alignItems: "center", gap: 3,
            fontSize: 11.5, color: "var(--accent)", textDecoration: "none" }}>
          Visit <IconExternal size={10}/>
        </a>
      </div>
    </div>
  );

  const Column = ({ label, items, color }) => (
    <div style={{ flex: 1, minWidth: 200 }}>
      <div style={{
        fontSize: 11, fontWeight: 700, letterSpacing: ".05em", textTransform: "uppercase",
        color, marginBottom: 12, paddingBottom: 8, borderBottom: `2px solid ${color}`,
        display: "flex", justifyContent: "space-between",
      }}>
        <span>{label}</span>
        <span style={{ fontWeight: 400, color: "var(--muted)" }}>{items.length}</span>
      </div>
      <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
        {items.length === 0 ? (
          <div style={{ color: "var(--muted)", fontSize: 12.5, padding: "12px 0" }}>
            {filterRegion === "all" ? "All covered ✓" : `None for ${BD_REGION_LABEL[filterRegion]}`}
          </div>
        ) : items.map(s => <SurfaceCard key={s.id} s={s}/>)}
      </div>
    </div>
  );

  if (loading) {
    return <div style={{ padding: 32, color: "var(--muted)", fontSize: 13.5 }}>Loading surfaces…</div>;
  }

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: "var(--gap)" }}>
      <div style={{ display: "flex", gap: 10, alignItems: "center" }}>
        <div style={{ width: 180 }}>
          <Select
            value={filterRegion}
            onChange={v => setFilterRegion(v)}
            options={BD_REGIONS.map(r => ({ label: BD_REGION_LABEL[r], value: r }))}
          />
        </div>
        <div style={{ flex: 1 }}/>
        <span style={{ fontSize: 12.5, color: "var(--muted)" }}>
          {p1.length + p2.length + p3.length} platforms you're not yet on
        </span>
      </div>

      <div style={{ display: "flex", gap: "var(--gap)", alignItems: "flex-start" }}>
        <Column label="P1 — Must Have" items={p1} color="var(--bad)"/>
        <Column label="P2 — Should Have" items={p2} color="var(--warn)"/>
        <Column label="P3 — Optional" items={p3} color="var(--muted)"/>
      </div>
    </div>
  );
};

// ---- Tab 3: Peer Benchmark ----

const PeerBenchmarkTab = () => {
  const { rows: groups, live, loading } = useLive(
    () => window.api.tcall("listPeerGroups"), [], [window.session?.tenantId]
  );
  const [selectedId, setSelectedId] = React.useState(null);
  const [benchmark, setBenchmark]   = React.useState(null);
  const [bmLoading, setBmLoading]   = React.useState(false);

  const loadBenchmark = async (groupId) => {
    setSelectedId(groupId);
    setBmLoading(true);
    try {
      const data = await window.api.tcall("peerBenchmark", { groupId });
      setBenchmark(data || []);
    } catch (e) {
      window.__toast("Could not load benchmark: " + (e?.message || "error"), "error");
      setBenchmark([]);
    }
    setBmLoading(false);
  };

  if (loading) {
    return <div style={{ padding: 32, color: "var(--muted)", fontSize: 13.5 }}>Loading peer groups…</div>;
  }

  if (!live || groups.length === 0) {
    return (
      <div style={{ textAlign: "center", padding: "48px 0" }}>
        <div style={{ fontSize: 32, marginBottom: 12 }}>👥</div>
        <div style={{ fontWeight: 600, fontSize: 15, marginBottom: 6 }}>No peer groups yet</div>
        <div style={{ color: "var(--muted)", fontSize: 13.5, marginBottom: 20 }}>
          Create a peer group to compare your authority score against similar companies.
        </div>
        <Btn kind="primary" onClick={() => window.__nav("peer-groups")}>Create Peer Group</Btn>
      </div>
    );
  }

  return (
    <div style={{ display: "grid", gridTemplateColumns: "240px 1fr", gap: "var(--gap)", alignItems: "start" }}>
      <Card padded={false}>
        <div style={{ padding: "12px 8px", fontWeight: 600, fontSize: 12.5, color: "var(--muted)",
          textTransform: "uppercase", letterSpacing: ".04em", borderBottom: "1px solid var(--line)" }}>
          Peer Groups
        </div>
        <nav style={{ display: "flex", flexDirection: "column", padding: 6 }}>
          {groups.map(g => (
            <button key={g.id} onClick={() => loadBenchmark(g.id)} style={{
              textAlign: "left", padding: "9px 12px", borderRadius: 8, border: "none", cursor: "pointer",
              fontSize: 13.5,
              background: selectedId === g.id ? "var(--accent-soft)" : "transparent",
              color: selectedId === g.id ? "var(--accent)" : "inherit",
              fontWeight: selectedId === g.id ? 600 : 400,
            }}>
              {g.name}
              <span style={{ color: "var(--muted)", fontSize: 12, marginLeft: 6 }}>({(g.company_ids || []).length})</span>
            </button>
          ))}
        </nav>
      </Card>

      <Card title="Rankings" subtitle={selectedId ? "Ranked by latest CredAxis score." : "Select a group on the left."} padded={false}>
        {bmLoading && <div style={{ padding: 24, color: "var(--muted)", fontSize: 13.5 }}>Loading…</div>}
        {!bmLoading && benchmark && (
          <DataTable
            rows={benchmark}
            keyField="company_id"
            columns={[
              { key: "rank", label: "#", align: "right", mono: true, render: (r) => r.rank ?? "—" },
              { key: "company_name", label: "Company", render: (r) => (
                <span style={{ fontWeight: r.is_client ? 700 : 400 }}>
                  {r.company_name}
                  {r.is_client && <Pill style={{ marginLeft: 8 }}>your client</Pill>}
                </span>
              )},
              { key: "final_score", label: "Score", align: "right", render: (r) => <ScoreBadge score={r.final_score}/> },
              { key: "score_band", label: "Band", render: (r) => r.score_band
                ? <span style={{ fontSize: 12.5 }}>{BD_BAND_LABEL[r.score_band] || r.score_band}</span>
                : <span style={{ color: "var(--muted)", fontSize: 12.5 }}>Not scored</span> },
              { key: "common_score",   label: "Common",   align: "right", mono: true, render: (r) => r.common_score?.toFixed(1) ?? "—" },
              { key: "industry_score", label: "Industry", align: "right", mono: true, render: (r) => r.industry_score?.toFixed(1) ?? "—" },
            ]}
          />
        )}
        {!bmLoading && !benchmark && (
          <div style={{ padding: 24, color: "var(--muted)", fontSize: 13.5 }}>Select a group to view rankings.</div>
        )}
      </Card>
    </div>
  );
};

// ---- Main screen ----

const BrandDashboardScreen = () => {
  const [tab, setTab] = React.useState("platforms");

  const { assessment, companyName, loading: asmLoading } = useBrandAssessments();
  const { assignments, loading: assLoading } = useBrandAssignments();
  const { surfaces, loading: surfLoading } = useBrandSurfaces();

  const TABS = [
    { id: "platforms",  label: "My Platforms" },
    { id: "suggested",  label: "Suggested Platforms" },
    { id: "benchmark",  label: "Peer Benchmark" },
  ];

  const p1Assigned = assignments.filter(a => a.priority === "p1").length;
  const present    = assignments.filter(a => a.presence_status === "present").length;
  const p1Missing  = assignments.filter(a => a.priority === "p1" && a.presence_status !== "present").length;
  const fintechUnassigned = surfaces.filter(s =>
    (s.industry_verticals || []).includes("financial_services") &&
    !assignments.some(a => a.surface_id === s.id)
  ).length;

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: "var(--gap)" }}>
      <ScreenHeader
        title="Brand Dashboard"
        subtitle="Your CredAxis authority score, platform presence, and peer ranking — all in one view."
        right={
          <Btn kind="ghost" size="sm" onClick={() => window.__nav("authority")}>
            Authority Engine →
          </Btn>
        }
      />

      {/* Score card */}
      {asmLoading ? (
        <Card><div style={{ padding: 32, textAlign: "center", color: "var(--muted)", fontSize: 13.5 }}>Loading score…</div></Card>
      ) : (
        <ScoreCard assessment={assessment} companyName={companyName}/>
      )}

      {/* KPI strip */}
      <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: "var(--gap)" }}>
        {[
          { label: "P1 Platforms Assigned", value: p1Assigned, sub: "must-have surfaces" },
          { label: "Present on Platform",   value: present,    sub: `of ${assignments.length} assigned` },
          { label: "P1 Gaps",               value: p1Missing,  sub: "not yet present" },
          { label: "Suggested (Fintech)",   value: fintechUnassigned, sub: "platforms to explore" },
        ].map(k => (
          <Card key={k.label}>
            <div style={{ display: "flex", flexDirection: "column", gap: 4 }}>
              <div style={{ fontSize: 12, color: "var(--muted)" }}>{k.label}</div>
              <div style={{ fontSize: 26, fontWeight: 700, fontFamily: "var(--mono)", color: "var(--ink)" }}>
                {k.value}
              </div>
              <div style={{ fontSize: 11.5, color: "var(--muted)" }}>{k.sub}</div>
            </div>
          </Card>
        ))}
      </div>

      {/* Tab bar */}
      <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 === "platforms"  && <MyPlatformsTab assignments={assignments} loading={assLoading}/>}
        {tab === "suggested"  && <SuggestedTab surfaces={surfaces} assignments={assignments} loading={surfLoading}/>}
        {tab === "benchmark"  && <PeerBenchmarkTab/>}
      </div>
    </div>
  );
};

Object.assign(window, { BrandDashboardScreen });
