// ADM-PROC-05 · Requirement detail (AMOMS Module 1)
// Admin Web · Procurement Manager / Officer · P0 · 1440×900
// Components: C-014 Status pill · C-019 Tab bar · C-209 Detail layout · C-001 Button
//             C-108 Confirmation modal · C-110 KPI card · C-123 Timeline / audit log
// Registered as window.Pages.reqDetail

const Ic5 = window.Icons;
const BUILT_05 = window.BUILT_PAGES;
const KES5 = (n) => "KSh " + (Number(n) || 0).toLocaleString("en-US");
const prettyD5 = (s) => new Date(s + "T00:00:00").toLocaleDateString("en-GB", { day: "numeric", month: "short", year: "numeric" });

// The requirement on show (PR-2026-0184). `detailState` tweak overrides its lifecycle.
const REQ = {
  id: "PR-2026-0184", product: "Hass", spec: "Min 200g/fruit, grade A, dry matter ≥ 24%",
  qty: 28_000, variance: 10, rate: 95, rateType: "ceiling",
  start: "2026-05-19", end: "2026-05-26", deadline: "2026-05-19",
  priority: "normal", grade: "Export", ref: "WK3-2026",
  createdBy: "Caroline Wanjala", createdInit: "CW", createdAt: "2026-05-10 08:14", updatedAt: "2026-05-12 07:20",
  version: 2, versions: 2,
  notes: "Prioritise Kangema & Kandara groups — strong last cycle. Hold 10% buffer for QC rejects.",
  orderId: "SO-2026-0413",
};

const RESP = window.MD.RESPONSES;
const SHORTLIST = RESP.filter(r => r.status === "shortlist");
const qtyOffered = RESP.reduce((s, r) => s + r.qty, 0);
const avgRate = Math.round(RESP.reduce((s, r) => s + r.rate, 0) / RESP.length);

const CHANNELS = [
  { key: "App",      icon: Ic5.Mobile, sent: 142, delivered: 142, read: 118 },
  { key: "SMS",      icon: Ic5.Phone,  sent: 142, delivered: 139, read: 96 },
  { key: "WhatsApp", icon: Ic5.Mail,   sent: 96,  delivered: 94,  read: 71 },
];
const GROUPS = [
  { name: "Kangema growers", count: 58 },
  { name: "Kandara co-op", count: 47 },
  { name: "Othaya outgrowers", count: 37 },
];

const VERSIONS = [
  { v: 2, when: "2026-05-12 07:20", by: "Caroline Wanjala", note: "Raised rate ceiling KSh 92 → 95 and re-broadcast to all groups.", current: true },
  { v: 1, when: "2026-05-10 08:14", by: "Caroline Wanjala", note: "Initial requirement created — 28,000 kg Hass, KSh 92/kg ceiling.", current: false },
];

const ACTIVITY = [
  { tone: "avocado", icon: Ic5.User,        text: "Mary Wairimu responded — 6,200 kg @ KSh 92/kg", when: "2026-05-12 07:18" },
  { tone: "avocado", icon: Ic5.User,        text: "Esther Njeri responded — 5,400 kg @ KSh 94/kg", when: "2026-05-12 06:55" },
  { tone: "info",    icon: Ic5.Bolt,        text: "Re-broadcast (v2) to 142 farmers via App, SMS & WhatsApp", when: "2026-05-12 07:20" },
  { tone: "warning", icon: Ic5.Edit,        text: "Caroline Wanjala raised rate ceiling KSh 92 → 95", when: "2026-05-12 07:19" },
  { tone: "info",    icon: Ic5.Bolt,        text: "Broadcast (v1) to 142 farmers via App, SMS & WhatsApp", when: "2026-05-10 09:02" },
  { tone: "soil",    icon: Ic5.Plus,        text: "Requirement created by Caroline Wanjala", when: "2026-05-10 08:14" },
];

