/* Supplier Comparison — Side-by-side table for sourcing decisions */

const SupplierCompare = () => {
  const [picked, setPicked] = useState(SUPPLIERS.slice(0, 3).map(s => s.id));
  const [filterCat, setFilterCat] = useState("all");

  const categories = Array.from(new Set(SUPPLIERS.map(s => s.cat)));
  const togglePick = (id) => {
    setPicked(picked.includes(id) ? picked.filter(x => x !== id) : [...picked, id]);
  };

  const compared = SUPPLIERS
    .filter(s => filterCat === "all" || s.cat === filterCat)
    .filter(s => picked.includes(s.id));

  const totalOpen = compared.reduce((a, b) => a + b.openBalance, 0);
  const avgLead = compared.length
    ? Math.round(compared.reduce((a, b) => a + b.leadDays, 0) / compared.length)
    : 0;

  return (
    <div className="page">
      <div className="page-head">
        <div>
          <div className="page-title">Comparatif fournisseurs</div>
          <div className="page-sub">
            Sélectionne 2 à 5 fournisseurs · {SUPPLIERS.length} disponibles ·
            {" "}{picked.length} en cours de comparaison
          </div>
        </div>
        <select value={filterCat} onChange={(e) => setFilterCat(e.target.value)} className="input" style={{ width: 200 }}>
          <option value="all">Toutes catégories</option>
          {categories.map(c => <option key={c} value={c}>{c}</option>)}
        </select>
      </div>

      {/* Picker chips */}
      <div className="card" style={{ padding: 10, marginBottom: 12 }}>
        <div style={{ fontSize: 10.5, color: "var(--text-dim)", textTransform: "uppercase", letterSpacing: "0.06em", marginBottom: 8 }}>
          Cliquer pour inclure / exclure
        </div>
        <div className="row" style={{ gap: 6, flexWrap: "wrap" }}>
          {SUPPLIERS.filter(s => filterCat === "all" || s.cat === filterCat).map(s => (
            <button
              key={s.id}
              onClick={() => togglePick(s.id)}
              className="btn"
              data-variant={picked.includes(s.id) ? "primary" : "ghost"}
              data-size="sm"
            >
              {s.name}
            </button>
          ))}
        </div>
      </div>

      {/* KPI summary */}
      {compared.length > 0 && (
        <div className="grid" style={{ gridTemplateColumns: "repeat(3, 1fr)", gap: 12, marginBottom: 12 }}>
          <div className="card" style={{ padding: 12 }}>
            <div style={{ fontSize: 10.5, color: "var(--text-dim)", textTransform: "uppercase" }}>Comptes ouverts</div>
            <div className="mono" style={{ fontSize: 20, fontWeight: 600, marginTop: 4 }}>${totalOpen.toLocaleString()}</div>
          </div>
          <div className="card" style={{ padding: 12 }}>
            <div style={{ fontSize: 10.5, color: "var(--text-dim)", textTransform: "uppercase" }}>Lead time moyen</div>
            <div className="mono" style={{ fontSize: 20, fontWeight: 600, marginTop: 4 }}>{avgLead}j</div>
          </div>
          <div className="card" style={{ padding: 12 }}>
            <div style={{ fontSize: 10.5, color: "var(--text-dim)", textTransform: "uppercase" }}>Total produits</div>
            <div className="mono" style={{ fontSize: 20, fontWeight: 600, marginTop: 4 }}>
              {compared.reduce((a, b) => a + b.products, 0)}
            </div>
          </div>
        </div>
      )}

      {/* Side-by-side table */}
      <div className="card" style={{ padding: 0, overflow: "auto" }}>
        <table className="table">
          <thead>
            <tr>
              <th style={{ width: 160 }}>Critère</th>
              {compared.map(s => (
                <th key={s.id} style={{ minWidth: 180 }}>
                  <div style={{ fontWeight: 600 }}>{s.name}</div>
                  <div className="mono" style={{ fontSize: 10.5, color: "var(--text-faint)", marginTop: 2 }}>{s.region}</div>
                </th>
              ))}
            </tr>
          </thead>
          <tbody>
            <tr>
              <td className="muted">Score global</td>
              {compared.map(s => (
                <td key={s.id} className="mono" style={{ fontWeight: 700, fontSize: 15, color: s.score >= 85 ? "var(--green)" : s.score >= 75 ? "var(--text)" : "var(--amber)" }}>
                  {s.score} / 100
                </td>
              ))}
            </tr>
            <tr>
              <td className="muted">Note</td>
              {compared.map(s => <td key={s.id} className="mono">{"★".repeat(Math.round(s.rating))}<span style={{ color: "var(--text-faint)" }}>{"★".repeat(5 - Math.round(s.rating))}</span> {s.rating}</td>)}
            </tr>
            <tr>
              <td className="muted">Produits</td>
              {compared.map(s => <td key={s.id} className="mono">{s.products}</td>)}
            </tr>
            <tr>
              <td className="muted">MOQ</td>
              {compared.map(s => <td key={s.id} className="mono">{s.moq.toLocaleString()} u</td>)}
            </tr>
            <tr>
              <td className="muted">Délai (jours)</td>
              {compared.map(s => (
                <td key={s.id} className="mono" style={{ color: s.leadDays <= 25 ? "var(--green)" : s.leadDays <= 32 ? "var(--text)" : "var(--amber)" }}>
                  {s.leadDays}j
                </td>
              ))}
            </tr>
            <tr>
              <td className="muted">Termes paiement</td>
              {compared.map(s => <td key={s.id}>{s.terms}</td>)}
            </tr>
            <tr>
              <td className="muted">Solde ouvert</td>
              {compared.map(s => (
                <td key={s.id} className="mono" style={{ color: s.openBalance === 0 ? "var(--text-faint)" : "var(--text)" }}>
                  ${s.openBalance.toLocaleString()}
                </td>
              ))}
            </tr>
            <tr>
              <td className="muted">Catégorie</td>
              {compared.map(s => <td key={s.id} style={{ fontSize: 11.5 }}>{s.cat}</td>)}
            </tr>
            <tr>
              <td className="muted">Contact</td>
              {compared.map(s => (
                <td key={s.id}>
                  <div style={{ fontSize: 12 }}>{s.contact}</div>
                  <div className="mono" style={{ fontSize: 10.5, color: "var(--text-faint)" }}>{s.email}</div>
                </td>
              ))}
            </tr>
          </tbody>
        </table>
        {compared.length === 0 && (
          <div style={{ padding: 30, textAlign: "center", color: "var(--text-faint)" }}>
            Sélectionne au moins un fournisseur ci-dessus pour démarrer la comparaison.
          </div>
        )}
      </div>
    </div>
  );
};

window.SupplierCompare = SupplierCompare;
