// =================================================================
// screens-workflow.jsx — CredAxis write flows (Phase 3).
//
//   new-assessment     NewAssessmentScreen   company → assessment → collect
//   assessment-detail  AssessmentDetailScreen evidence review, scoring, results
// =================================================================

const INDUSTRY_OPTIONS = [
  { value: "tech_saas_ai",       label: "Tech / SaaS / AI" },
  { value: "manufacturing",      label: "Manufacturing / Industrial" },
  { value: "financial_services", label: "Financial Services / Fintech" },
  { value: "healthcare_pharma",  label: "Healthcare / Pharma / Medtech" },
  { value: "consumer_d2c",       label: "Consumer / FMCG / D2C" },
];

const QUALITY_OPTIONS = [
  { value: 0.5, label: "Self-claimed, no proof (0.5x)" },
  { value: 0.7, label: "Owned content only (0.7x)" },
  { value: 0.8, label: "Unverified testimonial (0.8x)" },
  { value: 1.0, label: "Named client / visible proof (1.0x)" },
  { value: 1.1, label: "Third-party validation (1.1x)" },
  { value: 1.2, label: "Certified / audited (1.2x)" },
  { value: 1.3, label: "Multiple independent validations (1.3x)" },
];

const SOURCE_LABEL = { manual: "Manual", github: "GitHub", semrush: "SEMrush", moz: "MOZ", google: "Google", linkedin: "LinkedIn", news_api: "News", platform: "Platform", regulatory: "Regulatory" };

// Source-authority grade (MOZ Domain Authority) → tier label + Pill tone.
// Mirrors the agreed bands: ≥60 High, 40–59 Standard, 20–39 Low, else Excluded.
const sourceGrade = (da, excluded) => {
  if (excluded) return { label: "Excluded", tone: "warn" };
  if (da == null) return null;
  if (da >= 60) return { label: "High",     tone: "good" };
  if (da >= 40) return { label: "Standard", tone: "accent" };
  if (da >= 20) return { label: "Low",      tone: "neutral" };
  return { label: "Excluded", tone: "warn" };
};

// Site + grade cell for the evidence table. Renders nothing for un-sourced
// (aggregate/internal) evidence, so the column stays quiet for most rows.
const SourceGradeCell = ({ row }) => {
  if (!row.source_domain) return <span style={{ color: "var(--muted-2)" }}>—</span>;
  const g = sourceGrade(row.source_authority, row.source_excluded);
  const excluded = row.source_excluded;
  const tip = [
    row.source_authority != null ? `DA ${Math.round(row.source_authority)}` : null,
    row.source_multiplier != null ? `×${row.source_multiplier}` : null,
  ].filter(Boolean).join(" · ");
  return (
    <span title={tip} style={{ display: "inline-flex", alignItems: "center", gap: 6 }}>
      <span style={{
        fontSize: 12, fontFamily: "var(--mono)",
        color: excluded ? "var(--muted-2)" : "var(--ink-2)",
        textDecoration: excluded ? "line-through" : "none",
      }}>{row.source_domain}</span>
      {g && <Pill tone={g.tone}>{g.label}</Pill>}
    </span>
  );
};

// =================================================================
// NewAssessmentScreen — /new-assessment
// Dynamic multi-step wizard driven by GET /scoring/form-schema.
//   Step 1: Company  (industry choice re-renders the field set)
//   Step 2: Evidence (one card per factor from the schema)
//   Step 3: Review & create
// =================================================================
const LAYER_LABEL = { common: "Common Authority", industry: "Industry Authority", momentum: "Momentum" };

