// Tracker — list of all requests with status, deadline countdown, drill-in
function Tracker({ go }) {
  const [filter, setFilter] = React.useState("all");
  const [sel, setSel] = React.useState(null);
  const reqs = window.REQUESTS;

  const filtered = reqs.filter((r) => {
    if (filter === "all") return true;
    if (filter === "active") return !["fulfilled","refused","draft"].includes(r.status);
    if (filter === "closed") return ["fulfilled","refused"].includes(r.status);
    return r.status === filter;
  });

  if (sel) {
    return <RequestDetail r={sel} back={() => setSel(null)} />;
  }

  const tabs = [
    { id: "all",          label: "All",         count: reqs.length },
    { id: "active",       label: "Active",      count: reqs.filter((r) => !["fulfilled","refused","draft"].includes(r.status)).length },
    { id: "overdue",      label: "Overdue",     count: reqs.filter((r) => r.status === "overdue").length },
    { id: "internal-review", label: "Review",   count: reqs.filter((r) => r.status === "internal-review").length },
    { id: "closed",       label: "Closed",      count: reqs.filter((r) => ["fulfilled","refused"].includes(r.status)).length }
  ];

  return (
    <div>
      <SectionTitle sub="Every request, every recipient, every working day" action={
        <Button onClick={() => go("compose")} icon={<Ico.Plus/>}>New request</Button>
      }>Tracker</SectionTitle>

      <div style={{ display: "flex", gap: 4, marginBottom: 12, borderBottom: "1px solid var(--rule)" }}>
        {tabs.map((t) => (
          <button key={t.id} onClick={() => setFilter(t.id)} style={{
            background: "none", border: "none",
            padding: "10px 14px",
            fontSize: 13, fontFamily: "inherit",
            fontWeight: filter === t.id ? 600 : 500,
            color: filter === t.id ? "var(--text)" : "var(--muted)",
            borderBottom: filter === t.id ? "2px solid var(--accent)" : "2px solid transparent",
            cursor: "pointer",
            display: "inline-flex", alignItems: "center", gap: 8,
            marginBottom: -1
          }}>
            {t.label}
            <span style={{ fontSize: 11, fontFamily: "var(--font-mono)", color: "var(--muted)", background: "var(--surface-2)", padding: "0 6px", borderRadius: 2 }}>{t.count}</span>
          </button>
        ))}
      </div>

      <Card pad={0}>
        <table style={{ width: "100%", borderCollapse: "collapse", fontSize: 13 }}>
          <thead style={{ background: "var(--surface-2)" }}>
            <tr>
              <Th width={110}>Ref</Th>
              <Th>Title</Th>
              <Th width={170}>Recipient</Th>
              <Th width={130}>Status</Th>
              <Th width={180}>Deadline</Th>
              <Th width={90} num>Replies</Th>
              <Th width={110}>Owner</Th>
            </tr>
          </thead>
          <tbody>
            {filtered.map((r) => {
              const pct = r.workingDaysElapsed ? (r.workingDaysElapsed / 20) * 100 : 0;
              const tone = r.status === "overdue" ? "danger" : pct > 70 ? "warn" : "info";
              const daysLeft = 20 - r.workingDaysElapsed;
              return (
                <tr key={r.id}
                    onClick={() => setSel(r)}
                    style={{ cursor: "pointer", borderBottom: "1px solid var(--rule)" }}
                    onMouseEnter={(e) => e.currentTarget.style.background = "var(--surface-2)"}
                    onMouseLeave={(e) => e.currentTarget.style.background = "transparent"}>
                  <td style={{ padding: "12px 12px", fontFamily: "var(--font-mono)", fontSize: 11.5, color: "var(--muted)" }}>{r.id}</td>
                  <td style={{ padding: "12px 12px" }}>
                    <div style={{ fontWeight: 500, color: "var(--text)" }}>{r.title}</div>
                    <div style={{ display: "flex", gap: 6, marginTop: 4 }}>
                      {r.tags.map((t) => (
                        <span key={t} style={{ fontSize: 10.5, color: "var(--muted)", border: "1px solid var(--rule)", padding: "1px 6px", borderRadius: 2, fontFamily: "var(--font-mono)" }}>{t}</span>
                      ))}
                    </div>
                  </td>
                  <td style={{ padding: "12px 12px" }}>
                    <div style={{ fontSize: 12.5 }}>{r.recipientName}</div>
                    <div style={{ fontSize: 11, color: "var(--muted)", marginTop: 2 }}>{r.channel}</div>
                  </td>
                  <td style={{ padding: "12px 12px" }}><StatusPill status={r.status} /></td>
                  <td style={{ padding: "12px 12px" }}>
                    {r.sentOn ? (
                      <>
                        <div style={{ fontSize: 12, color: tone === "danger" ? "var(--danger-fg)" : "var(--text)", fontWeight: tone === "danger" ? 600 : 500, fontVariantNumeric: "tabular-nums" }}>
                          {daysLeft >= 0 ? `${daysLeft} day${daysLeft === 1 ? "" : "s"} left` : `${Math.abs(daysLeft)} day${Math.abs(daysLeft) === 1 ? "" : "s"} overdue`}
                        </div>
                        <div style={{ width: 140, marginTop: 6 }}><Bar pct={Math.min(100, pct)} tone={tone} /></div>
                      </>
                    ) : <span style={{ color: "var(--muted)" }}>—</span>}
                  </td>
                  <td style={{ padding: "12px 12px", textAlign: "right", fontVariantNumeric: "tabular-nums" }}>{r.replies}</td>
                  <td style={{ padding: "12px 12px", color: "var(--muted)" }}>{r.owner}</td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </Card>
    </div>
  );
}

function RequestDetail({ r, back }) {
  const replies = window.INBOX.filter((m) => m.requestId === r.id);
  const pct = r.workingDaysElapsed ? (r.workingDaysElapsed / 20) * 100 : 0;
  const tone = r.status === "overdue" ? "danger" : pct > 70 ? "warn" : "info";
  const daysLeft = 20 - r.workingDaysElapsed;

  const timeline = [
    { date: r.sentOn, label: "Dispatched", desc: `Sent via ${r.channel} to ${r.recipientName}`, ok: true },
    { date: r.sentOn, label: "Acknowledgement received", desc: "Recipient confirmed receipt", ok: r.workingDaysElapsed >= 2 },
    { date: r.deadline, label: "Substantive response due", desc: "20 working days from dispatch", ok: r.status === "fulfilled" || r.status === "partial" },
    { date: null, label: "Internal review window opens", desc: "If refused or partial", ok: r.status === "internal-review" || r.status === "fulfilled" }
  ];

  return (
    <div>
      <button onClick={back} style={{ background: "none", border: "none", color: "var(--muted)", fontSize: 13, cursor: "pointer", fontFamily: "inherit", marginBottom: 10, padding: 0 }}>← All requests</button>

      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", marginBottom: 20, gap: 24 }}>
        <div>
          <div style={{ fontFamily: "var(--font-mono)", fontSize: 12, color: "var(--muted)", marginBottom: 4 }}>{r.id}</div>
          <h2 style={{ margin: 0, fontSize: 22, fontWeight: 700, letterSpacing: "-0.01em", color: "var(--text)" }}>{r.title}</h2>
          <div style={{ fontSize: 13, color: "var(--muted)", marginTop: 6, maxWidth: 600 }}>{r.summary}</div>
        </div>
        <div style={{ display: "flex", gap: 8 }}>
          <Button variant="secondary" icon={<Ico.Edit/>}>Edit</Button>
          <Button variant="secondary" icon={<Ico.Mail/>}>Send follow-up</Button>
          {r.status === "refused" && <Button icon={<Ico.Warn/>}>Request internal review</Button>}
        </div>
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "2fr 1fr", gap: 16 }}>
        <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
          {r.sentOn && (
            <Card>
              <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 14 }}>
                <div>
                  <div style={{ fontWeight: 600, fontSize: 14 }}>20-working-day clock</div>
                  <div style={{ fontSize: 12, color: "var(--muted)", marginTop: 2 }}>FOIA s.10(1) statutory deadline</div>
                </div>
                <div style={{ textAlign: "right" }}>
                  <div style={{ fontSize: 28, fontWeight: 700, color: tone === "danger" ? "var(--danger-fg)" : "var(--text)", letterSpacing: "-0.02em", fontVariantNumeric: "tabular-nums" }}>
                    {daysLeft >= 0 ? `${daysLeft}` : `+${Math.abs(daysLeft)}`}
                  </div>
                  <div style={{ fontSize: 11, color: "var(--muted)", textTransform: "uppercase", letterSpacing: "0.06em", fontWeight: 600 }}>
                    {daysLeft >= 0 ? "days left" : "days overdue"}
                  </div>
                </div>
              </div>
              <Bar pct={Math.min(100, pct)} tone={tone} />
              <div style={{ display: "flex", justifyContent: "space-between", fontSize: 11, fontFamily: "var(--font-mono)", color: "var(--muted)", marginTop: 8 }}>
                <span>Sent {r.sentOn}</span>
                <span>Due {r.deadline}</span>
              </div>
            </Card>
          )}

          <Card pad={0}>
            <div style={{ padding: "14px 18px", borderBottom: "1px solid var(--rule)", fontWeight: 600, fontSize: 14 }}>Timeline</div>
            <div style={{ padding: "8px 18px 18px" }}>
              {timeline.map((step, i) => (
                <div key={i} style={{ display: "grid", gridTemplateColumns: "20px 1fr auto", gap: 14, padding: "12px 0", borderBottom: i < timeline.length - 1 ? "1px dashed var(--rule)" : "none", alignItems: "flex-start" }}>
                  <div style={{
                    width: 16, height: 16, borderRadius: "50%",
                    background: step.ok ? "var(--ok-bg)" : "var(--surface-2)",
                    border: `1px solid ${step.ok ? "var(--ok-bd)" : "var(--rule)"}`,
                    color: "var(--ok-fg)",
                    display: "grid", placeItems: "center",
                    marginTop: 2
                  }}>
                    {step.ok && <svg width="8" height="8" viewBox="0 0 8 8" fill="none" stroke="currentColor" strokeWidth="1.75"><path d="M1.5 4l1.5 1.5L6.5 2"/></svg>}
                  </div>
                  <div>
                    <div style={{ fontWeight: step.ok ? 600 : 500, fontSize: 13, color: step.ok ? "var(--text)" : "var(--muted)" }}>{step.label}</div>
                    <div style={{ fontSize: 12, color: "var(--muted)", marginTop: 2 }}>{step.desc}</div>
                  </div>
                  <div style={{ fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--muted)" }}>{step.date || "—"}</div>
                </div>
              ))}
            </div>
          </Card>

          {replies.length > 0 && (
            <Card pad={0}>
              <div style={{ padding: "14px 18px", borderBottom: "1px solid var(--rule)", display: "flex", justifyContent: "space-between" }}>
                <div style={{ fontWeight: 600, fontSize: 14 }}>Replies on this thread</div>
                <span style={{ fontFamily: "var(--font-mono)", fontSize: 12, color: "var(--muted)" }}>{replies.length} message{replies.length === 1 ? "" : "s"}</span>
              </div>
              {replies.map((m) => (
                <div key={m.id} style={{ padding: "12px 18px", borderBottom: "1px solid var(--rule)" }}>
                  <div style={{ display: "flex", justifyContent: "space-between" }}>
                    <div style={{ fontSize: 13, fontWeight: 500 }}>{m.fromName}</div>
                    <div style={{ fontSize: 11, fontFamily: "var(--font-mono)", color: "var(--muted)" }}>{m.receivedAt}</div>
                  </div>
                  <div style={{ fontSize: 12, color: "var(--muted)", marginTop: 4 }}>{m.subject}</div>
                  <div style={{ marginTop: 8 }}>
                    <Pill tone={m.extracted.responseClassification.includes("Partial") ? "warn" : m.extracted.responseClassification.includes("Full") ? "ok" : "info"}>
                      {m.extracted.responseClassification}
                    </Pill>
                  </div>
                </div>
              ))}
            </Card>
          )}
        </div>

        <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
          <Card>
            <div style={{ fontWeight: 600, fontSize: 14, marginBottom: 12 }}>Details</div>
            <div style={{ display: "grid", gridTemplateColumns: "auto 1fr", gap: "8px 14px", fontSize: 13 }}>
              <span style={{ color: "var(--muted)" }}>Status</span><span><StatusPill status={r.status}/></span>
              <span style={{ color: "var(--muted)" }}>Recipient</span><span>{r.recipientName}</span>
              <span style={{ color: "var(--muted)" }}>Channel</span><span>{r.channel}</span>
              <span style={{ color: "var(--muted)" }}>Sent</span><span style={{ fontFamily: "var(--font-mono)" }}>{r.sentOn || "—"}</span>
              <span style={{ color: "var(--muted)" }}>Owner</span><span>{r.owner}</span>
              <span style={{ color: "var(--muted)" }}>Replies</span><span style={{ fontVariantNumeric: "tabular-nums" }}>{r.replies}</span>
            </div>
          </Card>

          <Card>
            <div style={{ fontWeight: 600, fontSize: 14, marginBottom: 8 }}>Compliance checks</div>
            <ul style={{ paddingLeft: 0, margin: 0, listStyle: "none", fontSize: 13 }}>
              <li style={{ display: "flex", gap: 8, padding: "6px 0", borderBottom: "1px dashed var(--rule)" }}>
                <span style={{ color: "var(--ok-fg)" }}>✓</span><span>Within s.12 cost limit</span>
              </li>
              <li style={{ display: "flex", gap: 8, padding: "6px 0", borderBottom: "1px dashed var(--rule)" }}>
                <span style={{ color: "var(--ok-fg)" }}>✓</span><span>No vexatious-history flags</span>
              </li>
              <li style={{ display: "flex", gap: 8, padding: "6px 0", borderBottom: "1px dashed var(--rule)" }}>
                <span style={{ color: r.status === "overdue" ? "var(--danger-fg)" : "var(--ok-fg)" }}>{r.status === "overdue" ? "!" : "✓"}</span>
                <span>{r.status === "overdue" ? "Past 20-working-day deadline" : "Within 20-working-day window"}</span>
              </li>
              <li style={{ display: "flex", gap: 8, padding: "6px 0" }}>
                <span style={{ color: "var(--ok-fg)" }}>✓</span><span>Redaction pass complete</span>
              </li>
            </ul>
          </Card>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { Tracker, RequestDetail });