// ── Live time-remaining ticker (updates each second; tone shifts <24h / <2h) ──
const useTicker = (offsetMs) => {
  const end = useMemo(() => Date.now() + offsetMs, [offsetMs]);
  const [, force] = useState(0);
  useEffect(() => { const t = setInterval(() => force(n => n + 1), 1000); return () => clearInterval(t); }, []);
  const ms = end - Date.now();
  if (ms <= 0) return { text: "Deadline passed", tone: "overdue", passed: true };
  const d = Math.floor(ms / 864e5), h = Math.floor((ms % 864e5) / 36e5), m = Math.floor((ms % 36e5) / 6e4), s = Math.floor((ms % 6e4) / 1e3);
  const text = d > 0 ? `${d}d ${h}h ${m}m` : h > 0 ? `${h}h ${m}m ${s}s` : `${m}m ${s}s`;
  const tone = ms < 2 * 36e5 ? "overdue" : ms < 24 * 36e5 ? "soon" : "ok";
  return { text, tone, passed: false };
};

// ── Detail card ──
const DCard = ({ title, icon: I, action, children }) => (
  <Card style={{ marginBottom: 16 }}>
    <div className="card-head">
      <div className="head-text" style={{ flexDirection: "row", alignItems: "center", gap: 8 }}>
        {I && <span className="rd-card-ic"><I size={15} /></span>}
        <div className="card-title">{title}</div>
      </div>
      {action}
    </div>
    <div className="card-body" style={{ paddingTop: 2 }}>{children}</div>
  </Card>
);

const Spec = ({ label, value, strong }) => (
  <div className="rd-spec">
    <span className="rd-spec-label">{label}</span>
    <span className="rd-spec-value" style={strong ? { fontWeight: 600 } : undefined}>{value}</span>
  </div>
);

// ── Cancel modal ──
const CancelModal5 = ({ open, onClose, onConfirm }) => {
  const [reason, setReason] = useState("");
  useEffect(() => { if (open) setReason(""); }, [open]);
  if (!open) return null;
  return (
    <Modal open={open} onClose={onClose} title={`Cancel ${REQ.id}?`} sub="Respondents will be notified the requirement is withdrawn."
      footer={<>
        <Button variant="outline" onClick={onClose}>Keep requirement</Button>
        <Button variant="destructive" onClick={() => onConfirm(reason)} disabled={!reason.trim()}>Cancel requirement</Button>
      </>}>
      <div className="field">
        <label className="label">Reason for cancellation <span className="req">*</span></label>
        <textarea className="textarea" placeholder="e.g. Demand covered by another requirement." value={reason} onChange={(e) => setReason(e.target.value)} />
        <div className="field-hint">Recorded on the activity log and shown to respondents.</div>
      </div>
    </Modal>
  );
};

// ── Header kebab ──
const HeadKebab = ({ onAction, canArchive }) => {
  const [open, setOpen] = useState(false);
  return (
    <div className="proc-menu-wrap">
      <button className="btn btn-outline btn-icon" aria-label="More actions" onClick={() => setOpen(o => !o)}><Ic5.More size={16} /></button>
      {open && (
        <>
          <div className="proc-menu-scrim" onClick={() => setOpen(false)} />
          <div className="proc-menu right" style={{ minWidth: 190 }}>
            <button className="proc-menu-item" onClick={() => { setOpen(false); onAction("duplicate"); }}><Ic5.Layers size={14} /><span>Duplicate</span></button>
            <button className="proc-menu-item danger" onClick={() => { setOpen(false); onAction("cancel"); }}><Ic5.XCircle size={14} /><span>Cancel…</span></button>
            <div className="proc-menu-sep" />
            <button className="proc-menu-item" disabled={!canArchive} style={!canArchive ? { opacity: 0.4, cursor: "default" } : undefined} onClick={() => { setOpen(false); canArchive && onAction("archive"); }}><Ic5.Box size={14} /><span>Archive</span></button>
          </div>
        </>
      )}
    </div>
  );
};