const NewAssessmentScreen = () => {
  const [step, setStep] = React.useState(1);
  const [schema, setSchema] = React.useState(null);
  const [companies, setCompanies] = React.useState([]);
  const [mode, setMode] = React.useState("new");      // new | existing
  const [companyId, setCompanyId] = React.useState("");
  const [industry, setIndustry] = React.useState("tech_saas_ai");
  const [fields, setFields] = React.useState({});      // company field values
  const [evidence, setEvidence] = React.useState({});  // factor_key -> {url,title,quality_multiplier}
  const [autoCollect, setAutoCollect] = React.useState(true);
  const [busy, setBusy] = React.useState(false);
  const [error, setError] = React.useState(null);

  // Load companies once; load schema whenever industry changes
  React.useEffect(() => {
    (async () => {
      try {
        const list = await window.api.tcall("listCompanies");
        setCompanies(list || []);
      } catch {}
    })();
  }, []);

  React.useEffect(() => {
    (async () => {
      try {
        const s = await window.api.call("formSchema", null, null, { qs: `?industry=${industry}` });
        setSchema(s);
      } catch (e) { setError("Could not load form schema — is the backend running?"); }
    })();
  }, [industry]);

  // When picking an existing company, lock industry to theirs
  const pickExisting = (id) => {
    setCompanyId(id);
    const c = companies.find(x => x.id === id);
    if (c) setIndustry(c.industry);
  };

  const setField = (k, v) => setFields(f => ({ ...f, [k]: v }));
  const setEv = (key, patch) => setEvidence(ev => ({ ...ev, [key]: { ...(ev[key] || { quality_multiplier: 1.0 }), ...patch } }));

  const filledEvidence = Object.entries(evidence).filter(([, v]) => (v.url || v.title || "").trim());

  const submit = async () => {
    setBusy(true); setError(null);
    try {
      let cid = companyId;
      if (mode === "new") {
        if (!(fields.name || "").trim()) { setError("Company name is required."); setBusy(false); setStep(1); return; }
        // Split values into real columns vs the profile JSON
        const colKeys = new Set(["name", "website", "stage", "geography", "linkedin_url", "github_url"]);
        const body = { industry, profile: {} };
        for (const f of (schema?.company_fields || [])) {
          const v = (fields[f.key] || "").trim();
          if (!v) continue;
          if (f.profile) body.profile[f.key] = v;
          else if (colKeys.has(f.column || f.key)) body[f.column || f.key] = v;
        }
        if (Object.keys(body.profile).length === 0) delete body.profile;
        const company = await window.api.tcall("createCompany", null, body);
        cid = company.id;
      }
      if (!cid) { setError("Select or create a company first."); setBusy(false); setStep(1); return; }

      const assessment = await window.api.tcall("createAssessment", null, { company_id: cid });

      if (filledEvidence.length > 0) {
        await window.api.tcall("submitEvidenceBulk", { assessmentId: assessment.id }, {
          items: filledEvidence.map(([factor_key, v]) => ({
            factor_key,
            source: "manual",
            url: (v.url || "").trim() || null,
            title: (v.title || "").trim() || null,
            quality_multiplier: parseFloat(v.quality_multiplier) || 1.0,
          })),
        });
      }

      if (autoCollect) {
        try { await window.api.tcall("triggerCollection", { assessmentId: assessment.id }); } catch {}
      }

      window.__toast(`Assessment created with ${filledEvidence.length} evidence items`);
      window.__nav("assessment-detail", assessment.id);
    } catch (e) {
      setError(e.message || "Failed to create assessment.");
    }
    setBusy(false);
  };

  const steps = ["Company", "Evidence", "Review"];
  const sections = schema?.evidence_sections || [];
  const byLayer = { common: [], industry: [], momentum: [] };
  sections.forEach(s => (byLayer[s.layer] || byLayer.common).push(s));

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: "var(--gap)" }}>
      <ScreenHeader
        title="New assessment"
        subtitle={`Step ${step} of 3 — ${steps[step - 1]}`}
        right={
          <span style={{ display: "inline-flex", gap: 8 }}>
            {step > 1 && <Btn kind="ghost" onClick={() => setStep(s => s - 1)}>Back</Btn>}
            {step < 3 && <Btn kind="primary" onClick={() => setStep(s => s + 1)}
              disabled={step === 1 && mode === "new" && !(fields.name || "").trim() && false}>Next</Btn>}
            {step === 3 && <Btn kind="primary" disabled={busy} onClick={submit}>{busy ? "Creating…" : "Create assessment"}</Btn>}
          </span>
        }
      />

      {/* step indicator */}
      <div style={{ display: "flex", gap: 6 }}>
        {steps.map((s, i) => (
          <div key={s} onClick={() => setStep(i + 1)} style={{
            flex: 1, height: 4, borderRadius: 2, cursor: "pointer",
            background: i + 1 <= step ? "var(--accent)" : "var(--border)",
          }}/>
        ))}
      </div>

      {error && <Banner tone="warn" icon={<IconInfo size={16}/>}>{error}</Banner>}

      {/* ---------- STEP 1: Company ---------- */}
      {step === 1 && (
        <Card>
          <FormSection title="Company">
            <SegmentedControl value={mode} onChange={setMode}
              options={[{ value: "new", label: "New company" }, { value: "existing", label: "Existing company" }]}/>

            {mode === "existing" ? (
              <FieldRow label="Company">
                <Select value={companyId} onChange={(v) => pickExisting(v)}
                  options={[{ value: "", label: "Select…" }, ...companies.map(c => ({ value: c.id, label: c.name }))]}/>
              </FieldRow>
            ) : (
              <>
                <FieldRow label="Industry">
                  <Select value={industry} onChange={(v) => setIndustry(v)} options={INDUSTRY_OPTIONS}/>
                </FieldRow>
                <div className="hx-wizard-grid">
                  {(schema?.company_fields || []).map(f => (
                    <div key={f.key}>
                      <div style={{ fontSize: 12.5, fontWeight: 600, marginBottom: 5 }}>
                        {f.label}{f.required && <span style={{ color: "var(--bad)" }}> *</span>}
                      </div>
                      {f.type === "select" ? (
                        <Select value={fields[f.key] || ""} onChange={(v) => setField(f.key, v)}
                          options={[{ value: "", label: "—" }, ...(f.options || []).map(o => ({ value: o, label: o.replace(/_/g, " ") }))]}/>
                      ) : (
                        <Input value={fields[f.key] || ""} onChange={(v) => setField(f.key, v)}
                          placeholder={f.placeholder || ""}/>
                      )}
                      {f.help && <div style={{ fontSize: 11.5, color: "var(--muted)", marginTop: 4 }}>{f.help}</div>}
                    </div>
                  ))}
                </div>
              </>
            )}
          </FormSection>
        </Card>
      )}

      {/* ---------- STEP 2: Evidence ---------- */}
      {step === 2 && ["common", "industry", "momentum"].map(layer => byLayer[layer].length > 0 && (
        <div key={layer}>
          <div style={{ fontSize: 13, fontWeight: 700, letterSpacing: 0.4, textTransform: "uppercase",
                        color: "var(--muted)", margin: "6px 0 10px" }}>
            {LAYER_LABEL[layer]} · {byLayer[layer].reduce((s, x) => s + x.max_points, 0)} pts
          </div>
          <div className="hx-wizard-grid">
            {byLayer[layer].map(s => {
              const v = evidence[s.factor_key] || {};
              const filled = !!(v.url || v.title);
              return (
                <Card key={s.factor_key} style={{ borderLeft: filled ? "3px solid var(--accent)" : "3px solid transparent" }}>
                  <div style={{ display: "flex", alignItems: "baseline", gap: 8, marginBottom: 4 }}>
                    <strong style={{ fontSize: 13.5 }}>{s.label}</strong>
                    <span style={{ marginLeft: "auto", fontFamily: "var(--mono)", fontSize: 11.5, color: "var(--muted)" }}>{s.max_points} pts</span>
                  </div>
                  <div style={{ fontSize: 12, color: "var(--muted)", marginBottom: 8, minHeight: 30 }}>{s.help}</div>
                  {s.auto_collectable && (
                    <div style={{ fontSize: 11.5, color: "var(--accent)", marginBottom: 8 }}>⚡ Auto-collected when collection runs</div>
                  )}
                  <Input value={v.url || ""} onChange={(e) => setEv(s.factor_key, { url: e.target.value })}
                    placeholder={s.url_placeholder} style={{ marginBottom: 6 }}/>
                  <Input value={v.title || ""} onChange={(e) => setEv(s.factor_key, { title: e.target.value })}
                    placeholder={`e.g. ${s.evidence_hints[0] || "evidence description"}`} style={{ marginBottom: 6 }}/>
                  <Select value={String(v.quality_multiplier ?? 1.0)}
                    onChange={(v) => setEv(s.factor_key, { quality_multiplier: v })}
                    options={QUALITY_OPTIONS.map(q => ({ value: String(q.value), label: q.label }))}/>
                </Card>
              );
            })}
          </div>
        </div>
      ))}

      {/* ---------- STEP 3: Review ---------- */}
      {step === 3 && (
        <Card title="Review">
          <KeyValueList items={[
            { k: "Company", v: mode === "existing"
                ? (companies.find(c => c.id === companyId)?.name || "—")
                : (fields.name || "—") },
            { k: "Industry", v: INDUSTRY_OPTIONS.find(o => o.value === industry)?.label || industry },
            { k: "Evidence items to submit", v: String(filledEvidence.length) },
            { k: "Auto-collection", v: autoCollect ? "Yes — SEMrush + GitHub on creation" : "No" },
          ]}/>
          <label style={{ display: "flex", gap: 10, alignItems: "center", fontSize: 13.5, cursor: "pointer", marginTop: 14 }}>
            <Toggle checked={autoCollect} onChange={() => setAutoCollect(x => !x)}/>
            Auto-collect evidence on creation
          </label>
        </Card>
      )}

      <style>{`
        .hx-wizard-grid { display: grid; grid-template-columns: repeat(2, 1fr); gap: var(--gap); }
        @media (max-width: 980px) { .hx-wizard-grid { grid-template-columns: 1fr; } }
      `}</style>
    </div>
  );
};

