/* Product Research — Grid (Google-Sheets style) + Kanban toggle */

const COLUMNS = [
  { key: "name",     label: "Produit",         width: 320, type: "text" },
  { key: "asin",     label: "ASIN",            width: 110, type: "mono" },
  { key: "cat",      label: "Catégorie",       width: 140, type: "text" },
  { key: "status",   label: "Statut",          width: 130, type: "status" },
  { key: "price",    label: "Prix",            width: 80,  type: "money" },
  { key: "cost",     label: "Coût",            width: 80,  type: "money" },
  { key: "margin",   label: "Marge %",         width: 90,  type: "pct" },
  { key: "bsr",      label: "BSR",             width: 90,  type: "int" },
  { key: "stock",    label: "Stock",           width: 70,  type: "int" },
  { key: "vel",      label: "Vél./j",          width: 70,  type: "int" },
  { key: "owner",    label: "Propriétaire",    width: 110, type: "user" },
  { key: "supplier", label: "Fournisseur",     width: 180, type: "text" },
];

const MENU_BAR = ["Fichier", "Édition", "Affichage", "Insertion", "Données", "Outils", "Aide"];

const ProductRow = ({ p, selected, onToggle, onEdit }) => {
  return (
    <tr data-selected={selected} onClick={onToggle}>
      <td style={{ width: 36, textAlign: "center" }}>
        <input type="checkbox" checked={selected} onChange={() => {}} style={{ accentColor: "var(--accent)" }}/>
      </td>
      {COLUMNS.map((c) => {
        const v = p[c.key];
        let content;
        if (c.type === "money") content = <span className="num">{fmtDollar(v)}</span>;
        else if (c.type === "pct") {
          const tone = v >= 28 ? "var(--green)" : v >= 22 ? "var(--text)" : "var(--amber)";
          content = <span className="num" style={{ color: tone, fontWeight: 600 }}>{v.toFixed(1)}%</span>;
        }
        else if (c.type === "int") content = <span className="num">{v?.toLocaleString?.() ?? v}</span>;
        else if (c.type === "mono") content = <span className="mono" style={{ color: "var(--text-muted)", fontSize: 11.5 }}>{v}</span>;
        else if (c.type === "status") content = <StatusBadge value={v} />;
        else if (c.type === "user") content = <span style={{display:"inline-flex", alignItems:"center", gap:6}}><Avatar user={v} size="sm" /><span style={{textTransform:"capitalize", fontSize: 12}}>{v}</span></span>;
        else content = v;
        return <td key={c.key} style={{ maxWidth: c.width, overflow: "hidden", textOverflow: "ellipsis" }} onDoubleClick={onEdit}>{content}</td>;
      })}
    </tr>
  );
};

/* Kanban */
const KanbanCard = ({ p, onDragStart }) => (
  <div
    draggable
    onDragStart={onDragStart}
    style={{
      background: "var(--bg-2)",
      border: "1px solid var(--border-subtle)",
      borderRadius: 8,
      padding: 10,
      cursor: "grab",
      transition: "border-color 100ms, transform 100ms",
    }}
    onMouseEnter={(e) => e.currentTarget.style.borderColor = "var(--border-strong)"}
    onMouseLeave={(e) => e.currentTarget.style.borderColor = "var(--border-subtle)"}
  >
    <div style={{ fontSize: 12.5, fontWeight: 550, lineHeight: 1.35, marginBottom: 6 }}>{p.name}</div>
    <div className="row" style={{ gap: 6, marginBottom: 8 }}>
      <Asin value={p.asin} />
      <span style={{ color: "var(--text-faint)" }}>·</span>
      <span style={{ fontSize: 10.5, color: "var(--text-dim)" }}>{p.cat}</span>
    </div>
    <div className="between" style={{ fontSize: 11 }}>
      <div className="row" style={{ gap: 8 }}>
        <span className="num"><span className="muted">Prix</span> {fmtDollar(p.price)}</span>
        <span className="num" style={{ color: p.margin >= 28 ? "var(--green)" : "var(--text)" }}><span className="muted">Mge</span> {p.margin.toFixed(0)}%</span>
      </div>
      <Avatar user={p.owner} size="sm" />
    </div>
  </div>
);

