// Blockers & risk — tabbed view, API-wired.

// React hooks (Babel-standalone — make hooks visible per-script)
const { useState, useEffect, useRef, useMemo, useCallback, createContext, useContext } = React;

const brStyles = {
  page: { padding: 16, display: "flex", flexDirection: "column", gap: 12, height: "100%", overflow: "hidden" },
  tabs: { display: "flex", gap: 0, borderBottom: "1px solid var(--vk-border-subtle)" },
  tab: {
    padding: "8px 14px", fontSize: 13, color: "var(--vk-text-secondary)",
    cursor: "pointer", borderBottom: "2px solid transparent",
    transition: "color 120ms, border-color 120ms",
  },
  tabActive: {
    color: "var(--vk-text-primary)",
    borderBottom: "2px solid var(--vk-magenta)",
    fontWeight: 500,
  },
};

const BR_TABS = [
  { id: "blockers",  label: "Blockers"    },
  { id: "conflicts", label: "Conflicts"   },
  { id: "sensitive", label: "Sensitive"   },
  { id: "insider",   label: "Insider risk"},
];

function BlockersRisk({ openEntity, openEvidence }) {
  const app = useAppState();
  const [tab, setTab] = useState("blockers");
  const { data, loading } = useApi("/ranked/top_blockers", { city: app.city, run_id: app.runId, limit: 50 }, [app.city, app.runId]);
  const all = Array.isArray(data) ? data : [];

  // Tab filtering — server returns all blockers; we partition client-side.
  const rows = useMemo(() => {
    if (tab === "blockers")  return all.filter((e) => e.blocker_candidate === "yes" || e.entity_type === "regulator");
    if (tab === "conflicts") return all.filter((e) => (e.canonical_name || "").startsWith("[redacted") || e.entity_type === "person");
    if (tab === "sensitive") return all.filter((e) => e.risk_score >= 50 && e.confidence_score < 70);
    return all.filter((e) => (e.role_in_ecosystem || "").toLowerCase().includes("insider") || (e.canonical_name || "").startsWith("[redacted"));
  }, [all, tab]);

  return (
    <div style={brStyles.page}>
      <div style={{ display: "flex", alignItems: "baseline", gap: 12 }}>
        <h2 style={{ margin: 0, fontSize: 18, fontWeight: 500 }}>Blockers & risk</h2>
        <span style={{ fontSize: 11, color: "var(--vk-text-tertiary)" }}>{loading ? "loading…" : `${rows.length} rows`}</span>
      </div>
      <div style={brStyles.tabs}>
        {BR_TABS.map((t) => (
          <div key={t.id}
            style={{ ...brStyles.tab, ...(tab === t.id ? brStyles.tabActive : {}) }}
            onClick={() => setTab(t.id)}
          >{t.label}</div>
        ))}
      </div>
      <div style={{ flex: 1, overflow: "auto", background: "var(--vk-surface-1)", borderRadius: 5, boxShadow: "var(--vk-ring-ambient)", padding: 14 }}>
        {loading ? <SkeletonBlock rows={6} /> : rows.length === 0 ? (
          <EmptyState icon="ShieldCheck" title="Nothing flagged in this category for the current run." />
        ) : (
          <MiniTable
            columns={[
              { key: "name", label: "Entity", width: "1.3fr" },
              { key: "category", label: "Category", width: "1fr" },
              { key: "pattern", label: "Pattern", width: "1.6fr" },
              { key: "risk", label: "Risk", width: "60px", align: "right" },
              { key: "conf", label: "Conf.", width: "60px", align: "right" },
              { key: "action", label: "Rec. action", width: "1fr" },
            ]}
            rows={rows.map((e) => {
              const isRedacted = (e.canonical_name || "").startsWith("[redacted");
              const cat = tab === "blockers" ? { label: "Regulatory blocker", kind: "low" }
                : tab === "conflicts" ? { label: "Conflict of interest", kind: "med" }
                : tab === "sensitive" ? { label: "Sensitive", kind: "neutral" }
                : { label: "Insider risk", kind: "med" };
              return {
                key: e.entity_id,
                name: isRedacted
                  ? <span style={{ color: "var(--vk-text-tertiary)", fontStyle: "italic" }}>{e.canonical_name}</span>
                  : <EntityLink entity={e} onOpen={openEntity}>{e.canonical_name}</EntityLink>,
                category: <Pill kind={cat.kind}>{cat.label}</Pill>,
                pattern: <span style={{ color: "var(--vk-text-secondary)" }}>{e.role_in_ecosystem || e.sector_or_focus || "—"}</span>,
                risk: <Score value={e.risk_score} riskScale />,
                conf: <ConfPill confidence={e.confidence_score >= 70 ? "high" : e.confidence_score >= 40 ? "med" : "low"} />,
                action: <span style={{ color: "var(--vk-text-secondary)" }}>Manual review</span>,
              };
            })}
          />
        )}
      </div>
    </div>
  );
}

Object.assign(window, { BlockersRisk });