// =================================================================
// AssessmentDetailScreen — /assessment-detail?<id>
// =================================================================
const AssessmentDetailScreen = ({ assessmentId }) => {
  const [assessment, setAssessment] = React.useState(null);
  const [company, setCompany] = React.useState(null);
  const [evidence, setEvidence] = React.useState([]);
  const [collection, setCollection] = React.useState(null);
  const [scoreResult, setScoreResult] = React.useState(null);
  const [tab, setTab] = React.useState("evidence");
  const [busy, setBusy] = React.useState(null); // which action is running
  const [error, setError] = React.useState(null);
  const canApprove = window.session?.can("approve_evidence");
  const canScore = window.session?.can("score_assessment");

  const load = React.useCallback(async () => {
    try {
      const a = await window.api.tcall("getAssessment", { assessmentId });
      setAssessment(a);
      try { setCompany(await window.api.tcall("getCompany", { companyId: a.company_id })); } catch {}
      try { setEvidence(await window.api.tcall("listEvidence", { assessmentId }) || []); } catch {}
      try { setCollection(await window.api.tcall("collectionStatus", { assessmentId })); } catch {}
      setError(null);
    } catch (e) {
      setError(e.message || "Could not load assessment.");
    }
  }, [assessmentId]);

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

  const act = async (label, fn) => {
    setBusy(label);
    try { await fn(); await load(); }
    catch (e) { window.__toast(e.message || `${label} failed`); }
    setBusy(null);
  };

  const approve = (id) => act(`approve-${id}`, () =>
    window.api.tcall("approveEvidence", { assessmentId, evidenceId: id }));
  const reject = (id) => act(`reject-${id}`, () =>
    window.api.tcall("rejectEvidence", { assessmentId, evidenceId: id }));
  const approveAll = () => act("approve-all", () =>
    window.api.tcall("approveAllCollected", { assessmentId }));
  const collect = () => act("collect", async () => {
    await window.api.tcall("triggerCollection", { assessmentId });
    window.__toast("Collection started — refresh in a few seconds");
  });
  const runScore = () => act("score", async () => {
    const result = await window.api.tcall("scoreAssessment", { assessmentId });
    setScoreResult(result);
    setTab("score");
    window.__toast(`Scored: ${result.final_score}/100`);
  });

  if (error) return (
    <div style={{ display: "flex", flexDirection: "column", gap: "var(--gap)" }}>
      <ScreenHeader title="Assessment" subtitle=""/>
      <Card><EmptyState title="Could not load assessment" desc={error}
        action={<Btn kind="secondary" onClick={() => window.__nav("assessments")}>Back to assessments</Btn>}/></Card>
    </div>
  );
  if (!assessment) return <div style={{ padding: 40, color: "var(--muted)" }}>Loading…</div>;

  const approvedCount = evidence.filter(e => e.is_approved).length;
  const statusLabel = STATUS_TO_STAGE[assessment.status] || assessment.status;

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: "var(--gap)" }}>
      <ScreenHeader
        title={company?.name || "Assessment"}
        subtitle={`${statusLabel} · ${evidence.length} evidence items (${approvedCount} approved)`}
        right={
          <span style={{ display: "inline-flex", gap: 8, alignItems: "center" }}>
            <ScoreBadge score={assessment.final_score}/>
            {canApprove && (
              <Btn kind="secondary" disabled={busy === "collect"} onClick={collect}>
                {busy === "collect" ? "Collecting…" : "Auto-collect"}
              </Btn>
            )}
            {canScore && (
              <Btn kind="primary" disabled={busy === "score" || approvedCount === 0}
                onClick={runScore}>{busy === "score" ? "Scoring…" : "Run scoring"}</Btn>
            )}
          </span>
        }
      />

      <Tabs value={tab} onChange={setTab} items={[
        { value: "evidence", label: "Evidence", count: evidence.length },
        { value: "score",    label: "Score & gaps" },
        { value: "ai",       label: "AI insights" },
      ]}/>

      {tab === "evidence" && (
        <Card padded={false}>
          <Toolbar>
            <div style={{ flex: 1 }}/>
            {collection && (
              <span style={{ color: "var(--muted)", fontSize: 12.5 }}>
                {collection.total_collected} collected · {collection.pending_count} pending
              </span>
            )}
            {canApprove && evidence.some(e => !e.is_approved) && (
              <Btn kind="ghost" size="sm" disabled={busy === "approve-all"} onClick={approveAll}>
                {busy === "approve-all" ? "Approving…" : "Approve all"}
              </Btn>
            )}
            <Btn kind="ghost" size="sm" onClick={load}>↻ Refresh</Btn>
          </Toolbar>

          <DataTable
            rows={evidence}
            keyField="id"
            rowsPerPage={12}
            columns={[
              { key: "factor_key", label: "Factor", mono: true, render: (r) => <span style={{ fontSize: 12.5, fontFamily: "var(--mono)" }}>{r.factor_key}</span> },
              { key: "source",     label: "Source", render: (r) => <Pill>{SOURCE_LABEL[r.source] || r.source}</Pill> },
              { key: "title",      label: "Evidence", render: (r) => (
                <span style={{ fontSize: 13 }}>
                  {r.url ? <a href={r.url} target="_blank" rel="noreferrer" style={{ color: "var(--accent)" }}>{r.title || r.url}</a> : (r.title || r.notes || "—")}
                </span>
              )},
              { key: "source_domain", label: "Site", render: (r) => <SourceGradeCell row={r}/> },
              { key: "quality_multiplier", label: "Quality", align: "right", mono: true, render: (r) => `${r.quality_multiplier}x` },
              { key: "is_approved", label: "Status", render: (r) => (
                <StatusDot tone={r.is_approved ? "good" : "neutral"}>{r.is_approved ? "Approved" : "Pending"}</StatusDot>
              )},
              { key: "_actions", label: "Actions", sortable: false, render: (r) => (
                <span style={{ display: "inline-flex", gap: 4 }}>
                  {canApprove && (!r.is_approved
                    ? <button
                        title="Approve"
                        disabled={busy === `approve-${r.id}`}
                        onClick={(e) => { e.stopPropagation(); approve(r.id); }}
                        style={{
                          width: 28, height: 28, borderRadius: 6, border: "1px solid var(--line)",
                          background: "var(--panel)", color: "var(--good)", cursor: "pointer",
                          fontSize: 14, display: "inline-flex", alignItems: "center", justifyContent: "center",
                          opacity: busy === `approve-${r.id}` ? 0.5 : 1,
                        }}>✓</button>
                    : <button
                        title="Revoke approval"
                        disabled={busy === `reject-${r.id}`}
                        onClick={(e) => { e.stopPropagation(); reject(r.id); }}
                        style={{
                          width: 28, height: 28, borderRadius: 6, border: "1px solid var(--line)",
                          background: "var(--panel)", color: "var(--muted)", cursor: "pointer",
                          fontSize: 14, display: "inline-flex", alignItems: "center", justifyContent: "center",
                          opacity: busy === `reject-${r.id}` ? 0.5 : 1,
                        }}>✕</button>
                  )}
                </span>
              )},
            ]}
          />
          {evidence.length === 0 && (
            <div style={{ padding: 18, color: "var(--muted)", fontSize: 13.5 }}>
              No evidence yet. Use Auto-collect above, or submit evidence via the API.
            </div>
          )}
        </Card>
      )}

      {tab === "score" && (
        <ScorePanel assessment={assessment} scoreResult={scoreResult} evidence={evidence}/>
      )}

      {tab === "ai" && (
        <AiInsightsPanel assessmentId={assessmentId} assessment={assessment}/>
      )}
    </div>
  );
};

