// =================================================================
// screens-sourceauthority.jsx — Source Authority (MOZ) management.
//
//   SourceAuthorityScreen — /source-authority (superadmin + tenant admin)
//
// Cached domain-authority grades for the sites where brand mentions / links
// appear. Read-mostly: grades are populated automatically during evidence
// collection (MOZ Links API, 60-day cache). This screen lets an admin review
// grades, filter to flagged/excluded ones, and force-refresh on demand.
//
// `sourceGrade()` (DA → tier + Pill tone) is defined in screens-workflow.jsx,
// which loads before this file.
// =================================================================

const saFmtDate = (s) => {
  if (!s) return "—";
  try { return new Date(s).toLocaleDateString(undefined, { month: "short", day: "numeric", year: "numeric" }); }
  catch { return "—"; }
};

const saNum = (v) => (v == null ? "—" : Math.round(v));

const SourceAuthorityScreen = () => {
  const role = window.session?.role;
  const allowed = role === "superadmin" || role === "tenant_admin";

  const [rows, setRows] = React.useState([]);
  const [flaggedOnly, setFlaggedOnly] = React.useState(false);
  const [loading, setLoading] = React.useState(true);
  const [error, setError] = React.useState(null);
  const [domainsInput, setDomainsInput] = React.useState("");
  const [busy, setBusy] = React.useState(false);

  const load = React.useCallback(async () => {
    setLoading(true);
    try {
      const out = await window.api.call("listSourceDomains", null, null,
        { qs: flaggedOnly ? "?flagged_only=true" : "" });
      setRows(out?.items || []);
      setError(null);
    } catch (e) {
      setError(e.message || "Could not load source grades.");
    }
    setLoading(false);
  }, [flaggedOnly]);

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

  const gradeDomains = async () => {
    const domains = domainsInput.split(/[\s,]+/).map(d => d.trim()).filter(Boolean);
    if (!domains.length) return;
    setBusy(true);
    try {
      await window.api.call("gradeSourceDomains", null, { domains }, { qs: "?force=true" });
      setDomainsInput("");
      window.__toast?.(`Graded ${domains.length} domain${domains.length === 1 ? "" : "s"}`);
      await load();
    } catch (e) {
      window.__toast?.(e.message || "Grading failed");
    }
    setBusy(false);
  };

  if (!allowed) return (
    <div style={{ display: "flex", flexDirection: "column", gap: "var(--gap)" }}>
      <ScreenHeader title="Source Authority" subtitle=""/>
      <Card><EmptyState title="Restricted" desc="Source authority grades are available to platform admins only."/></Card>
    </div>
  );

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: "var(--gap)" }}>
      <ScreenHeader
        title="Source Authority"
        subtitle="MOZ domain-authority grades for the sites where mentions and links appear."
      />

      <Card title="Grade domains" subtitle="Paste domains (comma or space separated) to grade or refresh now.">
        <div style={{ display: "flex", gap: 8, alignItems: "center" }}>
          <div style={{ flex: 1 }}>
            <Input value={domainsInput} onChange={(e) => setDomainsInput(e.target.value)}
              placeholder="forbes.com, techcrunch.com"/>
          </div>
          <Btn kind="primary" disabled={busy || !domainsInput.trim()} onClick={gradeDomains}>
            {busy ? "Grading…" : "Grade"}
          </Btn>
        </div>
      </Card>

      <Card padded={false}>
        <Toolbar>
          <span style={{ fontWeight: 600, fontSize: 13 }}>Graded sites</span>
          <span style={{ color: "var(--muted)", fontSize: 12.5 }}>{rows.length} cached</span>
          <div style={{ flex: 1 }}/>
          <label style={{ display: "inline-flex", alignItems: "center", gap: 6, fontSize: 12.5, color: "var(--muted)", cursor: "pointer" }}>
            <input type="checkbox" checked={flaggedOnly} onChange={(e) => setFlaggedOnly(e.target.checked)}/>
            Flagged only
          </label>
          <Btn kind="ghost" size="sm" onClick={load}>↻ Refresh</Btn>
        </Toolbar>

        <DataTable
          rows={rows}
          keyField="domain"
          rowsPerPage={15}
          columns={[
            { key: "domain", label: "Domain", render: (r) => (
              <span style={{ fontFamily: "var(--mono)", fontSize: 12.5,
                textDecoration: r.is_excluded ? "line-through" : "none",
                color: r.is_excluded ? "var(--muted-2)" : "var(--ink)" }}>{r.domain}</span>
            )},
            { key: "_grade", label: "Grade", sortable: false, render: (r) => {
              const g = sourceGrade(r.effective_authority, r.is_excluded);
              return g ? <Pill tone={g.tone}>{g.label}</Pill> : <span style={{ color: "var(--muted-2)" }}>—</span>;
            }},
            { key: "effective_authority", label: "Authority", align: "right", mono: true, render: (r) => saNum(r.effective_authority) },
            { key: "domain_authority",   label: "DA",        align: "right", mono: true, render: (r) => saNum(r.domain_authority) },
            { key: "spam_score",         label: "Spam",      align: "right", mono: true, render: (r) => saNum(r.spam_score) },
            { key: "source_multiplier",  label: "Multiplier",align: "right", mono: true, render: (r) => r.source_multiplier != null ? `×${r.source_multiplier}` : "—" },
            { key: "_flags", label: "Flags", sortable: false, render: (r) => (
              <span style={{ display: "inline-flex", gap: 4 }}>
                {r.is_excluded && <Pill tone="warn">Excluded</Pill>}
                {r.divergence_flag && <Pill tone="neutral">⚑ Diverged</Pill>}
              </span>
            )},
            { key: "last_refreshed_at", label: "Refreshed", align: "right", render: (r) => (
              <span style={{ color: "var(--muted)", fontSize: 12.5 }}>{saFmtDate(r.last_refreshed_at)}</span>
            )},
          ]}
        />
        {!loading && rows.length === 0 && (
          <div style={{ padding: 18, color: "var(--muted)", fontSize: 13.5 }}>
            {error || "No graded sites yet. Grades populate automatically as evidence is collected, or grade some above."}
          </div>
        )}
      </Card>
    </div>
  );
};