// ADM-PROC-11 · Auto-comparison view (AMOMS Module 1)
// Admin Web · Procurement Manager · P0 · 1440×900
// Components: C-122 Comparison row · C-014 Status pill + tier badge · C-001 Button
// Registered as window.Pages.compare

const Ic11 = window.Icons;
const KES11 = (n) => "KSh " + (Number(n) || 0).toLocaleString("en-US");
const REQ_11 = { id: "PR-2026-0184", product: "Hass", qty: 28000, ceiling: 95 };

const FBN_11 = Object.fromEntries(window.MD.FARMERS.map(f => [f.name, f]));
const tier11 = (r) => r >= 4.7 ? "A" : r >= 4.3 ? "B" : "C";

// Enrich the top responses with comparison attributes (deterministic).
const ALL_11 = window.MD.RESPONSES.map((r, i) => {
  const f = FBN_11[r.name] || {};
  return {
    id: r.farmer, name: r.name, init: r.name.split(" ").map(x => x[0]).join(""),
    region: (f.village || "").split(",").slice(-1)[0].trim(), tier: tier11(f.rating || 4),
    rate: r.rate, qty: r.qty, earliest: r.earliest, responseHrs: [2, 3, 5, 6, 4, 8, 9, 11, 7, 12, 14, 16][i],
    quality: Math.round((f.rating || 4) * 20), reliability: [98, 96, 92, 90, 94, 85, 88, 80, 86, 74, 78, 70][i],
    distance: [12, 18, 34, 27, 41, 52, 23, 38, 30, 64, 47, 58][i], status: r.status,
  };
}).sort((a, b) => (b.quality - a.quality));

const ATTRS = [
  { key: "rate", label: "Rate (KSh/kg)", fmt: (v) => KES11(v), best: "min" },
  { key: "qty", label: "Offered qty", fmt: (v) => v.toLocaleString("en-US") + " kg", best: "max", partial: true },
  { key: "earliest", label: "Earliest delivery", fmt: (v) => window.AMDATE(v), best: "minDate" },
  { key: "responseHrs", label: "Response time", fmt: (v) => v + "h", best: "min" },
  { key: "quality", label: "Past quality score", fmt: (v) => v + " / 100", best: "max" },
  { key: "reliability", label: "Delivery reliability", fmt: (v) => v + "%", best: "max" },
  { key: "distance", label: "Distance from plant", fmt: (v) => v + " km", best: "min" },
  { key: "cost", label: "Cost to deliver", fmt: (v) => KES11(v), best: "min" },
];

