/* Catalogues — Produits par fournisseur (vue inventaire upstream) */

const Catalogs = () => {
  const [selected, setSelected] = useState(SUPPLIERS[0]?.id || null);
  const [search, setSearch] = useState("");
  const [, force] = useState(0);

  if (!SUPPLIERS || SUPPLIERS.length === 0) {
    return (
      <div className="page" style={{ maxWidth: 1500 }}>
        <div className="page-head">
          <div>
            <div className="page-title">Catalogues</div>
            <div className="page-sub">Aucun fournisseur — ajoute-en un dans l'Annuaire pour gérer un catalogue.</div>
          </div>
        </div>
        <div className="card" style={{ padding: 40, textAlign: "center", color: "var(--text-faint)", fontSize: 13 }}>
          Pas encore de catalogues à afficher.
        </div>
      </div>
    );
  }

  const sup = SUPPLIERS.find(s => s.id === selected) || SUPPLIERS[0];

  const persistSupplier = async (patch) => {
    Object.assign(sup, patch);
    force(x => x + 1);
    try {
      await fetch("/api/sync", {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ col: "suppliers", items: [{ ...sup }] }),
      });
    } catch (_) {}
  };
  const persistProduct = async (id, patch) => {
    const p = PRODUCTS.find(x => x.id === id);
    if (!p) return;
    Object.assign(p, patch);
    // Recompute margin if price/cost changed
    if (("price" in patch || "cost" in patch) && p.price > 0) {
      p.margin = ((p.price - p.cost) / p.price) * 100;
    }
    force(x => x + 1);
    try {
      await fetch("/api/sync", {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ col: "products", items: [{ ...p }] }),
      });
    } catch (_) {}
  };
  const products = PRODUCTS.filter(p => p.supplier === sup.name);
  const visible = products.filter(p =>
    !search || (p.name + " " + p.asin + " " + p.cat).toLowerCase().includes(search.toLowerCase())
  );

  const avgMargin = products.length
    ? (products.reduce((a, b) => a + b.margin, 0) / products.length).toFixed(1)
    : 0;
  const totalRevPotential = products.reduce((a, b) => a + b.price * b.vel * 30, 0);

  return (
    <div className="page">
      <div className="page-head">
        <div>
          <div className="page-title">Catalogues fournisseurs</div>
          <div className="page-sub">
            {SUPPLIERS.length} fournisseurs · {PRODUCTS.filter(p => p.supplier !== "—").length} produits sourcés ·
            MOQ et prix unitaire par fournisseur
          </div>
        </div>
      </div>

      <div className="grid" style={{ gridTemplateColumns: "260px 1fr", gap: 14, alignItems: "flex-start" }}>
        {/* Supplier list */}
        <div className="card" style={{ padding: 0, overflow: "hidden" }}>
          <div style={{ padding: 10, borderBottom: "1px solid var(--border-subtle)", fontSize: 11, color: "var(--text-dim)", textTransform: "uppercase", letterSpacing: "0.06em" }}>
            Fournisseurs
          </div>
          {SUPPLIERS.map(s => {
            const count = PRODUCTS.filter(p => p.supplier === s.name).length;
            const active = s.id === selected;
            return (
              <button
                key={s.id}
                onClick={() => setSelected(s.id)}
                style={{
                  display: "block", width: "100%", textAlign: "left",
                  padding: "10px 12px", border: 0,
                  borderBottom: "1px solid var(--border-subtle)",
                  borderLeft: active ? "2px solid var(--accent)" : "2px solid transparent",
                  background: active ? "var(--bg-3)" : "transparent",
                  cursor: "pointer", color: "var(--text)",
                }}
              >
                <div className="between">
                  <span style={{ fontSize: 12.5, fontWeight: active ? 600 : 500 }}>{s.name}</span>
                  <span className="mono" style={{ fontSize: 10.5, color: "var(--text-faint)" }}>{count}</span>
                </div>
                <div className="mono" style={{ fontSize: 10.5, color: "var(--text-dim)", marginTop: 2 }}>{s.region}</div>
              </button>
            );
          })}
        </div>

        {/* Catalog detail */}
        <div className="stack" style={{ gap: 12 }}>
          {/* Supplier header */}
          <div className="card" style={{ padding: 14 }}>
            <div className="between" style={{ alignItems: "flex-start" }}>
              <div>
                <div style={{ fontSize: 16, fontWeight: 600 }}>
                  <EditableField value={sup.name} onSave={(v) => persistSupplier({ name: v })} width={260}/>
                </div>
                <div className="mono" style={{ fontSize: 11.5, color: "var(--text-dim)", marginTop: 2 }}>
                  <EditableField value={sup.region} onSave={(v) => persistSupplier({ region: v })} width={120}/> ·{" "}
                  <EditableField value={sup.contact} onSave={(v) => persistSupplier({ contact: v })} width={140}/> ·{" "}
                  <EditableField value={sup.email} onSave={(v) => persistSupplier({ email: v })} type="email" width={200}/>
                </div>
              </div>
              <Badge tone="green" dot>
                <EditableField
                  value={sup.status || "actif"}
                  onSave={(v) => persistSupplier({ status: v })}
                  options={[{value:"actif",label:"actif"},{value:"inactif",label:"inactif"},{value:"revue",label:"en revue"}]}
                  width={90}
                />
              </Badge>
            </div>
            <div className="grid" style={{ gridTemplateColumns: "repeat(5, 1fr)", gap: 8, marginTop: 14 }}>
              <div style={{ background: "var(--bg-2)", padding: 8, borderRadius: 6 }}>
                <div style={{ fontSize: 10, color: "var(--text-faint)", textTransform: "uppercase" }}>Note</div>
                <div className="mono" style={{ fontWeight: 600, marginTop: 2 }}>{sup.rating} / 5</div>
              </div>
              <div style={{ background: "var(--bg-2)", padding: 8, borderRadius: 6 }}>
                <div style={{ fontSize: 10, color: "var(--text-faint)", textTransform: "uppercase" }}>MOQ</div>
                <div className="mono" style={{ fontWeight: 600, marginTop: 2 }}>{sup.moq}u</div>
              </div>
              <div style={{ background: "var(--bg-2)", padding: 8, borderRadius: 6 }}>
                <div style={{ fontSize: 10, color: "var(--text-faint)", textTransform: "uppercase" }}>Délai</div>
                <div className="mono" style={{ fontWeight: 600, marginTop: 2 }}>{sup.leadDays}j</div>
              </div>
              <div style={{ background: "var(--bg-2)", padding: 8, borderRadius: 6 }}>
                <div style={{ fontSize: 10, color: "var(--text-faint)", textTransform: "uppercase" }}>Marge moy.</div>
                <div className="mono" style={{ fontWeight: 600, marginTop: 2, color: "var(--green)" }}>{avgMargin}%</div>
              </div>
              <div style={{ background: "var(--bg-2)", padding: 8, borderRadius: 6 }}>
                <div style={{ fontSize: 10, color: "var(--text-faint)", textTransform: "uppercase" }}>Rev potentiel/m</div>
                <div className="mono" style={{ fontWeight: 600, marginTop: 2 }}>${Math.round(totalRevPotential).toLocaleString()}</div>
              </div>
            </div>
          </div>

          {/* Search */}
          <div className="input">
            <Icon name="search" size={12} style={{ marginRight: 6, color: "var(--text-dim)" }} />
            <input
              value={search}
              onChange={(e) => setSearch(e.target.value)}
              placeholder={`Filtrer le catalogue de ${sup.name}…`}
              style={{ flex: 1, background: "transparent", border: "none", outline: "none", color: "var(--text)" }}
            />
          </div>

          {/* Product table */}
          <div className="card" style={{ padding: 0, overflow: "auto" }}>
            <table className="table">
              <thead>
                <tr>
                  <th>Produit</th>
                  <th>ASIN</th>
                  <th>Catégorie</th>
                  <th style={{ textAlign: "right" }}>Coût/u</th>
                  <th style={{ textAlign: "right" }}>Prix vente</th>
                  <th style={{ textAlign: "right" }}>Marge %</th>
                  <th>Statut</th>
                </tr>
              </thead>
              <tbody>
                {visible.map(p => (
                  <tr key={p.id}>
                    <td style={{ maxWidth: 240 }}>
                      <EditableField value={p.name} onSave={(v) => persistProduct(p.id, { name: v })} width={220}/>
                    </td>
                    <td><Asin value={p.asin} /></td>
                    <td className="muted" style={{ fontSize: 11.5 }}>
                      <EditableField value={p.cat} onSave={(v) => persistProduct(p.id, { cat: v })} width={100}/>
                    </td>
                    <td className="mono" style={{ textAlign: "right" }}>
                      <EditableField value={p.cost} onSave={(v) => persistProduct(p.id, { cost: Number(v) || 0 })} type="number" format={(v) => "$" + Number(v).toFixed(2)} width={70}/>
                    </td>
                    <td className="mono" style={{ textAlign: "right" }}>
                      <EditableField value={p.price} onSave={(v) => persistProduct(p.id, { price: Number(v) || 0 })} type="number" format={(v) => "$" + Number(v).toFixed(2)} width={70}/>
                    </td>
                    <td className="mono" style={{ textAlign: "right", fontWeight: 600, color: p.margin >= 28 ? "var(--green)" : "var(--text)" }}>
                      {p.margin.toFixed(1)}%
                    </td>
                    <td>
                      <EditableField
                        value={p.status}
                        onSave={(v) => persistProduct(p.id, { status: v })}
                        options={[
                          { value: "evaluer", label: "À évaluer" },
                          { value: "recherche", label: "En recherche" },
                          { value: "valide", label: "Validé" },
                          { value: "commande", label: "Commandé" },
                          { value: "stock", label: "En stock" },
                        ]}
                        format={(v) => <Badge tone={STATUS_TONES[v] || "muted"} dot>{v}</Badge>}
                        width={110}
                      />
                    </td>
                  </tr>
                ))}
                {visible.length === 0 && (
                  <tr><td colSpan={7} style={{ textAlign: "center", padding: 24, color: "var(--text-faint)" }}>
                    {products.length === 0
                      ? "Aucun produit sourcé chez ce fournisseur"
                      : "Aucun produit ne correspond au filtre"}
                  </td></tr>
                )}
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </div>
  );
};

window.Catalogs = Catalogs;