// ---------- AI insights panel: action plan + investor summary ----------
const AiInsightsPanel = ({ assessmentId, assessment }) => {
  const [plan, setPlan] = React.useState(null);
  const [summary, setSummary] = React.useState(null);
  const [busy, setBusy] = React.useState(null);
  const [error, setError] = React.useState(null);
  const canRun = window.session?.can("run_ai_tasks");
  const scored = assessment.final_score != null;

  // Load existing plan on mount
  React.useEffect(() => {
    (async () => {
      try { setPlan(await window.api.tcall("getActionPlan", { assessmentId })); }
      catch { /* none yet */ }
    })();
  }, [assessmentId]);

  const run = async (label, fn) => {
    setBusy(label); setError(null);
    try { await fn(); }
    catch (e) {
      setError(e.status === 400 ? e.message
        : "AI generation failed — check that OPENAI_API_KEY is set in backend/.env and the assessment is scored.");
    }
    setBusy(null);
  };

  const generatePlan = () => run("plan", async () => {
    const p = await window.api.tcall("generateActionPlan", { assessmentId });
    setPlan(p);
    window.__toast(`Action plan generated — ${p.tasks?.length || 0} tasks`);
  });

  const generateSummary = () => run("summary", async () => {
    const s = await window.api.tcall("generateInvestorSummary", { assessmentId });
    setSummary(s);
  });

  const toggleTask = async (task) => {
    const next = task.status === "completed" ? "pending" : "completed";
    try {
      await window.api.tcall("updateActionTask",
        { assessmentId, planId: plan.id, taskId: task.id }, { status: next });
      setPlan(p => ({ ...p, tasks: p.tasks.map(t => t.id === task.id ? { ...t, status: next } : t) }));
    } catch (e) { window.__toast(e.message || "Update failed"); }
  };

  if (!scored) return (
    <Card><EmptyState title="Score the assessment first"
      desc="AI insights are generated from the computed score and gap map. Run scoring, then come back."/></Card>
  );

  const EFFORT_TONE = { low: "good", medium: "accent", high: "warn" };

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: "var(--gap)" }}>
      {error && <Banner tone="warn" icon={<IconInfo size={16}/>}>{error}</Banner>}

      {/* ---- 90-day action plan ---- */}
      <Card
        title="90-day action plan"
        subtitle={plan ? `Generated by ${plan.openai_model} · ${plan.tasks?.length || 0} tasks` : "AI-generated roadmap to improve the index score."}
        action={canRun && (
          <Btn kind={plan ? "secondary" : "primary"} size="sm" disabled={busy === "plan"} onClick={generatePlan}>
            {busy === "plan" ? "Generating… (can take ~30s)" : plan ? "Regenerate" : "Generate plan"}
          </Btn>
        )}
        padded={!plan}
      >
        {!plan && <div style={{ color: "var(--muted)", fontSize: 13.5 }}>
          No plan yet. {canRun ? "Press “Generate plan” to create one from the gap map." : "Ask a consultant or admin to generate one."}
        </div>}
      </Card>

      {plan?.summary && (
        <Card><div style={{ fontSize: 13.5, lineHeight: 1.6 }}>{plan.summary}</div></Card>
      )}

      {plan?.tasks?.length > 0 && (
        <Card padded={false}>
          <DataTable
            rows={plan.tasks}
            keyField="id"
            rowsPerPage={15}
            defaultSort={{ key: "priority", dir: "asc" }}
            columns={[
              { key: "status", label: "", sortable: false, render: (t) => (
                <input type="checkbox" checked={t.status === "completed"} onChange={() => toggleTask(t)}
                  style={{ cursor: "pointer" }}/>
              )},
              { key: "priority", label: "#", align: "right", mono: true },
              { key: "title", label: "Task", render: (t) => (
                <div>
                  <div style={{ fontWeight: 600, fontSize: 13.5, textDecoration: t.status === "completed" ? "line-through" : "none", opacity: t.status === "completed" ? 0.55 : 1 }}>{t.title}</div>
                  {t.description && <div style={{ color: "var(--muted)", fontSize: 12.5, marginTop: 2 }}>{t.description}</div>}
                </div>
              )},
              { key: "expected_impact", label: "Impact", render: (t) => (
                <span style={{ color: "var(--accent)", fontSize: 12.5 }}>{t.expected_impact || "—"}</span>
              )},
              { key: "effort", label: "Effort", render: (t) => t.effort
                ? <StatusDot tone={EFFORT_TONE[t.effort] || "neutral"}>{t.effort}</StatusDot> : "—" },
              { key: "due_days", label: "Due", align: "right", render: (t) => t.due_days ? `${t.due_days}d` : "—" },
            ]}
          />
        </Card>
      )}

      {/* ---- Investor signal summary ---- */}
      <Card
        title="Investor signal summary"
        subtitle="Due-diligence style write-up of credibility strengths and risks."
        action={canRun && (
          <Btn kind="secondary" size="sm" disabled={busy === "summary"} onClick={generateSummary}>
            {busy === "summary" ? "Generating…" : summary ? "Regenerate" : "Generate summary"}
          </Btn>
        )}
      >
        {summary
          ? <div style={{ fontSize: 13.5, lineHeight: 1.7, whiteSpace: "pre-wrap" }}>{summary.summary}</div>
          : <div style={{ color: "var(--muted)", fontSize: 13.5 }}>Not generated yet.</div>}
      </Card>
    </div>
  );
};