const ProductResearch = (props) => props.researchLayout === "grille"
  ? <ProductResearchGrid {...props}/>
  : <ProductResearchCards {...props}/>;

const ProductResearchCards = () => {
  const toast = useToast();
  const [filter, setFilter] = useState("");
  const [statusFilter, setStatusFilter] = useState("all");
  const [, force] = useState(0);
  const trashHook = (window.useKCCTrash || (() => ({ items: [], send: async () => {} })))();
  const [newOpen, setNewOpen] = useState(false);
  const [draft, setDraft] = useState({ name: "", asin: "", supplier: "", price: 0, cost: 0 });

  const create = async () => {
    if (!draft.name?.trim()) return;
    const id = "p-" + Date.now().toString(36);
    const price = Number(draft.price) || 0;
    const cost = Number(draft.cost) || 0;
    const fresh = {
      id,
      name: draft.name.trim(),
      asin: draft.asin.trim() || id.toUpperCase(),
      supplier: draft.supplier.trim() || "—",
      price, cost,
      margin: price > 0 ? ((price - cost) / price) * 100 : 0,
      cat: "Maison & Cuisine",
      owner: "clarens",
      bsr: 0, stock: 0, vel: 0,
      status: "evaluer",
    };
    PRODUCTS.push(fresh);
    setNewOpen(false);
    setDraft({ name: "", asin: "", supplier: "", price: 0, cost: 0 });
    force(x => x + 1);
    try {
      await fetch("/api/sync", {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ col: "products", items: [fresh] }),
      });
    } catch (_) {}
    toast?.({ message: `Produit "${fresh.name}" créé`, tone: "green" });
  };

  const deleteProduct = async (target, e) => {
    if (e) e.stopPropagation();
    if (!target) return;
    if (!window.confirm(`Mettre "${target.name}" à la corbeille ?`)) return;
    const idx = PRODUCTS.findIndex(p => p.id === target.id);
    if (idx >= 0) PRODUCTS.splice(idx, 1);
    await trashHook.send("products", target);
    force(x => x + 1);
    toast?.({ message: `"${target.name}" → corbeille`, tone: "muted" });
  };
  const palette = {
    "Maison & Cuisine": ["#d4c3a8", "#8a7355"],
    "Électronique":     ["#a8c3d4", "#557a8a"],
    "Auto":             ["#c2c2c2", "#555555"],
    "Animalerie":       ["#d4b8a8", "#8a6855"],
    "Sport & Plein Air":["#a8d4b8", "#558a68"],
    "Bureau":           ["#d4a8c3", "#8a5575"],
    "Voyage":           ["#c3a8d4", "#75558a"],
  };
  const list = PRODUCTS.filter((p) =>
    (!filter || p.name.toLowerCase().includes(filter.toLowerCase()) || p.asin.toLowerCase().includes(filter.toLowerCase()))
    && (statusFilter === "all" || p.status === statusFilter)
  );
  return (
    <div className="page">
      <div className="page-head">
        <div>
          <div className="page-title">Recherche de produits</div>
          <div className="page-sub">{list.length} produits · catalogue centralisé</div>
        </div>
        <div className="row">
          <button className="btn" data-variant="ghost"><Icon name="filter" size={13}/> Filtres</button>
          <button className="btn" onClick={() => { try { const rows = list.length ? list : []; const csv = "Nom,ASIN,Marge%,BSR,Prix,Coût\n" + rows.map(p => `"${p.name||""}",${p.asin||""},${(p.margin||0).toFixed?.(1)||0},${p.bsr||0},${p.price||0},${p.cost||0}`).join("\n"); const blob = new Blob([csv], { type:"text/csv;charset=utf-8" }); const url = URL.createObjectURL(blob); const a = document.createElement("a"); a.href = url; a.download = "kcc-produits-"+new Date().toISOString().slice(0,10)+".csv"; a.click(); URL.revokeObjectURL(url); toast?.({ message: rows.length+" produits exportés", tone:"green" }); } catch(e){ toast?.({ message: "Export CSV échoué: "+e.message, tone:"red" }); } }}><Icon name="download" size={13}/> CSV</button>
          <button className="btn" data-variant="primary" onClick={() => setNewOpen(true)}><Icon name="plus" size={13}/> Nouveau produit</button>
        </div>
      </div>

      <div className="row" style={{ marginBottom: 14, gap: 8 }}>
        <div style={{ position: "relative", width: 280 }}>
          <Icon name="search" size={13} style={{ position: "absolute", left: 10, top: "50%", transform: "translateY(-50%)", color: "var(--text-dim)" }}/>
          <input className="input" value={filter} onChange={(e) => setFilter(e.target.value)} placeholder="Rechercher par nom, ASIN…" style={{ paddingLeft: 30 }}/>
        </div>
        <div className="row" style={{ gap: 4, background: "var(--bg-2)", border: "1px solid var(--border-subtle)", borderRadius: 6, padding: 2 }}>
          {["all", ...Object.keys(STATUS)].map((s) => (
            <button key={s} onClick={() => setStatusFilter(s)} style={{
              height: 22, padding: "0 8px", borderRadius: 4, fontSize: 11.5,
              background: statusFilter === s ? "var(--bg-4)" : "transparent",
              color: statusFilter === s ? "var(--text)" : "var(--text-dim)",
              fontWeight: statusFilter === s ? 600 : 400,
            }}>{s === "all" ? "Tous" : STATUS[s].label}</button>
          ))}
        </div>
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(260px, 1fr))", gap: 14 }}>
        {list.map((p) => {
          const [c1, c2] = palette[p.cat] || palette["Maison & Cuisine"];
          return (
            <div key={p.id} className="card" style={{ padding: 0, overflow: "hidden", cursor: "pointer", transition: "transform 120ms, border-color 120ms" }}
              onMouseEnter={(e) => { e.currentTarget.style.transform = "translateY(-2px)"; e.currentTarget.style.borderColor = "var(--border-strong)"; }}
              onMouseLeave={(e) => { e.currentTarget.style.transform = "none"; e.currentTarget.style.borderColor = "var(--border-subtle)"; }}
            >
              <div style={{ height: 120, background: `linear-gradient(135deg, ${c1}, ${c2})`, position: "relative" }}>
                <div className="mono" style={{ position: "absolute", top: 10, left: 12, fontSize: 10, color: "rgba(255,255,255,.85)", letterSpacing: ".08em" }}>{p.asin}</div>
                <div style={{ position: "absolute", top: 10, right: 12, background: "rgba(0,0,0,.4)", color: "#fff", fontSize: 10.5, padding: "3px 8px", borderRadius: 4, backdropFilter: "blur(4px)" }} className="mono">
                  BSR {p.bsr > 9999 ? (p.bsr/1000).toFixed(1) + "k" : p.bsr}
                </div>
                <div style={{ position: "absolute", bottom: 10, left: 12 }}>
                  <StatusBadge value={p.status}/>
                </div>
                <button
                  onClick={(e) => deleteProduct(p, e)}
                  title="Mettre à la corbeille"
                  style={{ position: "absolute", bottom: 10, right: 10, background: "rgba(0,0,0,.5)", color: "var(--red)", border: "none", borderRadius: 4, width: 22, height: 22, cursor: "pointer", display: "grid", placeItems: "center" }}
                >
                  <Icon name="x" size={11}/>
                </button>
              </div>
              <div style={{ padding: 14 }}>
                <div style={{ fontSize: 12.5, fontWeight: 550, lineHeight: 1.35, marginBottom: 6, height: 34, overflow: "hidden" }}>{p.name}</div>
                <div className="mono" style={{ fontSize: 10.5, color: "var(--text-faint)", marginBottom: 10 }}>{p.cat} · {p.supplier}</div>
                <div style={{ display: "flex", gap: 14, fontSize: 11.5 }}>
                  <div><div className="muted" style={{ fontSize: 10 }}>Prix</div><div className="num" style={{ fontWeight: 600 }}>${p.price.toFixed(2)}</div></div>
                  <div><div className="muted" style={{ fontSize: 10 }}>Marge</div><div className="num" style={{ fontWeight: 600, color: p.margin >= 28 ? "var(--green)" : "var(--text)" }}>{p.margin.toFixed(0)}%</div></div>
                  <div><div className="muted" style={{ fontSize: 10 }}>Stock</div><div className="num" style={{ fontWeight: 600, color: p.stock === 0 ? "var(--red)" : p.stock < 50 ? "var(--amber)" : "var(--text)" }}>{p.stock}</div></div>
                  <div style={{ marginLeft: "auto" }}><Avatar user={p.owner} size="sm"/></div>
                </div>
              </div>
            </div>
          );
        })}
        {list.length === 0 && (
          <div className="card" style={{ padding: 30, textAlign: "center", color: "var(--text-faint)", gridColumn: "1 / -1" }}>
            Aucun produit — clique « + Nouveau produit » pour en créer un.
          </div>
        )}
      </div>

      {newOpen && (
        <div onClick={() => setNewOpen(false)} style={{ position: "fixed", inset: 0, background: "rgba(0,0,0,0.55)", zIndex: 9999, display: "grid", placeItems: "center" }}>
          <div className="card" onClick={(e) => e.stopPropagation()} style={{ width: 480, padding: 20 }}>
            <div style={{ fontSize: 15, fontWeight: 600, marginBottom: 14 }}>Nouveau produit</div>
            <div className="stack" style={{ gap: 10 }}>
              <div>
                <div style={{ fontSize: 11, color: "var(--text-dim)", marginBottom: 4 }}>Nom *</div>
                <div className="input" style={{ height: 32, padding: "0 10px" }}>
                  <input autoFocus value={draft.name} onChange={(e) => setDraft(d => ({ ...d, name: e.target.value }))} placeholder="Nom du produit" style={{ flex: 1, background: "transparent", border: "none", outline: "none", color: "var(--text)", fontSize: 12.5 }}/>
                </div>
              </div>
              <div>
                <div style={{ fontSize: 11, color: "var(--text-dim)", marginBottom: 4 }}>ASIN</div>
                <div className="input" style={{ height: 32, padding: "0 10px" }}>
                  <input value={draft.asin} onChange={(e) => setDraft(d => ({ ...d, asin: e.target.value }))} placeholder="B0XXXXXXX" style={{ flex: 1, background: "transparent", border: "none", outline: "none", color: "var(--text)", fontSize: 12.5 }}/>
                </div>
              </div>
              <div>
                <div style={{ fontSize: 11, color: "var(--text-dim)", marginBottom: 4 }}>Fournisseur</div>
                <div className="input" style={{ height: 32, padding: "0 10px" }}>
                  <input value={draft.supplier} onChange={(e) => setDraft(d => ({ ...d, supplier: e.target.value }))} placeholder="Nom du fournisseur" style={{ flex: 1, background: "transparent", border: "none", outline: "none", color: "var(--text)", fontSize: 12.5 }}/>
                </div>
              </div>
              <div className="row" style={{ gap: 8 }}>
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 11, color: "var(--text-dim)", marginBottom: 4 }}>Prix $</div>
                  <div className="input" style={{ height: 32, padding: "0 10px" }}>
                    <input type="number" value={draft.price} onChange={(e) => setDraft(d => ({ ...d, price: e.target.value }))} style={{ flex: 1, background: "transparent", border: "none", outline: "none", color: "var(--text)", fontSize: 12.5 }}/>
                  </div>
                </div>
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 11, color: "var(--text-dim)", marginBottom: 4 }}>Coût $</div>
                  <div className="input" style={{ height: 32, padding: "0 10px" }}>
                    <input type="number" value={draft.cost} onChange={(e) => setDraft(d => ({ ...d, cost: e.target.value }))} style={{ flex: 1, background: "transparent", border: "none", outline: "none", color: "var(--text)", fontSize: 12.5 }}/>
                  </div>
                </div>
              </div>
            </div>
            <div className="row" style={{ marginTop: 16, justifyContent: "flex-end", gap: 8 }}>
              <button className="btn" onClick={() => setNewOpen(false)}>Annuler</button>
              <button className="btn" data-variant="primary" onClick={create} disabled={!draft.name.trim()}>Créer</button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

