/* Archive + Report viewer + Settings */

/* ------------------------------ ARCHIVE ------------------------------ */
function ArchiveScreen({ onNav, filterType = "all" }) {
  const [typeFilter, setTypeFilter] = useState(filterType);
  const [ragFilter, setRagFilter] = useState("all");
  const [query, setQuery] = useState("");
  const [view, setView] = useState("timeline"); // timeline | table
  const [allReports, setAllReports] = useState(null); // null = loading

  useEffect(() => { setTypeFilter(filterType); }, [filterType]);

  useEffect(() => {
    api.get("/api/reports").then(setAllReports).catch(() => setAllReports(DEMO_REPORTS));
  }, []);

  const sourceReports = allReports !== null ? allReports : DEMO_REPORTS;

  let reports = sourceReports.slice().sort((a, b) => b.date.localeCompare(a.date));
  if (typeFilter !== "all") reports = reports.filter(r => r.type === typeFilter);
  if (ragFilter !== "all") reports = reports.filter(r => (r.overall_rag || r.overall) === ragFilter);
  if (query) reports = reports.filter(r => {
    const t = reportTypeMeta(r.type);
    return (t ? t.name.toLowerCase().includes(query.toLowerCase()) : false) || r.date.includes(query);
  });

  // Group by date for timeline
  const byDate = {};
  reports.forEach(r => { (byDate[r.date] = byDate[r.date] || []).push(r); });
  const dates = Object.keys(byDate).sort((a, b) => b.localeCompare(a));

  const _rag = (r) => r.overall_rag || r.overall || "amber";

  return (
    <div className="page">
      <div className="page-head">
        <div>
          <div className="page-title">Archive</div>
          <div className="page-sub">{allReports === null ? "Loading…" : `${reports.length} reports · browse, filter, and compare past runs.`}</div>
        </div>
        <button className="btn btn-primary" onClick={() => onNav("generate")}>
          <I.Zap style={{ width: 14, height: 14 }} /> Generate new
        </button>
      </div>

      {/* Filter bar */}
      <div className="card mb-6" style={{ padding: 14 }}>
        <div className="row gap-3">
          <div className="row gap-2" style={{ flex: 1, padding: "0 10px", background: "var(--surface-2)", borderRadius: 6, height: 32 }}>
            <I.Search style={{ color: "var(--text-3)", width: 14, height: 14 }} />
            <input value={query} onChange={e => setQuery(e.target.value)} placeholder="Search by type or date…"
              style={{ flex: 1, border: "none", outline: "none", background: "transparent", fontSize: 13, color: "var(--text)", fontFamily: "inherit" }} />
            {query && <I.X onClick={() => setQuery("")} style={{ color: "var(--text-3)", width: 13, height: 13, cursor: "pointer" }} />}
          </div>

          <div className="row gap-1" style={{ background: "var(--surface-2)", padding: 3, borderRadius: 6, height: 32 }}>
            {[
              { id: "all", l: "All" },
              ...REPORT_TYPES.map(t => ({ id: t.id, l: t.shortName })),
            ].map(o => (
              <button key={o.id} onClick={() => setTypeFilter(o.id)} style={{
                padding: "3px 10px", border: "none", borderRadius: 4,
                background: typeFilter === o.id ? "var(--surface)" : "transparent",
                color: typeFilter === o.id ? "var(--text)" : "var(--text-2)",
                fontWeight: typeFilter === o.id ? 500 : 400, fontSize: 12, cursor: "pointer",
                boxShadow: typeFilter === o.id ? "var(--sh-sm)" : "none",
              }}>{o.l}</button>
            ))}
          </div>

          <div className="row gap-1" style={{ background: "var(--surface-2)", padding: 3, borderRadius: 6, height: 32 }}>
            {["all", "red", "amber", "green"].map(r => (
              <button key={r} onClick={() => setRagFilter(r)} style={{
                padding: "3px 10px", border: "none", borderRadius: 4,
                background: ragFilter === r ? "var(--surface)" : "transparent",
                color: ragFilter === r ? "var(--text)" : "var(--text-2)",
                fontWeight: ragFilter === r ? 500 : 400, fontSize: 12, cursor: "pointer",
                boxShadow: ragFilter === r ? "var(--sh-sm)" : "none",
                textTransform: "capitalize", display: "flex", alignItems: "center", gap: 5,
              }}>
                {r !== "all" && <div className={`dot dot-${r}`} style={{ width: 6, height: 6, boxShadow: "none" }}></div>}
                {r}
              </button>
            ))}
          </div>

          <div className="row gap-1" style={{ background: "var(--surface-2)", padding: 3, borderRadius: 6, height: 32 }}>
            {[{ id: "timeline", l: "Timeline" }, { id: "table", l: "Table" }].map(v => (
              <button key={v.id} onClick={() => setView(v.id)} style={{
                padding: "3px 10px", border: "none", borderRadius: 4,
                background: view === v.id ? "var(--surface)" : "transparent",
                color: view === v.id ? "var(--text)" : "var(--text-2)",
                fontWeight: view === v.id ? 500 : 400, fontSize: 12, cursor: "pointer",
                boxShadow: view === v.id ? "var(--sh-sm)" : "none",
              }}>{v.l}</button>
            ))}
          </div>
        </div>
      </div>

      {view === "timeline" && (
        <div className="col gap-8">
          {dates.map(date => {
            const group = byDate[date];
            const overall = _rag(group[0]);
            const d = new Date(date);
            const weekday = d.toLocaleDateString("en-GB", { weekday: "long" });
            const pretty = d.toLocaleDateString("en-GB", { day: "numeric", month: "long", year: "numeric" });
            return (
              <div key={date}>
                <div className="row mb-4" style={{ paddingBottom: 10, borderBottom: "1px solid var(--border)" }}>
                  <div>
                    <div className="row gap-3">
                      <div className="serif" style={{ fontSize: 22, fontWeight: 500, letterSpacing: "-0.02em" }}>{pretty}</div>
                      <RagPill status={overall} />
                    </div>
                    <div className="text-xs text-3 mt-1 mono">{weekday} · {group.length} report{group.length !== 1 ? "s" : ""}</div>
                  </div>
                  <div className="spacer"></div>
                  <button className="btn btn-ghost btn-sm" onClick={() => onNav("report", { reportId: group[0].id })}>
                    Open day summary <I.ChevRight style={{ width: 12, height: 12 }} />
                  </button>
                </div>
                <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(260px, 1fr))", gap: 12 }}>
                  {group.map(r => {
                    const t = reportTypeMeta(r.type);
                    const Icon = t.icon;
                    return (
                      <div key={r.id} className="card" style={{ cursor: "pointer", transition: "all 0.1s" }}
                        onClick={() => onNav("report", { reportId: r.id })}
                        onMouseEnter={e => { e.currentTarget.style.borderColor = "var(--border-2)"; e.currentTarget.style.boxShadow = "var(--sh-md)"; }}
                        onMouseLeave={e => { e.currentTarget.style.borderColor = "var(--border)"; e.currentTarget.style.boxShadow = "none"; }}
                      >
                        <div style={{ padding: 16 }}>
                          <div className="row mb-3">
                            <div style={{ width: 28, height: 28, borderRadius: 6, background: "var(--surface-2)", display: "flex", alignItems: "center", justifyContent: "center", color: t.color }}>
                              <Icon />
                            </div>
                            <div className="spacer"></div>
                            <RagDot status={_rag(r)} />
                          </div>
                          <div className="fw-500 mb-1">{t.name}</div>
                          <div className="text-xs text-3 mono">{r.id}.html</div>
                          <div className="row mt-4" style={{ fontSize: 11 }}>
                            <span className="text-3 mono">{(r.metrics || {}).velocityPct ?? "—"}% velocity</span>
                            <div className="spacer"></div>
                            <span className="text-3 mono">{(r.metrics || {}).overdue ?? "—"} overdue</span>
                          </div>
                        </div>
                      </div>
                    );
                  })}
                </div>
              </div>
            );
          })}
        </div>
      )}

      {view === "table" && (
        <div className="card">
          <table className="data">
            <thead>
              <tr>
                <th>Date</th><th>Report</th><th>Overall</th><th>Velocity</th><th>Overdue</th><th>Blockers</th><th>Author</th><th></th>
              </tr>
            </thead>
            <tbody>
              {reports.map(r => {
                const t = reportTypeMeta(r.type);
                const Icon = t ? t.icon : I.File;
                return (
                  <tr key={r.id} style={{ cursor: "pointer" }} onClick={() => onNav("report", { reportId: r.id })}>
                    <td className="mono text-2" style={{ width: 110 }}>{r.date}</td>
                    <td>
                      <div className="row gap-2">
                        <Icon style={{ color: t ? t.color : "var(--text-2)", width: 14, height: 14 }} />
                        <span className="fw-500">{t ? t.name : r.type}</span>
                      </div>
                    </td>
                    <td>{_rag(r) && <RagPill status={_rag(r)} />}</td>
                    <td className="mono">{(r.metrics || {}).velocityPct ?? "—"}%</td>
                    <td className="mono">{(r.metrics || {}).overdue ?? "—"}</td>
                    <td className="mono">{(r.metrics || {}).blockers ?? "—"}</td>
                    <td className="text-2 mono">{r.author}</td>
                    <td style={{ width: 30 }}><I.ArrowUpRight style={{ color: "var(--text-3)" }} /></td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
      )}
    </div>
  );
}

/* ------------------------------ REPORT VIEWER ------------------------------ */
function ReportViewer({ reportId, onNav }) {
  const [report, setReport] = useState(null);
  const [showHtml, setShowHtml] = useState(false);

  useEffect(() => {
    // Try API first, fall back to demo data
    api.get(`/api/reports/${reportId}`)
      .then(setReport)
      .catch(() => {
        const demo = DEMO_REPORTS.find(r => r.id === reportId) || DEMO_REPORTS[0];
        setReport(demo);
      });
  }, [reportId]);

  if (!report) {
    return <div className="page" style={{ display: "flex", alignItems: "center", justifyContent: "center", minHeight: 300 }}>
      <div className="text-2">Loading report…</div>
    </div>;
  }

  const t = reportTypeMeta(report.type);
  const Icon = t ? t.icon : I.File;
  const overallRag = report.overall_rag || report.overall || "amber";

  return (
    <div style={{ display: "flex", flexDirection: "column" }}>
      {/* Report toolbar */}
      <div style={{
        borderBottom: "1px solid var(--border)",
        padding: "12px 24px",
        display: "flex", alignItems: "center", gap: 12,
        background: "var(--surface)",
      }}>
        <button className="btn btn-ghost btn-sm" onClick={() => onNav("archive")}>
          <I.ChevRight style={{ transform: "rotate(180deg)", width: 13, height: 13 }} /> Archive
        </button>
        <div style={{ width: 1, height: 16, background: "var(--border)" }}></div>
        <Icon style={{ color: t ? t.color : "var(--text-2)", width: 16, height: 16 }} />
        <span className="fw-500">{t ? t.name : report.type}</span>
        <span className="text-3 mono text-xs">·  {report.date}</span>
        {overallRag && <RagPill status={overallRag} />}
        <div className="spacer"></div>
        {report.html_file && (
          <button className="btn btn-ghost btn-sm" onClick={() => setShowHtml(v => !v)}>
            <I.File style={{ width: 13, height: 13 }} /> {showHtml ? "Close HTML" : "View HTML"}
          </button>
        )}
        <button className="btn btn-ghost btn-sm"><I.Download style={{ width: 13, height: 13 }} /> PDF</button>
        <button className="btn btn-secondary btn-sm" onClick={() => onNav("generate", { preselect: [report.type] })}>
          <I.Zap style={{ width: 13, height: 13 }} /> Re-run
        </button>
      </div>

      {showHtml && report.html_file && (
        <iframe
          src={`/api/reports/${report.id}/html?token=${api._token()}`}
          style={{ width: "100%", height: "80vh", border: "none", borderBottom: "1px solid var(--border)" }}
          title="Report HTML"
        />
      )}

      <div className="page" style={{ maxWidth: 1040, padding: "40px 32px" }}>
        {/* Report header */}
        <div style={{ borderBottom: "1px solid var(--border)", paddingBottom: 24, marginBottom: 32 }}>
          <div className="row gap-2 mb-4">
            <div className="label-xs">{t ? t.shortName : report.type} Report</div>
            <span className="text-3">·</span>
            <div className="label-xs">Week ending {new Date(report.date).toLocaleDateString("en-GB", { day: "numeric", month: "long", year: "numeric" })}</div>
          </div>
          <div className="row gap-4" style={{ alignItems: "flex-start" }}>
            <div style={{ flex: 1 }}>
              <h1 className="serif" style={{ fontSize: 36, fontWeight: 500, letterSpacing: "-0.02em", lineHeight: 1.1, marginBottom: 12 }}>
                {t && t.name === "RAG Status" ? "Weekly Status — BuildLog" : (t ? t.name : report.type)}
              </h1>
              <div className="text-2" style={{ fontSize: 15, lineHeight: 1.6, maxWidth: 640 }}>
                {t ? t.desc : report.html_file || ""}
              </div>
            </div>
            <div className="col gap-2" style={{ alignItems: "flex-end", minWidth: 180 }}>
              {overallRag && (
                <div className={`pill pill-${overallRag}`} style={{ padding: "4px 12px", fontSize: 13 }}>
                  <span className={`dot dot-${overallRag}`} style={{ width: 7, height: 7, boxShadow: "none" }}></span>
                  Overall: {overallRag.toUpperCase()}
                </div>
              )}
              <div className="text-xs text-3 mono">{report.generated_at || report.generatedAt || report.date}</div>
              <div className="text-xs text-3 mono">{report.html_file || ""}</div>
            </div>
          </div>
        </div>

        {/* Executive summary */}
        {report.type === "rag" && <>
          {/* KPI strip */}
          <div className="label-xs mb-3">Key metrics</div>
          <div className="mb-8" style={{ display: "grid", gridTemplateColumns: "repeat(5, 1fr)", gap: 12 }}>
            {(() => {
              const m = report.metrics || {};
              return [
                { l: "Total issues", v: String(m.total_issues ?? "—"), c: null },
                { l: "Done", v: String(m.done ?? "—"), sub: m.completion_pct != null ? `${m.completion_pct}%` : null, c: "var(--green)" },
                { l: "In progress", v: String(m.in_progress ?? "—"), c: "var(--blue)" },
                { l: "Overdue", v: String(m.overdue ?? "—"), c: "var(--red)" },
                { l: "Blockers", v: String(m.blockers ?? "—"), c: "var(--red)" },
              ];
            })().map((m, i) => (
              <div key={i} className="card" style={{ padding: "14px 16px" }}>
                <div className="label-xs mb-2">{m.l}</div>
                <div className="row gap-2" style={{ alignItems: "flex-end" }}>
                  <div className="mono" style={{ fontSize: 24, fontWeight: 600, color: m.c || "var(--text)" }}>{m.v}</div>
                  {m.sub && <div className="text-xs text-3 mono" style={{ marginBottom: 4 }}>{m.sub}</div>}
                </div>
              </div>
            ))}
          </div>

          {/* Workstream narrative */}
          <div className="label-xs mb-3">Workstream detail</div>
          <div className="card mb-8">
            {(report.workstreams || []).map((w, i, arr) => (
              <div key={w.name} style={{ padding: 24, borderBottom: i < arr.length - 1 ? "1px solid var(--border)" : "none" }}>
                <div className="row mb-4">
                  <RagDot status={w.rag} />
                  <h3 className="serif" style={{ fontSize: 22, fontWeight: 500, letterSpacing: "-0.01em" }}>{w.name}</h3>
                  <div className="spacer"></div>
                  <span className="mono text-sm text-2">{w.sp} SP · {w.done} tasks</span>
                </div>
                <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 14, marginBottom: 16 }}>
                  {[
                    { l: "Velocity", v: `${w.velocity}%`, bar: w.velocity, rag: w.rag },
                    { l: "Completion", v: `${w.completion}%`, bar: w.completion, rag: w.rag },
                    { l: "Overdue", v: w.overdue, rag: w.overdue > 2 ? "red" : w.overdue > 0 ? "amber" : "green" },
                    { l: "Blockers", v: w.blockers, rag: w.blockers > 0 ? "red" : "green" },
                  ].map((m, j) => (
                    <div key={j}>
                      <div className="label-xs mb-2">{m.l}</div>
                      <div className="row gap-2">
                        <div className="mono" style={{ fontSize: 18, fontWeight: 600 }}>{m.v}</div>
                        <div className={`dot dot-${m.rag}`}></div>
                      </div>
                      {m.bar != null && (
                        <div className="bar-track mt-2">
                          <div className={`bar-fill ${m.rag}`} style={{ width: `${m.bar}%` }}></div>
                        </div>
                      )}
                    </div>
                  ))}
                </div>
                <div className="text-2" style={{ fontSize: 13, lineHeight: 1.6 }}>
                  {w.spent_h != null && w.estimated_h != null &&
                    <span className="mono text-xs">{w.spent_h}h spent / {w.estimated_h}h est · </span>}
                  {w.done != null && w.total != null &&
                    <span>{w.done}/{w.total} issues done</span>}
                  {w.bugs > 0 && <span> · {w.bugs} open bug{w.bugs !== 1 ? "s" : ""}</span>}
                </div>
              </div>
            ))}
          </div>

          {/* Top risks — full narrative in HTML report */}
          {report.html_file && (
            <div className="card mb-8" style={{ padding: "20px 24px" }}>
              <div className="row gap-3">
                <I.Alert style={{ color: "var(--amber)", width: 16, height: 16, flexShrink: 0 }} />
                <div>
                  <div className="fw-500 mb-1">Full narrative, risks &amp; next-week priorities</div>
                  <div className="text-sm text-2">The complete executive summary, top risks, and action items are in the HTML report generated by Claude.</div>
                </div>
                <button className="btn btn-secondary btn-sm" style={{ flexShrink: 0 }} onClick={() => setShowHtml(true)}>
                  <I.File style={{ width: 13, height: 13 }} /> View HTML
                </button>
              </div>
            </div>
          )}
        </>}

        {/* VELOCITY viewer */}
        {report.type === "velocity" && <VelocityView report={report} />}
        {report.type === "raid" && <RaidView report={report} />}
        {report.type === "pattern" && <PatternView report={report} />}

        <div className="text-xs text-3 mono" style={{ paddingTop: 24, borderTop: "1px solid var(--border)", textAlign: "center" }}>
          Generated by Pulse · {report.generatedAt} · buildlog001.atlassian.net · claude-sonnet-4.5
        </div>
      </div>
    </div>
  );
}

function VelocityView({ report }) {
  const m = report.metrics || {};
  const ws = report.workstreams || {};
  const streams = ws.streams || [];
  const overruns = ws.overruns || [];

  return (
    <>
      <div className="label-xs mb-3">Summary</div>
      <div className="mb-8" style={{ display: "grid", gridTemplateColumns: "repeat(5, 1fr)", gap: 12 }}>
        {[
          { l: "Overrun issues", v: String(m.overrun_issues ?? "—"), c: "var(--red)" },
          { l: "In progress",   v: String(m.in_progress ?? "—") },
          { l: "Logged hours",  v: m.total_logged_h != null ? String(m.total_logged_h) : "—", sub: "h" },
          { l: "Estimated",     v: m.total_estimated_h != null ? String(m.total_estimated_h) : "—", sub: "h" },
          { l: "Burn rate",     v: m.burn_rate_pct != null ? `${m.burn_rate_pct}%` : "—", c: m.burn_rate_pct >= 70 ? "var(--green)" : "var(--amber)" },
        ].map((kpi, i) => (
          <div key={i} className="card" style={{ padding: "14px 16px" }}>
            <div className="label-xs mb-2">{kpi.l}</div>
            <div className="row gap-1" style={{ alignItems: "flex-end" }}>
              <div className="mono" style={{ fontSize: 22, fontWeight: 600, color: kpi.c || "var(--text)" }}>{kpi.v}</div>
              {kpi.sub && <div className="text-xs text-3 mono" style={{ marginBottom: 3 }}>{kpi.sub}</div>}
            </div>
          </div>
        ))}
      </div>

      <div className="label-xs mb-3">Workstream velocity</div>
      <div className="card mb-8">
        <table className="data">
          <thead><tr><th>Workstream</th><th>SP Done</th><th>Velocity</th><th>Logged</th><th>Estimated</th><th>Overdue</th></tr></thead>
          <tbody>
            {streams.length > 0 ? streams.map(w => (
              <tr key={w.name}>
                <td className="fw-500">{w.name}</td>
                <td className="mono text-2">{w.sp}</td>
                <td>
                  <div className="row gap-3">
                    <div className="bar-track" style={{ width: 120 }}>
                      <div className={`bar-fill ${w.rag || "amber"}`} style={{ width: `${w.velocity_pct || 0}%` }}></div>
                    </div>
                    <span className="mono fw-500" style={{ color: `var(--${w.rag || "amber"})` }}>{w.velocity_pct ?? "—"}%</span>
                  </div>
                </td>
                <td className="mono text-2">{w.logged_h != null ? `${w.logged_h}h` : "—"}</td>
                <td className="mono text-2">{w.estimated_h != null ? `${w.estimated_h}h` : "—"}</td>
                <td className="mono"><span style={{ color: (w.overdue || 0) > 2 ? "var(--red)" : "var(--text-2)" }}>{w.overdue ?? "—"}</span></td>
              </tr>
            )) : (
              <tr><td colSpan={6} className="text-2 text-sm" style={{ padding: 16, textAlign: "center" }}>No workstream data — view HTML report for details</td></tr>
            )}
          </tbody>
        </table>
      </div>

      {overruns.length > 0 && <>
        <div className="label-xs mb-3">Time overruns — {overruns.length} issues over estimate</div>
        <div className="card">
          <table className="data">
            <thead><tr><th>Key</th><th>Summary</th><th>Assignee</th><th>Est.</th><th>Logged</th><th>Overrun</th></tr></thead>
            <tbody>
              {overruns.map(o => {
                const rag = o.overrun_pct > 60 ? "red" : "amber";
                return (
                  <tr key={o.key}>
                    <td><span className="pill mono" style={{ fontSize: 11 }}>{o.key}</span></td>
                    <td>{o.summary}</td>
                    <td className="mono text-2">{o.assignee}</td>
                    <td className="mono text-2">{o.estimate_h}h</td>
                    <td className="mono text-2">{o.spent_h}h</td>
                    <td>
                      <div className="row gap-3">
                        <div className="bar-track" style={{ width: 100 }}>
                          <div className={`bar-fill ${rag}`} style={{ width: `${Math.min(o.overrun_pct / 2, 100)}%` }}></div>
                        </div>
                        <span className="mono fw-500" style={{ color: `var(--${rag})` }}>+{o.overrun_pct}%</span>
                      </div>
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
      </>}
    </>
  );
}

function RaidView({ report }) {
  const rows = report.workstreams || [];
  const m = report.metrics || {};

  return (
    <>
      <div className="label-xs mb-3">RAID Log — {rows.length || m.total || 0} entries</div>
      <div className="row gap-2 mb-4">
        <span className="pill pill-red"><span className="dot dot-red" style={{ width: 6, height: 6, boxShadow: "none" }}></span>P1 · High (6–9)</span>
        <span className="pill pill-amber"><span className="dot dot-amber" style={{ width: 6, height: 6, boxShadow: "none" }}></span>P2 · Medium (3–4)</span>
        <span className="pill pill-green"><span className="dot dot-green" style={{ width: 6, height: 6, boxShadow: "none" }}></span>P3 · Low (1–2)</span>
      </div>
      <div className="card">
        <table className="data">
          <thead>
            <tr>
              <th>Pri</th><th>Cat.</th><th>Key</th><th>Summary</th>
              <th>P</th><th>I</th><th>Score</th><th>Mitigation</th><th>Owner</th><th>Due</th>
            </tr>
          </thead>
          <tbody>
            {rows.length > 0 ? rows.map((r, idx) => {
              const rag = r.priority === "P1" ? "red" : r.priority === "P2" ? "amber" : "green";
              return (
                <tr key={`${r.category}-${r.key || idx}`}>
                  <td><span className={`pill pill-${rag}`} style={{ fontSize: 10 }}>{r.priority}</span></td>
                  <td className="fw-500 text-sm">{r.category}</td>
                  <td><span className="pill mono" style={{ fontSize: 11 }}>{r.key}</span></td>
                  <td className="text-sm">{r.summary}</td>
                  <td className="mono text-xs text-2">{r.probability}</td>
                  <td className="mono text-xs text-2">{r.impact}</td>
                  <td className="mono fw-600" style={{ color: `var(--${rag})` }}>{r.score}</td>
                  <td className="text-sm text-2">{r.mitigation}</td>
                  <td className="mono text-2 text-sm">{r.owner}</td>
                  <td className="mono text-2 text-sm">{r.due || "—"}</td>
                </tr>
              );
            }) : (
              <tr><td colSpan={10} className="text-2 text-sm" style={{ padding: 16, textAlign: "center" }}>No RAID data — view HTML report for details</td></tr>
            )}
          </tbody>
        </table>
      </div>
    </>
  );
}

function PatternView({ report }) {
  const m = report.metrics || {};
  const ws = report.workstreams || {};
  const currentFp = ws.current_fp || {};
  const historical = ws.historical || [];
  const matchFound = m.match_found;
  const alertColor = matchFound ? "var(--red)" : "var(--amber)";
  const alertBg = matchFound ? "var(--red-bg)" : "color-mix(in oklab, var(--amber) 10%, var(--surface))";
  const alertBorder = matchFound ? "color-mix(in oklab, var(--red) 30%, var(--border))" : "color-mix(in oklab, var(--amber) 30%, var(--border))";

  const fpRows = [
    { label: "Velocity",         val: currentFp.velocity,         pct: true },
    { label: "Completion rate",  val: currentFp.completion_rate,  pct: true },
    { label: "Overdue ratio",    val: currentFp.overdue_ratio,    pct: true, invert: true },
    { label: "Blocker ratio",    val: currentFp.blocker_ratio,    pct: true, invert: true },
    { label: "Open bugs ratio",  val: currentFp.open_bugs_ratio,  pct: true, invert: true },
  ].filter(r => r.val != null);

  return (
    <>
      <div className="card mb-8" style={{ borderColor: alertBorder, background: `color-mix(in oklab, ${alertColor} 3%, var(--surface))` }}>
        <div style={{ padding: 24, display: "flex", gap: 20, alignItems: "flex-start" }}>
          <div style={{ width: 48, height: 48, borderRadius: 10, background: alertBg, color: alertColor, display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}>
            <I.Alert style={{ width: 22, height: 22 }} />
          </div>
          <div style={{ flex: 1 }}>
            {matchFound ? (
              <>
                <div className="row gap-3 mb-2">
                  <span className="pill pill-red">PATTERN MATCH</span>
                  {m.similarity_pct > 0 && <span className="mono fw-600" style={{ color: "var(--red)" }}>{m.similarity_pct}% similarity</span>}
                </div>
                <div className="fw-600 mb-2" style={{ fontSize: 17 }}>
                  Matched: {m.matched_sprint || "Historical sprint"} — {m.matched_outcome || "Historical delay/overrun"}
                </div>
              </>
            ) : (
              <div className="row gap-3 mb-2">
                <span className="pill pill-green">NO MATCH</span>
                <span className="fw-600">No dangerous pattern detected</span>
              </div>
            )}
            {m.narrative && (
              <p className="text-2 text-sm" style={{ lineHeight: 1.7, marginBottom: 8 }}>{m.narrative}</p>
            )}
          </div>
        </div>
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 20, marginBottom: 32 }}>
        <div>
          <div className="label-xs mb-3">Current sprint fingerprint</div>
          <div className="card">
            {fpRows.length > 0 ? (
              <div style={{ padding: "8px 0" }}>
                {fpRows.map((f, i, arr) => {
                  const pctVal = Math.round((f.val || 0) * 100);
                  const rag = f.invert
                    ? (pctVal > 30 ? "red" : pctVal > 10 ? "amber" : "green")
                    : (pctVal < 40 ? "red" : pctVal < 70 ? "amber" : "green");
                  const risk = rag === "red" ? "HIGH RISK" : rag === "amber" ? "ELEVATED" : "OK";
                  return (
                    <div key={f.label} style={{
                      padding: "14px 20px", borderBottom: i < arr.length - 1 ? "1px solid var(--border)" : "none",
                      display: "grid", gridTemplateColumns: "1fr auto auto", gap: 12, alignItems: "center"
                    }}>
                      <span className="text-sm fw-500">{f.label}</span>
                      <div className="row gap-3">
                        <div className="bar-track" style={{ width: 100 }}>
                          <div className={`bar-fill ${rag}`} style={{ width: `${Math.min(pctVal, 100)}%` }}></div>
                        </div>
                        <span className="mono fw-500" style={{ width: 36, textAlign: "right" }}>{pctVal}%</span>
                      </div>
                      <span className={`pill pill-${rag}`} style={{ fontSize: 10 }}>{risk}</span>
                    </div>
                  );
                })}
              </div>
            ) : (
              <div className="text-sm text-2" style={{ padding: 20, textAlign: "center" }}>No fingerprint data</div>
            )}
          </div>
        </div>

        <div>
          <div className="label-xs mb-3">Historical matches</div>
          <div className="card">
            {historical.length > 0 ? (
              <div>
                {historical.slice(0, 5).map((h, i, arr) => {
                  const sim = Math.round((h.similarity || 0) * 100);
                  const rag = h.is_bad_sprint ? "red" : "green";
                  return (
                    <div key={h.sprint_name || i} style={{
                      padding: "14px 20px",
                      borderBottom: i < arr.length - 1 ? "1px solid var(--border)" : "none",
                      display: "grid", gridTemplateColumns: "1fr auto auto", gap: 12, alignItems: "center"
                    }}>
                      <div>
                        <div className="fw-500 text-sm">{h.sprint_name}</div>
                        <div className="text-xs text-3">{h.outcome || (h.is_bad_sprint ? "Historical delay/overrun" : "On-time delivery")}</div>
                      </div>
                      <div className="mono fw-500" style={{ color: `var(--${rag})` }}>{sim}%</div>
                      <RagDot status={rag} />
                    </div>
                  );
                })}
              </div>
            ) : (
              <div className="text-sm text-2" style={{ padding: 20, textAlign: "center" }}>No historical data</div>
            )}
          </div>
        </div>
      </div>
    </>
  );
}

/* ------------------------------ SETTINGS ------------------------------ */
function SettingsScreen() {
  const [tab, setTab] = useState("general");
  const [settings, setSettings] = useState(null);
  const [saving, setSaving] = useState(false);
  const [saveMsg, setSaveMsg] = useState("");
  const [testStatus, setTestStatus] = useState("");
  const [connStatus, setConnStatus] = useState("checking"); // "checking" | "ok" | "failed"
  const [schedStatus, setSchedStatus] = useState(null); // { active, next_run }
  const [slackTestStatus, setSlackTestStatus] = useState(""); // "" | "Testing…" | "✓ Sent" | "✗ Failed"
  const [complianceData, setComplianceData] = useState(null); // null | { no_log_issues, compliance }
  const [complianceLoading, setComplianceLoading] = useState(false);

  const loadSchedStatus = () =>
    api.get("/api/schedule/status").then(setSchedStatus).catch(() => {});

  useEffect(() => {
    api.get("/api/settings").then(data => {
      setSettings(data);
      setAppTz(data.schedule_timezone);
      api.post("/api/settings/test-connection", {
        jira_url: data.jira_url,
        jira_email: data.jira_email,
      }).then(r => setConnStatus(r.ok ? "ok" : "failed")).catch(() => setConnStatus("failed"));
    }).catch(() => setConnStatus("failed"));
    loadSchedStatus();
  }, []);

  const updateField = (key, val) => setSettings(s => ({ ...s, [key]: val }));

  const saveSettings = async () => {
    setSaving(true); setSaveMsg("");
    try {
      await api.put("/api/settings", settings);
      setSaveMsg("Saved");
      loadSchedStatus();
    } catch (e) {
      setSaveMsg("Error: " + e.message);
    } finally {
      setSaving(false);
      setTimeout(() => setSaveMsg(""), 3000);
    }
  };

  const testSlack = async () => {
    setSlackTestStatus("Sending…");
    try {
      const { ok } = await api.post("/api/settings/test-slack", {});
      setSlackTestStatus(ok ? "✓ Sent to Slack" : "✗ Failed");
    } catch {
      setSlackTestStatus("✗ Error");
    }
    setTimeout(() => setSlackTestStatus(""), 4000);
  };

  const loadCompliance = async () => {
    setComplianceLoading(true);
    try {
      const data = await api.get("/api/agents/timelog/compliance");
      setComplianceData(data);
    } catch (e) {
      setComplianceData({ error: e.message || "Failed to load" });
    } finally {
      setComplianceLoading(false);
    }
  };

  const testConnection = async () => {
    setTestStatus("Testing…");
    setConnStatus("checking");
    try {
      const { ok } = await api.post("/api/settings/test-connection", {
        jira_url: settings?.jira_url,
        jira_email: settings?.jira_email,
        jira_api_token: settings?.jira_api_token,
      });
      setTestStatus(ok ? "✓ Connected" : "✗ Failed");
      setConnStatus(ok ? "ok" : "failed");
    } catch {
      setTestStatus("✗ Error");
      setConnStatus("failed");
    }
    setTimeout(() => setTestStatus(""), 4000);
  };
  return (
    <div className="page" style={{ maxWidth: 960 }}>
      <div className="page-head">
        <div>
          <div className="page-title">Settings</div>
          <div className="page-sub">Configure your Jira connection, schedule, and report preferences.</div>
        </div>
      </div>

      <div className="row gap-0 mb-6" style={{ borderBottom: "1px solid var(--border)" }}>
        {[
          { id: "general", l: "General" },
          { id: "jira", l: "Jira connection" },
          { id: "schedule", l: "Schedule" },
          { id: "reports", l: "Reports" },
          { id: "notify", l: "Notifications" },
          { id: "team", l: "Team" },
        ].map(t => (
          <button key={t.id} onClick={() => setTab(t.id)} style={{
            padding: "10px 16px", border: "none", background: "transparent",
            color: tab === t.id ? "var(--text)" : "var(--text-2)",
            fontWeight: tab === t.id ? 500 : 400, fontSize: 13, cursor: "pointer",
            borderBottom: `2px solid ${tab === t.id ? "var(--text)" : "transparent"}`,
            marginBottom: -1,
          }}>{t.l}</button>
        ))}
      </div>

      {tab === "general" && (
        <div className="card mb-6">
          <div className="card-head">
            <div>
              <div className="card-title">General</div>
              <div className="text-xs text-3 mt-1">Display preferences applied across all dates, times, and the scheduler.</div>
            </div>
          </div>
          <div style={{ padding: 20, display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16 }}>
            <div className="field">
              <label>Timezone</label>
              <select className="input"
                value={settings?.schedule_timezone || "Europe/Kyiv"}
                onChange={e => { updateField("schedule_timezone", e.target.value); setAppTz(e.target.value); }}>
                {[
                  "UTC",
                  "Europe/London", "Europe/Dublin", "Europe/Lisbon",
                  "Europe/Paris", "Europe/Berlin", "Europe/Rome", "Europe/Madrid", "Europe/Amsterdam",
                  "Europe/Warsaw", "Europe/Prague", "Europe/Vienna", "Europe/Budapest",
                  "Europe/Kyiv", "Europe/Bucharest", "Europe/Sofia", "Europe/Athens",
                  "Europe/Helsinki", "Europe/Tallinn", "Europe/Riga", "Europe/Vilnius",
                  "Europe/Istanbul", "Europe/Moscow", "Europe/Minsk",
                  "Asia/Dubai", "Asia/Karachi", "Asia/Kolkata", "Asia/Dhaka",
                  "Asia/Bangkok", "Asia/Ho_Chi_Minh", "Asia/Jakarta",
                  "Asia/Singapore", "Asia/Kuala_Lumpur", "Asia/Manila",
                  "Asia/Shanghai", "Asia/Hong_Kong", "Asia/Taipei",
                  "Asia/Seoul", "Asia/Tokyo",
                  "Australia/Perth", "Australia/Adelaide", "Australia/Sydney", "Australia/Brisbane",
                  "Pacific/Auckland", "Pacific/Fiji",
                  "America/Anchorage", "America/Los_Angeles", "America/Denver",
                  "America/Chicago", "America/New_York", "America/Toronto",
                  "America/Mexico_City", "America/Bogota", "America/Lima",
                  "America/Sao_Paulo", "America/Argentina/Buenos_Aires",
                  "Atlantic/Reykjavik", "Atlantic/Azores",
                ].map(tz => <option key={tz} value={tz}>{tz.replace(/_/g, " ")}</option>)}
              </select>
              <div className="text-xs text-3 mt-1">Affects all date/time displays and scheduled run timing.</div>
            </div>
          </div>
          <div className="card-head" style={{ borderTop: "1px solid var(--border)", borderBottom: "none" }}>
            <span className="text-xs text-3 mono">{saveMsg || ""}</span>
            <button className="btn btn-primary btn-sm" onClick={saveSettings} disabled={saving}>
              {saving ? "Saving…" : "Save changes"}
            </button>
          </div>
        </div>
      )}

      {tab === "jira" && (
        <div className="card mb-6">
          <div className="card-head">
            <div>
              <div className="card-title">Jira Cloud connection</div>
              <div className="text-xs text-3 mt-1">Used by all agents to fetch issues and fields.</div>
            </div>
            {connStatus === "checking" && (
              <span className="pill"><span className="dot" style={{ width: 6, height: 6, boxShadow: "none", background: "var(--text-3)" }}></span>Checking…</span>
            )}
            {connStatus === "ok" && (
              <span className="pill pill-green"><span className="dot dot-green" style={{ width: 6, height: 6, boxShadow: "none" }}></span>Connected</span>
            )}
            {connStatus === "failed" && (
              <span className="pill pill-red"><span className="dot dot-red" style={{ width: 6, height: 6, boxShadow: "none" }}></span>Not connected</span>
            )}
          </div>
          <div style={{ padding: 20, display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16 }}>
            <div className="field">
              <label>Jira URL</label>
              <input className="input mono" value={settings?.jira_url || ""} onChange={e => updateField("jira_url", e.target.value)} />
            </div>
            <div className="field">
              <label>Project key</label>
              <input className="input mono" value={settings?.jira_project_key || ""} onChange={e => updateField("jira_project_key", e.target.value)} />
            </div>
            <div className="field">
              <label>Email</label>
              <input className="input mono" value={settings?.jira_email || ""} onChange={e => updateField("jira_email", e.target.value)} />
            </div>
            <div className="field">
              <label>API token</label>
              <div className="row gap-2">
                <input className="input mono" type="password" value={settings?.jira_api_token || ""} onChange={e => updateField("jira_api_token", e.target.value)} placeholder="●●●●●●●●" />
                <button className="btn btn-secondary" onClick={testConnection} disabled={!!testStatus}>
                  {testStatus || "Test"}
                </button>
              </div>
            </div>
          </div>
          <div className="card-head" style={{ borderTop: "1px solid var(--border)", borderBottom: "none" }}>
            <span className="text-xs text-3 mono">{saveMsg || "Changes saved automatically"}</span>
            <button className="btn btn-primary btn-sm" onClick={saveSettings} disabled={saving}>
              {saving ? "Saving…" : "Save changes"}
            </button>
          </div>
        </div>
      )}

      {tab === "schedule" && (() => {
        const schedEnabled = settings?.schedule_enabled !== "false";
        const toggleEnabled = () => updateField("schedule_enabled", schedEnabled ? "false" : "true");

        const [schedHour, schedMin] = (settings?.schedule_time || "17:00").split(":").map(Number);
        const updateTime = (h, m) => {
          const hh = Math.min(23, Math.max(0, isNaN(h) ? 0 : h));
          const mm = Math.min(59, Math.max(0, isNaN(m) ? 0 : m));
          updateField("schedule_time", `${String(hh).padStart(2, "0")}:${String(mm).padStart(2, "0")}`);
        };

        const numStepper = (val, minVal, maxVal, onChangeFn) => {
          const step = (delta) => (e) => { e.preventDefault(); onChangeFn(Math.min(maxVal, Math.max(minVal, val + delta))); };
          return (
            <div style={{ display: "flex", flex: 1, alignItems: "stretch", border: "1px solid var(--border)", borderRadius: 6, overflow: "hidden", background: "var(--surface)" }}>
              <input
                type="text" inputMode="numeric"
                value={String(val)}
                onFocus={e => e.target.select()}
                onClick={e => e.target.select()}
                onChange={e => {
                  const v = parseInt(e.target.value.replace(/\D/g, ""), 10);
                  onChangeFn(isNaN(v) ? minVal : Math.min(maxVal, Math.max(minVal, v)));
                }}
                onBlur={e => {
                  const v = parseInt(e.target.value, 10);
                  onChangeFn(isNaN(v) ? minVal : Math.min(maxVal, Math.max(minVal, v)));
                }}
                style={{
                  flex: 1, minWidth: 0, border: "none", outline: "none",
                  padding: "6px 0", textAlign: "center",
                  fontFamily: "monospace", fontSize: 14, fontWeight: 500,
                  background: "transparent", color: "var(--text)", cursor: "text",
                }}
              />
              <div style={{ display: "flex", flexDirection: "column", width: 22, borderLeft: "1px solid var(--border)", flexShrink: 0 }}>
                <button onMouseDown={step(1)}
                  style={{ flex: 1, border: "none", background: "transparent", cursor: "pointer", padding: 0, color: "var(--text-2)", fontSize: 9, display: "flex", alignItems: "center", justifyContent: "center" }}
                  onMouseEnter={e => e.currentTarget.style.background = "var(--surface-2)"}
                  onMouseLeave={e => e.currentTarget.style.background = "transparent"}>▲</button>
                <div style={{ height: 1, background: "var(--border)" }} />
                <button onMouseDown={step(-1)}
                  style={{ flex: 1, border: "none", background: "transparent", cursor: "pointer", padding: 0, color: "var(--text-2)", fontSize: 9, display: "flex", alignItems: "center", justifyContent: "center" }}
                  onMouseEnter={e => e.currentTarget.style.background = "var(--surface-2)"}
                  onMouseLeave={e => e.currentTarget.style.background = "transparent"}>▼</button>
              </div>
            </div>
          );
        };

        const allIds = REPORT_TYPES.map(t => t.id);
        const agentsStr = settings?.schedule_agents || "all";
        const selectedAgents = new Set(agentsStr === "all" ? allIds : agentsStr.split(",").filter(Boolean));
        const toggleAgent = (id) => {
          const next = new Set(selectedAgents);
          if (next.has(id)) { if (next.size === 1) return; next.delete(id); } else next.add(id);
          updateField("schedule_agents", next.size === allIds.length ? "all" : [...next].join(","));
        };

        const isActive = schedEnabled && schedStatus?.active;

        return (
          <div className="card mb-6">
            <div className="card-head">
              <div className="card-title">Automated runs</div>
              <div className="row gap-3" style={{ alignItems: "center" }}>
                {schedStatus === null
                  ? <span className="text-xs text-3">Loading…</span>
                  : isActive
                    ? <span className="pill pill-green"><span className="dot dot-green" style={{ width: 6, height: 6, boxShadow: "none" }}></span>Active</span>
                    : <span className="pill pill-red"><span className="dot dot-red" style={{ width: 6, height: 6, boxShadow: "none" }}></span>Inactive</span>
                }
                <div title={schedEnabled ? "Disable schedule" : "Enable schedule"}
                  onClick={toggleEnabled}
                  style={{
                    width: 36, height: 20, borderRadius: 100, padding: 2, cursor: "pointer",
                    background: schedEnabled ? "var(--text)" : "var(--border-2)",
                    transition: "background 0.15s", flexShrink: 0,
                  }}>
                  <div style={{
                    width: 16, height: 16, borderRadius: 100, background: "var(--surface)",
                    transform: schedEnabled ? "translateX(16px)" : "translateX(0)",
                    transition: "transform 0.15s",
                  }} />
                </div>
              </div>
            </div>

            <div style={{ padding: 20, display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16, opacity: schedEnabled ? 1 : 0.45, pointerEvents: schedEnabled ? "auto" : "none" }}>
              <div className="field">
                <label>Run every</label>
                <select className="input" value={settings?.schedule_day || "friday"} onChange={e => updateField("schedule_day", e.target.value)}>
                  <option value="monday">Monday</option>
                  <option value="tuesday">Tuesday</option>
                  <option value="wednesday">Wednesday</option>
                  <option value="thursday">Thursday</option>
                  <option value="friday">Friday</option>
                  <option value="saturday">Saturday</option>
                  <option value="sunday">Sunday</option>
                  <option value="weekday">Every weekday (Mon–Fri)</option>
                </select>
              </div>

              <div className="field">
                <label>At</label>
                <div className="row gap-1" style={{ alignItems: "center" }}>
                  {numStepper(isNaN(schedHour) ? 0 : schedHour, 0, 23, h => updateTime(h, schedMin))}
                  <span style={{ fontSize: 11, color: "var(--text-3)", fontFamily: "monospace", padding: "0 2px" }}>h</span>
                  {numStepper(isNaN(schedMin) ? 0 : schedMin, 0, 59, m => updateTime(schedHour, m))}
                  <span style={{ fontSize: 11, color: "var(--text-3)", fontFamily: "monospace", padding: "0 2px" }}>m</span>
                </div>
              </div>

              <div className="field">
                <label>Timezone</label>
                <div className="input mono text-2" style={{ userSelect: "none", cursor: "default", color: "var(--text-3)" }}>
                  {settings?.schedule_timezone || "Europe/Kyiv"}
                  <span style={{ marginLeft: 8, fontSize: 11 }}>— change in General tab</span>
                </div>
              </div>

              <div className="field">
                <label>Next run</label>
                <div className="input mono text-2" style={{ userSelect: "none", cursor: "default" }}>
                  {schedStatus?.next_run
                    ? new Date(schedStatus.next_run).toLocaleString("en-GB", { weekday: "short", day: "numeric", month: "short", year: "numeric", hour: "2-digit", minute: "2-digit", timeZone: appTz() })
                    : "—"}
                </div>
              </div>
            </div>

            <div style={{ padding: 20, borderTop: "1px solid var(--border)", opacity: schedEnabled ? 1 : 0.45, pointerEvents: schedEnabled ? "auto" : "none" }}>
              <div className="label-xs mb-3">Reports to run</div>
              <div className="col gap-2">
                {REPORT_TYPES.map(t => (
                  <label key={t.id} className="row gap-3" style={{ cursor: "pointer" }} onClick={() => toggleAgent(t.id)}>
                    <div style={{
                      width: 16, height: 16, borderRadius: 4, border: `1.5px solid ${selectedAgents.has(t.id) ? "var(--text)" : "var(--border-2)"}`,
                      background: selectedAgents.has(t.id) ? "var(--text)" : "transparent",
                      display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0,
                    }}>
                      {selectedAgents.has(t.id) && <I.Check style={{ width: 10, height: 10, color: "var(--accent-fg)", strokeWidth: 3 }} />}
                    </div>
                    <t.icon style={{ color: t.color, width: 14, height: 14 }} />
                    <span className="text-sm fw-500">{t.name}</span>
                    <span className="spacer"></span>
                    <span className="text-xs text-3 mono">{t.runtime}</span>
                  </label>
                ))}
              </div>
            </div>

            <div className="card-head" style={{ borderTop: "1px solid var(--border)", borderBottom: "none" }}>
              <span className="text-xs text-3 mono">{saveMsg || "Save to apply schedule changes"}</span>
              <button className="btn btn-primary btn-sm" onClick={saveSettings} disabled={saving}>
                {saving ? "Saving…" : "Save changes"}
              </button>
            </div>
          </div>
        );
      })()}

      {tab === "reports" && (
        <div className="card mb-6">
          <div className="card-head"><div className="card-title">RAG thresholds</div></div>
          <div style={{ padding: 20 }}>
            <table className="data">
              <thead><tr><th>Metric</th><th>🔴 RED</th><th>🟡 AMBER</th><th>🟢 GREEN</th></tr></thead>
              <tbody>
                <tr><td className="fw-500">Velocity</td><td className="mono">&lt; 60%</td><td className="mono">60–80%</td><td className="mono">&gt; 80%</td></tr>
                <tr><td className="fw-500">Overdue tasks</td><td className="mono">3+</td><td className="mono">1–2</td><td className="mono">0</td></tr>
                <tr><td className="fw-500">Critical blockers</td><td className="mono">&gt; 2 days</td><td className="mono">with mitigation</td><td className="mono">none</td></tr>
                <tr><td className="fw-500">Open critical bugs</td><td className="mono">2+</td><td className="mono">1</td><td className="mono">0</td></tr>
                <tr><td className="fw-500">Completion rate</td><td className="mono">&lt; 50%</td><td className="mono">50–75%</td><td className="mono">&gt; 75%</td></tr>
              </tbody>
            </table>
          </div>
        </div>
      )}

      {tab === "notify" && (() => {
        const toggle = (field) => updateField(field, settings?.[field] === "true" ? "false" : "true");
        const isOn = (field) => settings?.[field] !== "false";

        const Toggle = ({ field, size = 36 }) => {
          const on = isOn(field);
          const knob = size === 36 ? 16 : 14;
          return (
            <div onClick={() => toggle(field)} style={{
              width: size, height: size === 36 ? 20 : 18, borderRadius: 100, padding: 2, cursor: "pointer", flexShrink: 0,
              background: on ? "var(--text)" : "var(--border-2)", transition: "background 0.15s",
            }}>
              <div style={{
                width: knob, height: knob, borderRadius: 100, background: "var(--surface)",
                transform: on ? `translateX(${size - knob - 4}px)` : "translateX(0)", transition: "transform 0.15s",
              }} />
            </div>
          );
        };

        const SectionRow = ({ label, sub, field, children }) => (
          <div className="row" style={{ padding: "14px 0", borderBottom: "1px solid var(--border)", alignItems: "center", gap: 16 }}>
            <div style={{ flex: 1 }}>
              <div className="fw-500 text-sm">{label}</div>
              {sub && <div className="text-xs text-3 mono mt-1">{sub}</div>}
            </div>
            {field ? <Toggle field={field} /> : children}
          </div>
        );

        const AgentRow = ({ label, enabledField, sub, children }) => (
          <div style={{ padding: "14px 0", borderBottom: "1px solid var(--border)" }}>
            <div className="row mb-2">
              <div>
                <span className="fw-500 text-sm">{label}</span>
                {sub && <span className="text-xs text-3 mono ml-2">{sub}</span>}
              </div>
              <div className="spacer" />
              <Toggle field={enabledField} />
            </div>
            {isOn(enabledField) && (
              <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10, paddingLeft: 4 }}>
                {children}
              </div>
            )}
          </div>
        );

        const complianceItems = complianceData?.compliance || [];
        const overallPct = complianceItems.length
          ? Math.round(complianceItems.reduce((s, c) => s + c.compliance_pct, 0) / complianceItems.length)
          : null;

        return (
          <div className="col gap-6">

            {/* ── Slack ── */}
            <div className="card">
              <div className="card-head">
                <div>
                  <div className="card-title">Slack</div>
                  <div className="text-xs text-3 mt-1">
                    {settings?.slack_bot_token ? "Bot Token configured" : "Bot Token not set"}
                  </div>
                </div>
                <Toggle field="notify_slack_enabled" />
              </div>

              <div style={{ padding: "0 20px 4px", opacity: isOn("notify_slack_enabled") ? 1 : 0.45, pointerEvents: isOn("notify_slack_enabled") ? "auto" : "none" }}>
                <SectionRow label="Bot Token" sub="xoxb-… stored in .env">
                  <div className="row gap-2" style={{ flex: 1, maxWidth: 360 }}>
                    <input className="input mono" type="password"
                      value={settings?.slack_bot_token || ""}
                      onChange={e => updateField("slack_bot_token", e.target.value)}
                      placeholder="xoxb-…" style={{ flex: 1 }} />
                    <button className="btn btn-secondary btn-sm" onClick={testSlack} disabled={!!slackTestStatus}>
                      {slackTestStatus || "Test"}
                    </button>
                  </div>
                </SectionRow>

                <SectionRow label="Default channel" sub="Fallback for all alerts">
                  <input className="input mono" value={settings?.slack_channel || ""}
                    onChange={e => updateField("slack_channel", e.target.value)}
                    placeholder="#rag" style={{ width: 160 }} />
                </SectionRow>

                <SectionRow label="Internal / weekly reports" sub="Weekly RAG digest (5.1)">
                  <input className="input mono" value={settings?.slack_channel_internal || ""}
                    onChange={e => updateField("slack_channel_internal", e.target.value)}
                    placeholder="leave blank to use default" style={{ width: 200 }} />
                </SectionRow>

                <SectionRow label="Alerts channel" sub="Anomaly & escalation alerts (5.2–5.6)">
                  <input className="input mono" value={settings?.slack_channel_alerts || ""}
                    onChange={e => updateField("slack_channel_alerts", e.target.value)}
                    placeholder="leave blank to use default" style={{ width: 200 }} />
                </SectionRow>

                <div className="row" style={{ padding: "14px 0", gap: 24 }}>
                  <span className="fw-500 text-sm" style={{ minWidth: 120 }}>Alert on RAG change</span>
                  <div className="row gap-3">
                    <label className="row gap-2" style={{ cursor: "pointer", fontSize: 13 }}>
                      <Toggle field="notify_on_red" size={32} /> 🔴 RED
                    </label>
                    <label className="row gap-2" style={{ cursor: "pointer", fontSize: 13 }}>
                      <Toggle field="notify_on_amber" size={32} /> 🟡 AMBER
                    </label>
                  </div>
                </div>
              </div>

              <div className="card-head" style={{ borderTop: "1px solid var(--border)", borderBottom: "none" }}>
                <span className="text-xs text-3 mono">{saveMsg || ""}</span>
                <button className="btn btn-primary btn-sm" onClick={saveSettings} disabled={saving}>
                  {saving ? "Saving…" : "Save"}
                </button>
              </div>
            </div>

            {/* ── Agent Alerts ── */}
            <div className="card">
              <div className="card-head">
                <div className="card-title">Agent Alerts</div>
                <div className="text-xs text-3 mono">Configure thresholds and enable/disable each agent's Slack alert</div>
              </div>
              <div style={{ padding: "0 20px 4px" }}>
                <AgentRow label="Velocity Anomaly" enabledField="velocity_anomaly_enabled" sub="Daily · 08:00">
                  <div className="field">
                    <label>Overrun threshold</label>
                    <div className="row gap-1">
                      <input className="input mono" type="number" step="0.01" min="1.01" max="3"
                        value={settings?.velocity_threshold || "1.15"}
                        onChange={e => updateField("velocity_threshold", e.target.value)}
                        style={{ width: 80 }} />
                      <span className="text-xs text-3 mono" style={{ alignSelf: "center" }}>
                        ({Math.round(((parseFloat(settings?.velocity_threshold) || 1.15) - 1) * 100)}% over estimate)
                      </span>
                    </div>
                  </div>
                </AgentRow>

                <AgentRow label="Dependency Staleness" enabledField="dependency_alert_enabled" sub="Daily · 08:30">
                  <div className="field">
                    <label>Stale after</label>
                    <div className="row gap-1">
                      <input className="input mono" type="number" min="1" max="30"
                        value={settings?.staleness_days_threshold || "3"}
                        onChange={e => updateField("staleness_days_threshold", e.target.value)}
                        style={{ width: 70 }} />
                      <span className="text-xs text-3 mono" style={{ alignSelf: "center" }}>days without update</span>
                    </div>
                  </div>
                </AgentRow>

                <AgentRow label="RAID Escalation" enabledField="raid_agent_enabled" sub="Weekly · Mon 09:00">
                  <div className="field">
                    <label>Escalate at score ≥</label>
                    <div className="row gap-1">
                      <input className="input mono" type="number" min="1" max="9"
                        value={settings?.raid_score_threshold || "6"}
                        onChange={e => updateField("raid_score_threshold", e.target.value)}
                        style={{ width: 60 }} />
                      <span className="text-xs text-3 mono" style={{ alignSelf: "center" }}>/ 9 (P × I)</span>
                    </div>
                  </div>
                </AgentRow>

                <AgentRow label="Time Log Reminder" enabledField="time_log_reminder_enabled" sub="Daily · 17:00">
                  <div className="field">
                    <label>Grace period</label>
                    <div className="row gap-1">
                      <input className="input mono" type="number" min="1" max="48"
                        value={settings?.time_log_grace_hours || "8"}
                        onChange={e => updateField("time_log_grace_hours", e.target.value)}
                        style={{ width: 60 }} />
                      <span className="text-xs text-3 mono" style={{ alignSelf: "center" }}>hours before reminder</span>
                    </div>
                  </div>
                </AgentRow>
              </div>

              <div className="card-head" style={{ borderTop: "1px solid var(--border)", borderBottom: "none" }}>
                <span className="text-xs text-3 mono">{saveMsg || ""}</span>
                <button className="btn btn-primary btn-sm" onClick={saveSettings} disabled={saving}>
                  {saving ? "Saving…" : "Save"}
                </button>
              </div>
            </div>

            {/* ── Email ── */}
            <div className="card">
              <div className="card-head">
                <div>
                  <div className="card-title">Email</div>
                  <div className="text-xs text-3 mt-1">SMTP Gmail · Phase 3c</div>
                </div>
                <Toggle field="notify_email_enabled" />
              </div>

              <div style={{ padding: "0 20px 4px", opacity: isOn("notify_email_enabled") ? 1 : 0.45, pointerEvents: isOn("notify_email_enabled") ? "auto" : "none" }}>
                <SectionRow label="PM email" sub="Receives weekly digest and RAID escalations">
                  <input className="input mono" value={settings?.email_pm || ""}
                    onChange={e => updateField("email_pm", e.target.value)}
                    placeholder="pm@company.com" style={{ width: 240 }} />
                </SectionRow>
                <SectionRow label="Tech Lead email" sub="Receives RAID P1 escalations">
                  <input className="input mono" value={settings?.email_techlead || ""}
                    onChange={e => updateField("email_techlead", e.target.value)}
                    placeholder="techlead@company.com" style={{ width: 240 }} />
                </SectionRow>
                <SectionRow label="Test email" sub="">
                  <div className="row gap-2">
                    <button className="btn btn-secondary btn-sm" disabled title="SMTP not configured — see Phase 3c">
                      Send test
                    </button>
                    <span className="pill text-xs">Phase 3c</span>
                  </div>
                </SectionRow>
              </div>

              <div className="card-head" style={{ borderTop: "1px solid var(--border)", borderBottom: "none" }}>
                <span className="text-xs text-3 mono">{saveMsg || ""}</span>
                <button className="btn btn-primary btn-sm" onClick={saveSettings} disabled={saving}>
                  {saving ? "Saving…" : "Save"}
                </button>
              </div>
            </div>

            {/* ── Time Compliance widget ── */}
            <div className="card">
              <div className="card-head">
                <div>
                  <div className="card-title">Time Logging Compliance</div>
                  <div className="text-xs text-3 mt-1">In Progress tasks without any time logged today</div>
                </div>
                <button className="btn btn-secondary btn-sm" onClick={loadCompliance} disabled={complianceLoading}>
                  {complianceLoading ? "Loading…" : "Refresh"}
                </button>
              </div>

              {!complianceData && !complianceLoading && (
                <div style={{ padding: 24, textAlign: "center", color: "var(--text-3)", fontSize: 13 }}>
                  Click Refresh to fetch live data from Jira.
                </div>
              )}

              {complianceData?.error && (
                <div style={{ padding: 20, color: "var(--red)", fontSize: 13 }}>{complianceData.error}</div>
              )}

              {complianceData && !complianceData.error && (
                <div>
                  <div className="row gap-4" style={{ padding: "16px 20px", borderBottom: "1px solid var(--border)" }}>
                    <div style={{ textAlign: "center" }}>
                      <div style={{ fontSize: 28, fontWeight: 800, color: overallPct >= 80 ? "var(--green)" : overallPct >= 50 ? "var(--amber)" : "var(--red)" }}>
                        {overallPct !== null ? `${overallPct}%` : "—"}
                      </div>
                      <div className="text-xs text-3">Overall compliance</div>
                    </div>
                    <div style={{ borderLeft: "1px solid var(--border)", padding: "0 0 0 16px" }}>
                      <div style={{ fontSize: 22, fontWeight: 700 }}>{complianceData.no_log_issues?.length ?? 0}</div>
                      <div className="text-xs text-3">tasks with no time logged</div>
                    </div>
                  </div>

                  {complianceItems.length > 0 && (
                    <table className="data">
                      <thead><tr><th>Assignee</th><th>Logged / Tasks</th><th>Compliance</th></tr></thead>
                      <tbody>
                        {complianceItems.map(c => (
                          <tr key={c.name}>
                            <td className="fw-500 text-sm">{c.name}</td>
                            <td className="mono text-sm">{c.logged_count}/{c.task_count}</td>
                            <td>
                              <div className="row gap-2">
                                <div style={{
                                  width: 60, height: 6, borderRadius: 3, background: "var(--surface-2)", overflow: "hidden",
                                }}>
                                  <div style={{
                                    width: `${c.compliance_pct}%`, height: "100%",
                                    background: c.compliance_pct >= 80 ? "var(--green)" : c.compliance_pct >= 50 ? "var(--amber)" : "var(--red)",
                                  }} />
                                </div>
                                <span className="mono text-sm">{c.compliance_pct}%</span>
                              </div>
                            </td>
                          </tr>
                        ))}
                      </tbody>
                    </table>
                  )}

                  {complianceData.no_log_issues?.length > 0 && (
                    <div style={{ padding: "12px 20px 16px", borderTop: "1px solid var(--border)" }}>
                      <div className="label-xs mb-2">Tasks with no time logged</div>
                      <div className="col gap-1">
                        {complianceData.no_log_issues.map(i => (
                          <div key={i.key} className="row gap-2 text-sm">
                            <code style={{ fontSize: 11, background: "var(--surface-2)", padding: "1px 5px", borderRadius: 3 }}>{i.key}</code>
                            <span className="text-2">{i.assignee}</span>
                            <span className="text-3 text-xs" style={{ flex: 1, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{i.summary}</span>
                          </div>
                        ))}
                      </div>
                    </div>
                  )}
                </div>
              )}
            </div>
          </div>
        );
      })()}

      {tab === "team" && (
        <div className="card mb-6">
          <div className="card-head">
            <div className="card-title">Team members</div>
            <button className="btn btn-secondary btn-sm"><I.Plus style={{ width: 12, height: 12 }} /> Invite</button>
          </div>
          <table className="data">
            <thead><tr><th>Member</th><th>Role</th><th>Access</th><th>Last active</th></tr></thead>
            <tbody>
              {[
                { n: "Maks K.", e: "maks@pulse.app", r: "Delivery Manager", a: "Owner", la: "Now" },
                { n: "Alex P.", e: "alex.petrov@company.com", r: "Backend Lead", a: "Editor", la: "2h ago" },
                { n: "Natasha W.", e: "natasha.web@company.com", r: "Frontend Lead", a: "Editor", la: "5h ago" },
                { n: "Dmitri F.", e: "dmitri.fox@company.com", r: "QA Lead", a: "Editor", la: "1d ago" },
                { n: "Olga Q.", e: "olga.qa@company.com", r: "QA", a: "Viewer", la: "3d ago" },
              ].map(m => (
                <tr key={m.e}>
                  <td>
                    <div className="row gap-3">
                      <div className="avatar" style={{ width: 24, height: 24, fontSize: 10 }}>{m.n.split(" ").map(x => x[0]).join("")}</div>
                      <div>
                        <div className="fw-500 text-sm">{m.n}</div>
                        <div className="text-xs text-3 mono">{m.e}</div>
                      </div>
                    </div>
                  </td>
                  <td className="text-sm text-2">{m.r}</td>
                  <td><span className="pill">{m.a}</span></td>
                  <td className="text-xs text-3 mono">{m.la}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}
    </div>
  );
}

Object.assign(window, { ArchiveScreen, ReportViewer, SettingsScreen });