// ---------- Score results panel ----------
const ScorePanel = ({ assessment, scoreResult, evidence = [] }) => {
  const scored = assessment.final_score != null;
  const layers = [
    { label: "Common Authority",   value: scoreResult?.common_score   ?? assessment.common_authority_score,   max: 60 },
    { label: "Industry Authority", value: scoreResult?.industry_score ?? assessment.industry_authority_score, max: 30 },
    { label: "Momentum",           value: scoreResult?.momentum_score ?? assessment.momentum_score,           max: 10 },
  ];
  const gaps = scoreResult?.gaps || [];

  // How source-authority grading affected this run (graded mentions only).
  const graded = evidence.filter(e => e.source_domain && e.source_multiplier != null);
  const excluded = graded.filter(e => e.source_excluded).length;
  const weighted = graded.length - excluded;

  if (!scored && !scoreResult) return (
    <Card><EmptyState title="Not scored yet"
      desc="Approve evidence, then press “Run scoring” to compute the CredAxis index."/></Card>
  );

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: "var(--gap)" }}>
      {graded.length > 0 && (
        <div style={{ fontSize: 12.5, color: "var(--muted)" }}>
          {weighted} mention{weighted === 1 ? "" : "s"} weighted by source authority
          {excluded > 0 && <> · {excluded} excluded (low authority / spam)</>}
        </div>
      )}
      <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: "var(--gap)" }}>
        {layers.map(l => (
          <Card key={l.label} title={l.label} subtitle={`out of ${l.max} points`}>
            <div style={{ fontSize: 28, fontWeight: 700, fontFamily: "var(--mono)", marginBottom: 8 }}>
              {l.value != null ? l.value.toFixed(1) : "—"}
            </div>
            <ProgressBar value={l.value || 0} max={l.max}/>
          </Card>
        ))}
      </div>

      {gaps.length > 0 && (
        <Card title="Authority gap map" subtitle="Factors below 60% of their potential, sorted by opportunity." padded={false}>
          <DataTable
            rows={gaps}
            keyField="factor_key"
            rowsPerPage={10}
            columns={[
              { key: "label",        label: "Factor" },
              { key: "layer",        label: "Layer", render: (r) => <Pill>{r.layer}</Pill> },
              { key: "current_score",label: "Current", align: "right", mono: true, render: (r) => r.current_score.toFixed(1) },
              { key: "max_points",   label: "Max", align: "right", mono: true },
              { key: "opportunity",  label: "Opportunity", align: "right", render: (r) => (
                <span style={{ color: "var(--accent)", fontFamily: "var(--mono)", fontSize: 12.5 }}>+{r.opportunity.toFixed(1)}</span>
              )},
              { key: "current_pct",  label: "", sortable: false, render: (r) => (
                <div style={{ width: 90 }}><ProgressBar value={r.current_pct} max={100}/></div>
              )},
            ]}
          />
        </Card>
      )}
    </div>
  );
};