const ProductResearchGrid = () => {
  const toast = useToast();
  const [view, setView] = useState("grid"); // grid | kanban
  const [data, setData] = useState(PRODUCTS);
  const [selected, setSelected] = useState(new Set());
  const [sortKey, setSortKey] = useState("margin");
  const [sortDir, setSortDir] = useState("desc");
  const [filter, setFilter] = useState("");
  const [statusFilter, setStatusFilter] = useState("all");
  const dragRef = useRef(null);
  const fileInputRef = useRef(null);

  // CSV → products import (in-place)
  const handleImportFile = async (file) => {
    if (!file) return;
    try {
      const text = await file.text();
      const lines = text.replace(/\r/g, "").split("\n").filter(Boolean);
      if (lines.length < 2) { toast({ message: "CSV vide ou invalide", tone: "red" }); return; }
      const headers = lines[0].split(",").map(h => h.trim().toLowerCase());
      const items = lines.slice(1).map(line => {
        const cells = line.split(",");
        const obj = {};
        headers.forEach((h, i) => { obj[h] = (cells[i] || "").trim(); });
        return {
          id: obj.asin || obj.id || `p-${Date.now()}-${Math.random().toString(36).slice(2, 7)}`,
          asin: obj.asin || "",
          title: obj.title || obj.name || obj.asin || "—",
          name: obj.title || obj.name || obj.asin || "—",
          category: obj.category || obj.cat || "—",
          price: +obj.price || 0,
          cost: +obj.cost || 0,
          fees: +obj.fees || 0,
          bsr: +obj.bsr || 0,
          stock: +obj.stock || +obj.inventory || 0,
          status: obj.status || "pending",
          image: obj.image || obj.imageurl || obj.photo || "",
        };
      });
      // Sync D1
      await fetch("/api/sync", {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ col: "products", items }),
      }).catch(() => {});
      // Local update
      setData(d => [...items.map(i => ({ ...i, margin: i.price > 0 ? ((i.price - i.cost - i.fees) / i.price) * 100 : 0, owner: "clarens", vel: 0, supplier: "—", delta: 0, spark: [], cat: i.category })), ...d]);
      toast({ message: `${items.length} produit(s) importé(s)`, tone: "green" });
    } catch (err) {
      toast({ message: "Erreur import: " + err.message, tone: "red" });
    }
  };

  const handleExportCSV = () => {
    const headers = ["asin", "title", "category", "price", "cost", "fees", "margin", "bsr", "stock", "status"];
    const lines = [headers.join(",")];
    visible.forEach(p => {
      lines.push(headers.map(h => {
        const v = p[h] ?? p[h === "title" ? "name" : h] ?? "";
        return /[",\n]/.test(String(v)) ? `"${String(v).replace(/"/g, '""')}"` : String(v);
      }).join(","));
    });
    const blob = new Blob([lines.join("\n")], { type: "text/csv" });
    const url = URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = url; a.download = `produits-${Date.now()}.csv`; a.click();
    setTimeout(() => URL.revokeObjectURL(url), 1000);
    toast({ message: `${visible.length} produit(s) exporté(s)`, tone: "green" });
  };

  const visible = useMemo(() => {
    let v = [...data];
    if (filter) {
      const s = filter.toLowerCase();
      v = v.filter((p) => p.name.toLowerCase().includes(s) || p.asin.toLowerCase().includes(s) || p.cat.toLowerCase().includes(s));
    }
    if (statusFilter !== "all") v = v.filter((p) => p.status === statusFilter);
    v.sort((a, b) => {
      const x = a[sortKey], y = b[sortKey];
      const cmp = typeof x === "number" ? x - y : String(x).localeCompare(String(y));
      return sortDir === "asc" ? cmp : -cmp;
    });
    return v;
  }, [data, filter, statusFilter, sortKey, sortDir]);

  const toggleSel = (id) => {
    const next = new Set(selected);
    next.has(id) ? next.delete(id) : next.add(id);
    setSelected(next);
  };

  const toggleSort = (k) => {
    if (sortKey === k) setSortDir(d => d === "asc" ? "desc" : "asc");
    else { setSortKey(k); setSortDir("desc"); }
  };

  const handleDrop = (status) => {
    if (!dragRef.current) return;
    const id = dragRef.current;
    setData((d) => d.map((p) => p.id === id ? { ...p, status } : p));
    const product = data.find(p => p.id === id);
    toast({ message: `${product?.name?.slice(0, 30)}… → ${STATUS[status].label}`, tone: "green" });
    dragRef.current = null;
  };

  return (
    <div style={{ display: "flex", flexDirection: "column", height: "100%" }}>
      {/* Sheets menu bar */}
      <div style={{ display: "flex", alignItems: "center", padding: "6px 16px 0", gap: 2, borderBottom: "1px solid var(--border-subtle)" }}>
        <div className="row" style={{ gap: 0 }}>
          {MENU_BAR.map((m) => (
            <button key={m} className="btn" data-variant="ghost" data-size="sm" style={{ height: 26, fontSize: 12 }}>{m}</button>
          ))}
        </div>
        <div style={{ flex: 1 }}/>
        <div className="mono dim" style={{ fontSize: 10.5, marginRight: 8 }}>Auto-sauvegardé · il y a 12s</div>
      </div>

      {/* Toolbar */}
      <div className="row" style={{ padding: "10px 16px", gap: 8, borderBottom: "1px solid var(--border-subtle)", background: "var(--bg-0)" }}>
        <div style={{ position: "relative", width: 280 }}>
          <Icon name="search" size={13} style={{ position: "absolute", left: 10, top: "50%", transform: "translateY(-50%)", color: "var(--text-dim)" }} />
          <input className="input" value={filter} onChange={(e) => setFilter(e.target.value)} placeholder="Rechercher par nom, ASIN, catégorie…" style={{ paddingLeft: 30 }}/>
        </div>

        <div className="row" style={{ gap: 4, background: "var(--bg-2)", border: "1px solid var(--border-subtle)", borderRadius: 6, padding: 2 }}>
          {["all", ...Object.keys(STATUS)].map((s) => (
            <button key={s} onClick={() => setStatusFilter(s)} style={{
              height: 22, padding: "0 8px", borderRadius: 4, fontSize: 11.5,
              background: statusFilter === s ? "var(--bg-4)" : "transparent",
              color: statusFilter === s ? "var(--text)" : "var(--text-dim)",
              fontWeight: statusFilter === s ? 600 : 400,
            }}>
              {s === "all" ? "Tous" : STATUS[s].label}
            </button>
          ))}
        </div>

        <div style={{ flex: 1 }}/>

        {selected.size > 0 && (
          <>
            <span className="mono" style={{ fontSize: 11.5, color: "var(--accent)", padding: "0 8px" }}>{selected.size} sélectionnés</span>
            <button className="btn" data-size="sm"><Icon name="edit" size={12} /> Modifier</button>
            <button className="btn" data-size="sm" data-variant="danger"><Icon name="trash" size={12} /> Supprimer</button>
            <div style={{ width: 1, height: 16, background: "var(--border)", margin: "0 4px" }}/>
          </>
        )}

        <button className="btn" data-size="sm"><Icon name="filter" size={12} /> Filtres</button>
        <button className="btn" data-size="sm" onClick={handleExportCSV}><Icon name="download" size={12} /> CSV</button>
        <button className="btn" data-size="sm" onClick={() => fileInputRef.current?.click()}>
          <Icon name="upload" size={12} /> Importer
        </button>
        <input
          ref={fileInputRef}
          type="file"
          accept=".csv,text/csv"
          style={{ display: "none" }}
          onChange={(e) => { handleImportFile(e.target.files?.[0]); e.target.value = ""; }}
        />

        <div className="row" style={{ gap: 0, background: "var(--bg-2)", border: "1px solid var(--border-subtle)", borderRadius: 6, padding: 2, marginLeft: 4 }}>
          <button onClick={() => setView("grid")} style={{
            height: 22, padding: "0 8px", borderRadius: 4, fontSize: 11.5,
            background: view === "grid" ? "var(--bg-4)" : "transparent",
            color: view === "grid" ? "var(--text)" : "var(--text-dim)",
            display: "inline-flex", alignItems: "center", gap: 5, fontWeight: view === "grid" ? 600 : 400
          }}><Icon name="grid" size={11} /> Grille</button>
          <button onClick={() => setView("kanban")} style={{
            height: 22, padding: "0 8px", borderRadius: 4, fontSize: 11.5,
            background: view === "kanban" ? "var(--bg-4)" : "transparent",
            color: view === "kanban" ? "var(--text)" : "var(--text-dim)",
            display: "inline-flex", alignItems: "center", gap: 5, fontWeight: view === "kanban" ? 600 : 400
          }}><Icon name="layers" size={11} /> Kanban</button>
        </div>

        <button className="btn" data-size="sm" data-variant="primary"><Icon name="plus" size={12} /> Produit</button>
      </div>

      {/* Body */}
      {view === "grid" ? (
        <div style={{ flex: 1, overflow: "auto" }}>
          <table className="table" style={{ minWidth: 1400 }}>
            <thead>
              <tr>
                <th style={{ width: 36, textAlign: "center" }}>
                  <input type="checkbox"
                    checked={selected.size === visible.length && visible.length > 0}
                    onChange={() => setSelected(selected.size === visible.length ? new Set() : new Set(visible.map(v => v.id)))}
                    style={{ accentColor: "var(--accent)" }}
                  />
                </th>
                {COLUMNS.map((c) => (
                  <th key={c.key} style={{ minWidth: c.width, maxWidth: c.width }} onClick={() => toggleSort(c.key)}>
                    <span className="row" style={{ gap: 4 }}>
                      {c.label}
                      {sortKey === c.key && <Icon name={sortDir === "asc" ? "arrowUp" : "arrowDown"} size={10} />}
                    </span>
                  </th>
                ))}
              </tr>
            </thead>
            <tbody>
              {visible.map((p) => (
                <ProductRow key={p.id} p={p} selected={selected.has(p.id)} onToggle={() => toggleSel(p.id)} onEdit={() => toast({ message: "Mode édition inline (double-clic) — démo", tone: "blue" })}/>
              ))}
            </tbody>
          </table>
          {/* Status bar */}
          <div className="row" style={{ height: 28, padding: "0 16px", borderTop: "1px solid var(--border-subtle)", fontSize: 11, color: "var(--text-dim)", gap: 16, position: "sticky", bottom: 0, background: "var(--bg-0)" }}>
            <span><span className="mono">{visible.length}</span> lignes</span>
            <span>Stock total : <span className="mono" style={{ color: "var(--text)" }}>{visible.reduce((s,p)=>s+p.stock,0).toLocaleString()}</span></span>
            <span>Marge moy. : <span className="mono" style={{ color: "var(--green)" }}>{(visible.reduce((s,p)=>s+p.margin,0)/visible.length||0).toFixed(1)}%</span></span>
            <span style={{ marginLeft: "auto" }} className="mono">SQLite · D1 · KV synced</span>
          </div>
        </div>
      ) : (
        <div style={{ flex: 1, overflow: "auto", padding: 16, background: "var(--bg-0)" }}>
          <div style={{ display: "grid", gridTemplateColumns: `repeat(${Object.keys(STATUS).length}, 1fr)`, gap: 12, minWidth: 1200 }}>
            {Object.entries(STATUS).map(([key, meta]) => {
              const items = visible.filter((p) => p.status === key);
              return (
                <div key={key}
                     onDragOver={(e) => e.preventDefault()}
                     onDrop={() => handleDrop(key)}
                     style={{ display: "flex", flexDirection: "column", minHeight: 200 }}>
                  <div className="between" style={{ padding: "0 4px 10px" }}>
                    <div className="row" style={{ gap: 6 }}>
                      <span style={{ width: 8, height: 8, borderRadius: 2, background: `var(--${meta.tone === "muted" ? "text-dim" : meta.tone})` }} />
                      <span style={{ fontSize: 12, fontWeight: 600 }}>{meta.label}</span>
                      <span className="mono" style={{ fontSize: 10.5, color: "var(--text-faint)" }}>{items.length}</span>
                    </div>
                    <button className="icon-btn" style={{ width: 22, height: 22 }}><Icon name="plus" size={12} /></button>
                  </div>
                  <div style={{ display: "flex", flexDirection: "column", gap: 8, padding: 8, background: "var(--bg-1)", border: "1px solid var(--border-subtle)", borderRadius: 10, minHeight: 100, flex: 1 }}>
                    {items.map((p) => (
                      <KanbanCard key={p.id} p={p} onDragStart={() => dragRef.current = p.id} />
                    ))}
                    {items.length === 0 && <div style={{ padding: 16, textAlign: "center", fontSize: 11, color: "var(--text-faint)" }}>Glissez ici</div>}
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      )}
    </div>
  );
};

window.ProductResearch = ProductResearch;