// ── Skeleton ──
const DetailSkeleton = () => (
  <div className="page">
    <div className="sk lg" style={{ width: 280, marginBottom: 10 }} />
    <div className="sk" style={{ width: 420, marginBottom: 24 }} />
    <div className="rd-grid">
      <div>{[0, 1, 2].map(i => <Card key={i} style={{ marginBottom: 16 }}><div className="card-body">{[60, 80, 50].map((w, j) => <div key={j} className="sk" style={{ width: w + "%", marginBottom: 10 }} />)}</div></Card>)}</div>
      <div><Card><div className="card-body">{[70, 50, 60, 40].map((w, j) => <div key={j} className="sk" style={{ width: w + "%", marginBottom: 12 }} />)}</div></Card></div>
    </div>
  </div>
);

// ── Page ──
const RequirementDetail = ({ tweaks }) => {
  const toast = useToast();
  const ds = (tweaks && tweaks.detailState) || "receiving";
  const go = (file) => { if (BUILT_05.includes(file)) window.location.href = file; else toast({ title: `${file.replace(".html", "")} isn't part of this prototype`, tone: "danger" }); };

  const [tab, setTab] = useState("overview");
  const [notes, setNotes] = useState(REQ.notes);
  const [editingNotes, setEditingNotes] = useState(false);
  const [cancelOpen, setCancelOpen] = useState(false);
  const [status, setStatus] = useState(ds);
  useEffect(() => { setStatus(ds); if (ds === "draft") setTab("overview"); }, [ds]);

  // Ticker offset by state
  const offset = status === "pastdeadline" ? -36e5 : status === "receiving" ? (6 * 864e5 + 18 * 36e5) : status === "draft" ? (7 * 864e5) : (3 * 864e5);
  const ticker = useTicker(offset);

  if (status === "loading") return <DetailSkeleton />;

  const isDraft = status === "draft";
  const isCancelled = status === "cancelled";
  const isApproved = status === "approved";
  const postBroadcast = ["receiving", "pastdeadline", "approved"].includes(status);
  const canApprove = SHORTLIST.length > 0 && (status === "receiving" || status === "pastdeadline");
  const respCount = isDraft ? 0 : RESP.length;

  const statusKey = status === "receiving" ? "receiving" : status === "pastdeadline" ? "receiving" : status === "approved" ? "approved" : status === "cancelled" ? "cancelled" : "draft";

  const onAction = (a) => {
    if (a === "duplicate") { toast({ title: "Duplicating into a new draft" }); go("ADM-PROC-03.html"); }
    else if (a === "cancel") setCancelOpen(true);
    else if (a === "archive") { toast({ title: `${REQ.id} archived` }); go("ADM-PROC-02.html"); }
  };

  const tabs = [
    { value: "overview", label: "Overview" },
    { value: "responses", label: "Responses", count: respCount },
    { value: "broadcast", label: "Broadcast status" },
    { value: "versions", label: "Versions" },
    { value: "activity", label: "Activity" },
  ];

  return (
    <div className={`page rd-page${isCancelled ? " rd-dimmed" : ""}`}>
      {/* Header bar */}
      <div className="rd-head">
        <button className="btn btn-ghost btn-icon" aria-label="Back" onClick={() => go("ADM-PROC-02.html")}><Ic5.ChevronLeft size={18} /></button>
        <div className="rd-head-title">
          <div className="rd-id-row">
            <span className="mono rd-id">{REQ.id}</span>
            <StatusBadge status={statusKey} />
            {REQ.priority === "urgent" && <Badge tone="soil" icon={Ic5.Bolt}>Urgent</Badge>}
          </div>
          <h1 className="rd-title">{REQ.product} — {REQ.qty.toLocaleString("en-US")} kg · {REQ.grade}</h1>
        </div>
        <div className="rd-head-actions">
          {isDraft && <Button variant="outline" icon={Ic5.Edit} onClick={() => go("ADM-PROC-06.html")}>Edit</Button>}
          {isDraft && <Button variant="primary" icon={Ic5.Bolt} onClick={() => go("ADM-PROC-07.html")}>Broadcast</Button>}
          {postBroadcast && <Button variant="outline" icon={Ic5.Eye} onClick={() => go("ADM-PROC-10.html")}>View responses</Button>}
          {canApprove && <Button variant="primary" icon={Ic5.CheckCircle} onClick={() => go("ADM-PROC-13.html")}>Approve &amp; confirm</Button>}
          <HeadKebab onAction={onAction} canArchive={isCancelled} />
        </div>
      </div>

      {/* Sub-header strip */}
      <div className="rd-substrip">
        <span><Avatar initials={REQ.createdInit} size="sm" /> Created by <b>{REQ.createdBy}</b></span>
        <span className="rd-dot">·</span>
        <span>{prettyD5(REQ.createdAt.slice(0, 10))}</span>
        <span className="rd-dot">·</span>
        <span>Updated {REQ.updatedAt.slice(5, 16)}</span>
        <span className="rd-dot">·</span>
        <span className="rd-ver">v{REQ.version} of {REQ.versions}</span>
      </div>

      {/* State banners */}
      {isDraft && (
        <div className="alert" style={{ marginBottom: 16, background: "var(--info-soft)", borderColor: "oklch(from var(--info) l c h / 0.3)" }}>
          <span className="alert-icon" style={{ color: "var(--info)" }}><Ic5.Info size={16} /></span>
          <div className="alert-body">
            <div className="alert-title">This is a draft</div>
            <div className="alert-desc">Broadcast it to start receiving responses from farmers. You can still edit every field until then.</div>
          </div>
        </div>
      )}
      {status === "pastdeadline" && (
        <div className="alert alert-warning" style={{ marginBottom: 16 }}>
          <span className="alert-icon"><Ic5.Clock size={16} /></span>
          <div className="alert-body">
            <div className="alert-title">Response deadline passed</div>
            <div className="alert-desc">No new responses can arrive. Review the {RESP.length} received and award the shortlist.</div>
          </div>
        </div>
      )}
      {isApproved && (
        <div className="alert alert-success" style={{ marginBottom: 16 }}>
          <span className="alert-icon"><Ic5.CheckCircle size={16} /></span>
          <div className="alert-body">
            <div className="alert-title">Order confirmed · awaiting fulfilment</div>
            <div className="alert-desc">Linked to order <b className="mono">{REQ.orderId}</b>. Track delivery in Sales &amp; Orders.</div>
          </div>
        </div>
      )}
      {isCancelled && (
        <div className="alert alert-soil" style={{ marginBottom: 16 }}>
          <span className="alert-icon"><Ic5.XCircle size={16} /></span>
          <div className="alert-body">
            <div className="alert-title">Requirement cancelled</div>
            <div className="alert-desc">Reason: Demand covered by PR-2026-0182. Respondents were notified. Archive to remove from active lists.</div>
          </div>
        </div>
      )}

      {/* Tab bar */}
      <div style={{ marginBottom: 16 }}>
        <Tabs value={tab} onChange={(v) => { if (v === "responses" && isDraft) { toast({ title: "No responses yet", desc: "Broadcast the draft first." }); return; } setTab(v); }} options={tabs} />
      </div>

      {/* ───── Overview ───── */}
      {tab === "overview" && (
        <div className="rd-grid">
          {/* Left column */}
          <div className="rd-main">
            <DCard title="Requirement" icon={Ic5.Procurement}>
              <div className="rd-spec-grid">
                <Spec label="Product" value={<Badge tone="avocado">{REQ.product}</Badge>} />
                <Spec label="Grade" value={REQ.grade} />
                <Spec label="Target quantity" value={`${REQ.qty.toLocaleString("en-US")} kg`} strong />
                <Spec label="Acceptable variance" value={`±${REQ.variance}%`} />
              </div>
              <div className="rd-notefield" style={{ marginTop: 14 }}>
                <div className="rd-spec-label" style={{ marginBottom: 4 }}>Specification</div>
                <div style={{ fontSize: 13.5, lineHeight: 1.5 }}>{REQ.spec}</div>
              </div>
            </DCard>

            <DCard title="Pricing" icon={Ic5.Coin}>
              <div className="rd-spec-grid">
                <Spec label="Rate" value={<span style={{ fontWeight: 600 }}>{KES5(REQ.rate)}<span className="muted" style={{ fontWeight: 400 }}>/kg</span></span>} />
                <Spec label="Rate type" value={<Badge tone="pulp">{REQ.rateType === "ceiling" ? "Ceiling (max)" : REQ.rateType === "target" ? "Target" : "Floor (min)"}</Badge>} />
                <Spec label="Reference" value={<span className="mono" style={{ fontSize: 12.5 }}>{REQ.ref}</span>} />
                <Spec label="Est. budget" value={KES5(REQ.rate * REQ.qty)} />
              </div>
            </DCard>

            <DCard title="Timeline" icon={Ic5.Calendar}>
              <div className="rd-timeline">
                <div className="rd-tl-item">
                  <span className="rd-tl-dot ok" />
                  <div><div className="rd-tl-label">Response deadline</div><div className="rd-tl-val">{prettyD5(REQ.deadline)}</div></div>
                </div>
                <div className="rd-tl-item">
                  <span className="rd-tl-dot" />
                  <div><div className="rd-tl-label">Delivery window</div><div className="rd-tl-val">{prettyD5(REQ.start)} – {prettyD5(REQ.end)}</div></div>
                </div>
              </div>
              {!isDraft && !isCancelled && (
                <div className={`rd-ticker rd-ticker-${ticker.tone}`}>
                  <Ic5.Clock size={15} />
                  <span>{ticker.passed ? "Response window closed" : "Time remaining"}</span>
                  <b>{ticker.text}</b>
                </div>
              )}
            </DCard>

            <DCard title="Internal notes" icon={Ic5.Edit}
              action={!isCancelled && (editingNotes
                ? <Button size="sm" variant="primary" onClick={() => { setEditingNotes(false); toast({ title: "Notes saved" }); }}>Save</Button>
                : <Button size="sm" variant="ghost" icon={Ic5.Edit} onClick={() => setEditingNotes(true)}>Edit</Button>)}>
              {editingNotes
                ? <textarea className="textarea" value={notes} onChange={(e) => setNotes(e.target.value)} autoFocus />
                : <div style={{ fontSize: 13.5, lineHeight: 1.55, color: notes ? "var(--foreground)" : "var(--muted-foreground)" }}>{notes || "No internal notes."}</div>}
              <div className="field-hint" style={{ marginTop: 8 }}>Visible only to the procurement team — never shown to farmers.</div>
            </DCard>
          </div>

          {/* Right rail */}
          <div className="rd-side">
            <Card className="rd-rail-card" style={{ marginBottom: 16 }}>
              <div className="card-head"><div className="card-title">Response summary</div></div>
              <div className="card-body" style={{ paddingTop: 4 }}>
                {isDraft ? (
                  <div className="proc-inline-empty" style={{ padding: "20px 8px", justifyContent: "flex-start" }}>
                    <Ic5.User size={18} /><div className="muted" style={{ fontSize: 12.5 }}>No responses until broadcast.</div>
                  </div>
                ) : (
                  <>
                    <div className="rd-kpis">
                      <div className="rd-kpi"><div className="rd-kpi-val">{RESP.length}</div><div className="rd-kpi-lab">Responses</div></div>
                      <div className="rd-kpi"><div className="rd-kpi-val">{SHORTLIST.length}</div><div className="rd-kpi-lab">Shortlisted</div></div>
                      <div className="rd-kpi"><div className="rd-kpi-val">{KES5(avgRate)}</div><div className="rd-kpi-lab">Avg rate/kg</div></div>
                    </div>
                    <div className="rd-offered">
                      <div className="row" style={{ justifyContent: "space-between", marginBottom: 6 }}>
                        <span className="rd-spec-label">Qty offered vs target</span>
                        <span style={{ fontSize: 12.5, fontWeight: 600 }}>{qtyOffered.toLocaleString("en-US")} / {REQ.qty.toLocaleString("en-US")} kg</span>
                      </div>
                      <Progress value={qtyOffered} max={REQ.qty} tone={qtyOffered >= REQ.qty ? "" : "pulp"} />
                      <div className="field-hint" style={{ marginTop: 6 }}>{qtyOffered >= REQ.qty ? "Target fully covered by offers." : `${Math.round((qtyOffered / REQ.qty) * 100)}% of target covered.`}</div>
                    </div>
                    <Button variant="outline" size="sm" icon={Ic5.Eye} onClick={() => go("ADM-PROC-10.html")} style={{ width: "100%", marginTop: 14 }}>View &amp; compare responses</Button>
                  </>
                )}
              </div>
            </Card>

            <Card className="rd-rail-card">
              <div className="card-head"><div className="card-title">Broadcast</div></div>
              <div className="card-body" style={{ paddingTop: 4 }}>
                {isDraft ? (
                  <div className="muted" style={{ fontSize: 12.5 }}>Not broadcast yet. Channels and reach appear here once sent.</div>
                ) : (
                  <>
                    <div className="rd-channels">
                      {CHANNELS.map(c => (
                        <div key={c.key} className="rd-channel">
                          <span className="rd-channel-ic"><c.icon size={14} /></span>
                          <span className="rd-channel-name">{c.key}</span>
                          <span className="rd-channel-meta">{c.delivered}/{c.sent} delivered · {c.read} read</span>
                        </div>
                      ))}
                    </div>
                    <div className="rd-spec-label" style={{ margin: "14px 0 8px" }}>Groups reached</div>
                    <div className="proc-chips">
                      {GROUPS.map(g => <span key={g.name} className="proc-chip" style={{ cursor: "default" }}>{g.name}<span className="chip-count">{g.count}</span></span>)}
                    </div>
                  </>
                )}
              </div>
            </Card>
          </div>
        </div>
      )}

      {/* ───── Responses ───── */}
      {tab === "responses" && (
        <Card>
          <CardHead title={`${RESP.length} responses`} desc={`${SHORTLIST.length} shortlisted · sorted by score`}
            action={<Button size="sm" variant="primary" icon={Ic5.Eye} onClick={() => go("ADM-PROC-10.html")}>Open comparison</Button>} />
          <div className="card-body flush">
            <div className="tbl-wrap">
              <table className="tbl">
                <thead><tr><th>Farmer</th><th className="num">Qty offered</th><th className="num">Rate</th><th>Earliest</th><th className="num">Score</th><th>Status</th></tr></thead>
                <tbody>
                  {RESP.map(r => (
                    <tr key={r.farmer}>
                      <td><span style={{ display: "inline-flex", alignItems: "center", gap: 8 }}><Avatar initials={r.name.split(" ").map(x => x[0]).join("")} size="sm" /><span style={{ fontWeight: 500 }}>{r.name}</span></span></td>
                      <td className="num" style={{ fontWeight: 600 }}>{r.qty.toLocaleString("en-US")}<span className="muted" style={{ fontWeight: 400 }}> kg</span></td>
                      <td className="num">{KES5(r.rate)}</td>
                      <td>{r.earliest.slice(5)}</td>
                      <td className="num"><b style={{ color: r.score >= 85 ? "var(--success)" : r.score >= 70 ? "var(--foreground)" : "var(--muted-foreground)" }}>{r.score}</b></td>
                      <td><StatusBadge status={r.status} /></td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </div>
        </Card>
      )}

      {/* ───── Broadcast status ───── */}
      {tab === "broadcast" && (
        <div className="rd-grid">
          <div className="rd-main">
            <DCard title="Channel performance" icon={Ic5.Bolt}>
              <div className="tbl-wrap">
                <table className="tbl"><thead><tr><th>Channel</th><th className="num">Sent</th><th className="num">Delivered</th><th className="num">Read</th><th>Read rate</th></tr></thead>
                  <tbody>{CHANNELS.map(c => (
                    <tr key={c.key}><td><span style={{ display: "inline-flex", alignItems: "center", gap: 8 }}><span className="rd-channel-ic"><c.icon size={14} /></span>{c.key}</span></td>
                      <td className="num">{c.sent}</td><td className="num">{c.delivered}</td><td className="num">{c.read}</td>
                      <td style={{ minWidth: 120 }}><Progress value={c.read} max={c.sent} tone="pulp" /></td></tr>
                  ))}</tbody>
                </table>
              </div>
            </DCard>
          </div>
          <div className="rd-side">
            <Card className="rd-rail-card">
              <div className="card-head"><div className="card-title">Groups &amp; reach</div></div>
              <div className="card-body" style={{ paddingTop: 4 }}>
                {GROUPS.map(g => (
                  <div key={g.name} className="stat-row"><span className="stat-label"><Ic5.Users size={14} />{g.name}</span><span className="stat-value">{g.count}</span></div>
                ))}
                <div className="stat-row"><span className="stat-label" style={{ fontWeight: 600, color: "var(--foreground)" }}>Total farmers</span><span className="stat-value" style={{ fontWeight: 700 }}>142</span></div>
              </div>
            </Card>
          </div>
        </div>
      )}

      {/* ───── Versions ───── */}
      {tab === "versions" && (
        <Card>
          <CardHead title="Version history" desc="Editing a broadcast requirement creates a new version and re-notifies respondents." />
          <div className="card-body">
            <div className="rd-vlist">
              {VERSIONS.map(v => (
                <div key={v.v} className="rd-vitem">
                  <span className={`rd-vbadge${v.current ? " current" : ""}`}>v{v.v}</span>
                  <div style={{ flex: 1 }}>
                    <div style={{ fontSize: 13.5, fontWeight: 500 }}>{v.note}{v.current && <span className="badge badge-avocado" style={{ marginLeft: 8 }}>Current</span>}</div>
                    <div className="muted" style={{ fontSize: 12, marginTop: 3 }}>{v.by} · {v.when}</div>
                  </div>
                  {!v.current && <Button size="sm" variant="ghost" onClick={() => toast({ title: `Viewing v${v.v}`, desc: "Read-only snapshot" })}>View</Button>}
                </div>
              ))}
            </div>
          </div>
        </Card>
      )}

      {/* ───── Activity (C-123) ───── */}
      {tab === "activity" && (
        <Card>
          <CardHead title="Activity log" desc="Every change, broadcast and response on this requirement." />
          <div className="card-body">
            <div className="rd-audit">
              {ACTIVITY.map((a, i) => (
                <div key={i} className="rd-audit-item">
                  <span className={`proc-ic tone-${a.tone}`}><a.icon size={14} /></span>
                  <div style={{ flex: 1 }}>
                    <div style={{ fontSize: 13.5, lineHeight: 1.4 }}>{a.text}</div>
                    <div className="muted" style={{ fontSize: 11.5, marginTop: 2 }}>{a.when}</div>
                  </div>
                </div>
              ))}
            </div>
          </div>
        </Card>
      )}

      {/* Sticky bottom action bar */}
      {!isCancelled && (
        <div className="rd-actionbar">
          <div className="rd-ab-info">
            {isDraft ? <span className="muted">Draft — not yet broadcast</span>
              : <><b>{RESP.length}</b> responses · <b>{SHORTLIST.length}</b> shortlisted{canApprove ? "" : ""}</>}
          </div>
          <div className="rd-ab-actions">
            {isDraft ? (
              <>
                <Button variant="outline" icon={Ic5.Edit} onClick={() => go("ADM-PROC-06.html")}>Edit</Button>
                <Button variant="primary" icon={Ic5.Bolt} onClick={() => go("ADM-PROC-07.html")}>Broadcast to farmers</Button>
              </>
            ) : (
              <>
                <Button variant="outline" icon={Ic5.Eye} onClick={() => go("ADM-PROC-10.html")}>View responses ({RESP.length})</Button>
                <Button variant="primary" icon={Ic5.CheckCircle} disabled={!canApprove} onClick={() => canApprove && go("ADM-PROC-13.html")}
                  title={canApprove ? "" : "Requires at least one shortlisted response"}>Approve &amp; confirm</Button>
              </>
            )}
          </div>
        </div>
      )}

      <CancelModal5 open={cancelOpen} onClose={() => setCancelOpen(false)} onConfirm={() => { setStatus("cancelled"); setCancelOpen(false); toast({ title: `${REQ.id} cancelled` }); }} />
    </div>
  );
};

window.Pages = Object.assign(window.Pages || {}, { reqDetail: RequirementDetail });