// =================================================================
// LiveDashboard — real stats for superadmin / tenant users.
// (Consultants get PortfolioScreen instead.)
// =================================================================
const LiveDashboard = ({ data }) => {
  const role = window.session?.role;
  const isSuper = role === "superadmin";
  const tenantSelected = !!window.session?.tenantId;

  const { rows: stats, live, loading } = useLive(async () => {
    const out = { assessments: [], companies: [], tenants: null };
    if (tenantSelected) {
      [out.assessments, out.companies] = await Promise.all([
        window.api.tcall("listAssessments"),
        window.api.tcall("listCompanies"),
      ]);
    }
    if (isSuper) {
      try { out.tenants = await window.api.call("listTenants"); } catch {}
    }
    return out;
  }, { assessments: [], companies: [], tenants: null }, [window.session?.tenantId]);

  const assessments = stats.assessments || [];
  const scored = assessments.filter(a => a.final_score != null);
  const avgScore = scored.length
    ? Math.round(scored.reduce((s, a) => s + a.final_score, 0) / scored.length) : null;
  const active = assessments.filter(a => !["completed", "archived"].includes(a.status)).length;
  const companyName = Object.fromEntries((stats.companies || []).map(c => [c.id, c.name]));

  const topScored = [...scored].sort((a, b) => b.final_score - a.final_score).slice(0, 5);

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: "var(--gap)" }}>
      <ScreenHeader
        title={`Good ${new Date().getHours() < 12 ? "morning" : new Date().getHours() < 17 ? "afternoon" : "evening"}`}
        subtitle={tenantSelected ? "Live overview for the active client." : "Select a client from the Clients screen to see live data."}
        right={
          <span style={{ display: "inline-flex", gap: 10, alignItems: "center" }}>
            <LiveBadge live={live} loading={loading}/>
            <Btn kind="primary" onClick={() => window.__nav("new-assessment")}>New assessment</Btn>
          </span>
        }
      />

      <div style={{ display: "grid", gridTemplateColumns: isSuper ? "repeat(4, 1fr)" : "repeat(3, 1fr)", gap: "var(--gap)" }}>
        <Card title="Assessments" subtitle="total in client">
          <div style={{ fontSize: 30, fontWeight: 700, fontFamily: "var(--mono)" }}>{assessments.length}</div>
        </Card>
        <Card title="In progress" subtitle="not yet scored">
          <div style={{ fontSize: 30, fontWeight: 700, fontFamily: "var(--mono)" }}>{active}</div>
        </Card>
        <Card title="Average score" subtitle="across scored assessments">
          <div style={{ fontSize: 30, fontWeight: 700, fontFamily: "var(--mono)" }}>{avgScore ?? "—"}</div>
        </Card>
        {isSuper && (
          <Card title="Clients" subtitle="on the platform">
            <div style={{ fontSize: 30, fontWeight: 700, fontFamily: "var(--mono)" }}>{stats.tenants ? stats.tenants.length : "—"}</div>
          </Card>
        )}
      </div>

      <Card title="Top scored companies" subtitle="Latest assessment scores in this client." padded={false}>
        <DataTable
          rows={topScored.map(a => ({
            id: a.id,
            company: companyName[a.company_id] || a.company_id,
            score: a.final_score,
            band: a.score_band ? (BAND_LABEL[a.score_band] || a.score_band) : "—",
          }))}
          keyField="id"
          onRowClick={(r) => window.__nav("assessment-detail", r.id)}
          columns={[
            { key: "company", label: "Company", render: (r) => <strong>{r.company}</strong> },
            { key: "score",   label: "Score", align: "right", render: (r) => <ScoreBadge score={r.score}/> },
            { key: "band",    label: "Band" },
          ]}
        />
        {topScored.length === 0 && (
          <div style={{ padding: 18, color: "var(--muted)", fontSize: 13.5 }}>
            {tenantSelected ? "No scored assessments yet — create one to get started." : "No client selected."}
          </div>
        )}
      </Card>
    </div>
  );
};