const Compare = ({ tweaks }) => {
  const toast = useToast();
  const go = window.makeGo(toast);
  const count = Number((tweaks && tweaks.compareCount) || "4");

  const [cols, setCols] = useState(ALL_11.slice(0, count === 6 ? 6 : count));
  useEffect(() => { setCols(ALL_11.slice(0, count === 6 ? 6 : count)); }, [count]);
  const [sortBy, setSortBy] = useState("rate");
  const [shortlisted, setShortlisted] = useState(new Set(ALL_11.filter(r => r.status === "shortlist").map(r => r.id)));

  const withCost = cols.map(c => ({ ...c, cost: c.qty * c.rate }));
  const sorted = [...withCost].sort((a, b) => sortBy === "rate" ? a.rate - b.rate : sortBy === "qty" ? b.qty - a.qty : b.quality - a.quality);

  // best value per attribute
  const bestVal = {};
  ATTRS.forEach(a => {
    const vals = sorted.map(c => a.key === "earliest" ? new Date(c.earliest).getTime() : c[a.key]);
    bestVal[a.key] = a.best === "max" ? Math.max(...vals) : Math.min(...vals);
  });

  const isBest = (a, c) => {
    const v = a.key === "earliest" ? new Date(c.earliest).getTime() : c[a.key];
    return v === bestVal[a.key];
  };

  const toggleShort = (id) => { setShortlisted(s => { const n = new Set(s); n.has(id) ? n.delete(id) : n.add(id); return n; }); };
  const removeCol = (id) => setCols(cs => cs.filter(c => c.id !== id));

  return (
    <div className="page cmp-page">
      <div className="cmp-head">
        <button className="btn btn-ghost btn-icon" aria-label="Back" onClick={() => go("ADM-PROC-10.html")}><Ic11.ChevronLeft size={18} /></button>
        <div>
          <h1 className="cmp-title">Compare responses — <span className="mono" style={{ fontWeight: 600 }}>{REQ_11.id}</span></h1>
          <div className="muted" style={{ fontSize: 12.5, marginTop: 2 }}>{sorted.length} side by side · best value highlighted</div>
        </div>
        <div className="cmp-head-actions">
          <span className="muted" style={{ fontSize: 12 }}>Order by</span>
          <select className="select" style={{ width: "auto", height: 32 }} value={sortBy} onChange={(e) => setSortBy(e.target.value)}>
            <option value="rate">Rate (low→high)</option><option value="qty">Qty (high→low)</option><option value="quality">Quality</option>
          </select>
          <Button variant="primary" onClick={() => go("ADM-PROC-10.html")}>Done</Button>
        </div>
      </div>

      <div className="cmp-scroll">
        <table className="cmp-table">
          <thead>
            <tr>
              <th className="cmp-attr"></th>
              {sorted.map(c => (
                <th key={c.id} className={`cmp-col cmp-colhead${shortlisted.has(c.id) ? " cmp-shortlisted-col" : ""}`}>
                  <div className="cmp-fname"><Avatar initials={c.init} size="sm" />{c.name}
                    {shortlisted.has(c.id) && <span className="cmp-colbadge">Shortlisted</span>}
                  </div>
                  <div className="cmp-fmeta">
                    <span style={{ display: "inline-flex", alignItems: "center", gap: 6 }}>
                      <Badge tone={c.tier === "A" ? "avocado" : c.tier === "B" ? "pulp" : "outline"}>Tier {c.tier}</Badge>
                      {c.region} · responded {c.responseHrs}h after
                    </span>
                  </div>
                </th>
              ))}
            </tr>
          </thead>
          <tbody>
            {ATTRS.map(a => (
              <tr key={a.key}>
                <td className="cmp-attr">{a.label}</td>
                {sorted.map(c => {
                  const best = isBest(a, c);
                  const partial = a.partial && c.qty < REQ_11.qty;
                  return (
                    <td key={c.id} className={`cmp-col${best ? " cmp-best" : ""}`}>
                      <span className="cmp-cell">{a.fmt(c[a.key])}{best && <span className="cmp-best-tag"><Ic11.Check size={10} />best</span>}</span>
                      {partial && <span className="cmp-partial">Partial — {Math.round((c.qty / REQ_11.qty) * 100)}% of target</span>}
                    </td>
                  );
                })}
              </tr>
            ))}
            {/* Action row */}
            <tr>
              <td className="cmp-attr">Decision</td>
              {sorted.map(c => (
                <td key={c.id} className="cmp-col">
                  <div className="cmp-colactions">
                    <Button size="xs" variant={shortlisted.has(c.id) ? "avocado" : "outline"} icon={Ic11.Star} onClick={() => toggleShort(c.id)}>{shortlisted.has(c.id) ? "Listed" : "Shortlist"}</Button>
                    <button className="btn btn-ghost btn-icon btn-xs" aria-label="Reject" title="Reject" onClick={() => toast({ title: `Rejected ${c.name}` })}><Ic11.XCircle size={13} /></button>
                    <button className="btn btn-ghost btn-icon btn-xs" aria-label="Remove" title="Remove from comparison" onClick={() => removeCol(c.id)}><Ic11.X size={13} /></button>
                  </div>
                </td>
              ))}
            </tr>
          </tbody>
        </table>
      </div>

      <div className="cmp-actionbar">
        <div style={{ fontSize: 13, color: "var(--muted-foreground)" }}><b style={{ color: "var(--foreground)" }}>{shortlisted.size}</b> shortlisted · highlights are advisory</div>
        <div style={{ marginLeft: "auto", display: "flex", gap: 8 }}>
          <Button variant="outline" icon={Ic11.Plus} onClick={() => { const next = ALL_11.find(r => !cols.some(c => c.id === r.id)); if (next) setCols(cs => [...cs, next]); else toast({ title: "All responses already in comparison" }); }}>Add response</Button>
          <Button variant="primary" icon={Ic11.Star} onClick={() => go("ADM-PROC-12.html")}>Confirm shortlist</Button>
        </div>
      </div>
    </div>
  );
};

window.Pages = Object.assign(window.Pages || {}, { compare: Compare });