// =================================================================
// PeerGroupsScreen — /peer-groups
// =================================================================
const PeerGroupsScreen = () => {
  const [selected, setSelected] = React.useState(null);   // group id
  const [benchmark, setBenchmark] = React.useState(null);
  const [creating, setCreating] = React.useState(false);
  const [name, setName] = React.useState("");
  const [companyIds, setCompanyIds] = React.useState([]);
  const [companies, setCompanies] = React.useState([]);
  const canWrite = window.session?.can("create_assessment");

  const { rows: groups, live, loading, refresh } = useLive(
    () => window.api.tcall("listPeerGroups"), [], [window.session?.tenantId]);

  React.useEffect(() => {
    (async () => {
      try { setCompanies(await window.api.tcall("listCompanies") || []); } catch {}
    })();
  }, []);

  const loadBenchmark = async (groupId) => {
    setSelected(groupId);
    try { setBenchmark(await window.api.tcall("peerBenchmark", { groupId })); }
    catch (e) { window.__toast(e.message || "Could not load benchmark"); }
  };

  const createGroup = async () => {
    if (!name.trim() || companyIds.length === 0) {
      window.__toast("Name the group and pick at least one company"); return;
    }
    try {
      await window.api.tcall("createPeerGroup", null, { name: name.trim(), company_ids: companyIds });
      setCreating(false); setName(""); setCompanyIds([]);
      refresh();
      window.__toast("Peer group created");
    } catch (e) { window.__toast(e.message || "Create failed"); }
  };

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: "var(--gap)" }}>
      <ScreenHeader
        title="Peer benchmark"
        subtitle="Compare companies in the same competitive set by their latest scores."
        right={
          <span style={{ display: "inline-flex", gap: 10, alignItems: "center" }}>
            <LiveBadge live={live} loading={loading}/>
            {canWrite && <Btn kind="primary" onClick={() => setCreating(c => !c)}>{creating ? "Close" : "New peer group"}</Btn>}
          </span>
        }
      />

      {creating && (
        <Card title="New peer group">
          <FieldRow label="Group name">
            <Input value={name} onChange={(e) => setName(e.target.value)} placeholder="e.g. Indian B2B SaaS — Seed"/>
          </FieldRow>
          <FieldRow label="Companies">
            <div style={{ display: "flex", flexDirection: "column", gap: 6, maxHeight: 200, overflowY: "auto" }}>
              {companies.map(c => (
                <label key={c.id} style={{ display: "flex", gap: 8, alignItems: "center", fontSize: 13.5, cursor: "pointer" }}>
                  <input type="checkbox" checked={companyIds.includes(c.id)}
                    onChange={(e) => setCompanyIds(ids => e.target.checked ? [...ids, c.id] : ids.filter(i => i !== c.id))}/>
                  {c.name}
                </label>
              ))}
              {companies.length === 0 && <span style={{ color: "var(--muted)", fontSize: 13 }}>No companies in this tenant yet.</span>}
            </div>
          </FieldRow>
          <div style={{ marginTop: 12 }}>
            <Btn kind="primary" onClick={createGroup}>Create group</Btn>
          </div>
        </Card>
      )}

      <div style={{ display: "grid", gridTemplateColumns: "260px 1fr", gap: "var(--gap)", alignItems: "start" }}>
        <Card title="Groups" padded={false}>
          <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: selected === g.id ? "var(--accent-soft)" : "transparent",
                  color: selected === g.id ? "var(--accent)" : "inherit",
                  fontWeight: selected === g.id ? 600 : 400,
                }}>
                {g.name} <span style={{ color: "var(--muted)", fontSize: 12 }}>({g.company_ids.length})</span>
              </button>
            ))}
            {groups.length === 0 && !loading && (
              <div style={{ padding: 12, color: "var(--muted)", fontSize: 13 }}>No peer groups yet.</div>
            )}
          </nav>
        </Card>

        <Card title="Benchmark" subtitle={selected ? "Ranked by latest assessment score." : "Select a group on the left."} padded={false}>
          {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 }}>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
                    ? (BAND_LABEL[r.score_band] || r.score_band)
                    : <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) ?? "—" },
              ]}
            />
          )}
          {!benchmark && <div style={{ padding: 18, color: "var(--muted)", fontSize: 13.5 }}>No group selected.</div>}
        </Card>
      </div>
    </div>
  );
};

Object.assign(window, { NewAssessmentScreen, AssessmentDetailScreen, LiveDashboard, PeerGroupsScreen });
