// catalogue-admin.jsx — Page « Catalogue » (admin) : photos, familles, ordre, tuiles et presets.
//
// Les noms, prix et descriptions viennent de QuickBooks (lecture seule ici : on les change dans
// QuickBooks). Ici on gère ce que QuickBooks ne sait pas : image (bucket Supabase « catalogue »),
// famille d'affichage, ordre, tuile ou recherche seulement, et les presets du parcours.

(function () {
  const { useState, useEffect, useMemo } = React;
  const sb = () => window.RAYCAST_SUPABASE;
  const fmt = (n) => window.CALC_RE.fmtCAD(n);

  async function uploadImage(qbo_id, file) {
    const ext = (file.name.split(".").pop() || "png").toLowerCase().replace("jpeg", "jpg");
    const path = `${qbo_id}-${Date.now()}.${ext}`;
    const { error } = await sb().storage.from("catalogue").upload(path, file, { upsert: true, contentType: file.type });
    if (error) throw error;
    const { data } = sb().storage.from("catalogue").getPublicUrl(path);
    return data.publicUrl;
  }

  async function saveMeta(qbo_id, patch) {
    const { error } = await sb().from("catalogue_meta").upsert({ qbo_id, ...patch, updated_at: new Date().toISOString() }, { onConflict: "qbo_id" });
    if (error) throw error;
  }

  function LigneArticle({ a, onChange, isAdmin }) {
    const [busy, setBusy] = useState(false);
    const [ok, setOk] = useState(false);
    const apply = async (patch) => {
      setBusy(true); setOk(false);
      try { await saveMeta(a.id, patch); onChange(a.id, patch); setOk(true); setTimeout(() => setOk(false), 1500); }
      catch (e) { alert("Sauvegarde refusée : " + (e.message || e)); }
      finally { setBusy(false); }
    };
    const pick = () => {
      const i = document.createElement("input"); i.type = "file"; i.accept = "image/*";
      i.onchange = async () => { if (!i.files[0]) return; setBusy(true); try { const url = await uploadImage(a.id, i.files[0]); await apply({ image_url: url }); } catch (e) { alert("Téléversement refusé : " + (e.message || e)); } finally { setBusy(false); } };
      i.click();
    };
    return (
      <tr style={{ opacity: busy ? .6 : 1 }}>
        <td>{a.image_url ? <img className="re-admin-thumb" src={a.image_url} alt="" onClick={isAdmin ? pick : undefined} title="Changer la photo" /> : <div className="re-admin-thumb empty" onClick={isAdmin ? pick : undefined}>+ photo</div>}</td>
        <td><div style={{ fontWeight: 600 }}>{a.nom}</div><div style={{ fontSize: 11, color: "#94a3b8" }}>{a.categorie}{a.sous_categorie ? " · " + a.sous_categorie : ""}{a.sku ? " · " + a.sku : ""} · Id {a.id}</div></td>
        <td style={{ whiteSpace: "nowrap", fontWeight: 700 }}>{fmt(a.prix)}</td>
        <td><select disabled={!isAdmin} value={a.famille} onChange={e => apply({ famille: e.target.value })}>{window.CatalogueRE.FAMILLES.map(f => <option key={f.id} value={f.id}>{f.label}</option>)}</select></td>
        <td><input disabled={!isAdmin} type="number" defaultValue={a.ordre === 9999 ? "" : a.ordre} onBlur={e => { const v = e.target.value === "" ? 9999 : Number(e.target.value); if (v !== a.ordre) apply({ ordre: v }); }} /></td>
        <td><input disabled={!isAdmin} type="checkbox" checked={!!a.tuile} onChange={e => apply({ tuile: e.target.checked })} /></td>
        <td>{a.image_url && isAdmin && <button className="re-btn small" onClick={() => apply({ image_url: null })}>Retirer photo</button>} {ok && <span className="re-saved">enregistré</span>}</td>
      </tr>
    );
  }

  function Articles({ cat, reload, isAdmin }) {
    const [q, setQ] = useState("");
    const [fam, setFam] = useState("");
    const [local, setLocal] = useState({});
    const rows = useMemo(() => cat.articles.map(a => ({ ...a, ...(local[a.id] || {}) })).filter(a => (!fam || a.famille === fam) && (!q || `${a.nom} ${a.categorie} ${a.sku || ""}`.toLowerCase().includes(q.toLowerCase()))), [cat, q, fam, local]);
    const onChange = (id, patch) => setLocal(l => ({ ...l, [id]: { ...(l[id] || {}), ...patch } }));
    return (
      <>
        <div className="re-toolbar">
          <div className="re-chips">
            <button className={`re-chip ${!fam ? "on" : ""}`} onClick={() => setFam("")}>Toutes</button>
            {window.CatalogueRE.FAMILLES.map(f => <button key={f.id} className={`re-chip ${fam === f.id ? "on" : ""}`} onClick={() => setFam(f.id)}>{f.label}</button>)}
          </div>
          <input className="re-search" type="search" placeholder="Chercher…" value={q} onChange={e => setQ(e.target.value)} />
        </div>
        <table>
          <thead><tr><th>Photo</th><th>Article (QuickBooks)</th><th>Prix HT</th><th>Famille</th><th>Ordre</th><th>Tuile</th><th></th></tr></thead>
          <tbody>{rows.map(a => <LigneArticle key={a.id} a={a} onChange={onChange} isAdmin={isAdmin} />)}</tbody>
        </table>
        <p className="re-muted" style={{ marginTop: 10 }}>{rows.length} article{rows.length > 1 ? "s" : ""}. Noms, prix et descriptions se changent dans QuickBooks ; le worker relit toutes les 30 minutes, ou tout de suite avec « relire QuickBooks ».</p>
      </>
    );
  }

  function PresetEditor({ preset, cat, onSaved, onDeleted }) {
    const [p, setP] = useState(preset);
    const [q, setQ] = useState("");
    const [busy, setBusy] = useState(false);
    const cand = useMemo(() => q.length < 2 ? [] : cat.articles.filter(a => a.nom.toLowerCase().includes(q.toLowerCase())).slice(0, 8), [q, cat]);
    const lignes = p.lignes || [];
    const setL = (lignes) => setP({ ...p, lignes });
    const total = lignes.reduce((s, l) => { const a = cat.byId.get(l.qbo_id); return s + (a ? a.prix * (Number(l.qty) || 0) : 0); }, 0);
    const save = async () => {
      setBusy(true);
      try {
        const row = { nom: p.nom, famille: p.famille || null, description: p.description || null, lignes, ordre: Number(p.ordre) || 100, actif: p.actif !== false, updated_at: new Date().toISOString() };
        const r = p.id ? await sb().from("presets").update(row).eq("id", p.id).select().single() : await sb().from("presets").insert(row).select().single();
        if (r.error) throw r.error;
        onSaved(r.data);
      } catch (e) { alert("Sauvegarde refusée : " + (e.message || e)); }
      finally { setBusy(false); }
    };
    const del = async () => {
      if (!p.id || !confirm(`Supprimer le preset « ${p.nom} » ?`)) return;
      const { error } = await sb().from("presets").delete().eq("id", p.id);
      if (error) return alert(error.message);
      onDeleted(p.id);
    };
    return (
      <div className="re-preset-editor">
        <div className="re-grid2">
          <label className="re-field span"><span className="re-field-label">Nom du preset</span><input value={p.nom || ""} onChange={e => setP({ ...p, nom: e.target.value })} /></label>
          <label className="re-field"><span className="re-field-label">Famille</span><select value={p.famille || ""} onChange={e => setP({ ...p, famille: e.target.value })}><option value="">—</option>{window.CatalogueRE.FAMILLES.map(f => <option key={f.id} value={f.id}>{f.label}</option>)}</select></label>
          <label className="re-field"><span className="re-field-label">Ordre</span><input type="number" value={p.ordre || 100} onChange={e => setP({ ...p, ordre: e.target.value })} /></label>
          <label className="re-field span"><span className="re-field-label">Description (infobulle)</span><input value={p.description || ""} onChange={e => setP({ ...p, description: e.target.value })} /></label>
        </div>
        <div className="re-preset-lines">
          {lignes.map((l, i) => { const a = cat.byId.get(l.qbo_id); return (
            <div key={i} className="re-preset-line">
              <span>{a ? a.nom : l.qbo_id} <span className="re-muted">{a ? fmt(a.prix) : ""}</span></span>
              <input type="number" min="0" value={l.qty} onChange={e => setL(lignes.map((x, j) => j === i ? { ...x, qty: Number(e.target.value) || 0 } : x))} />
              <button className="re-btn small" onClick={() => setL(lignes.filter((_, j) => j !== i))}>×</button>
            </div>); })}
          <div className="re-typeahead">
            <input className="re-search" placeholder="Ajouter un article…" value={q} onChange={e => setQ(e.target.value)} />
            {cand.length > 0 && <div className="re-typeahead-list">{cand.map(a => <div key={a.id} className="re-typeahead-item" onClick={() => { setL([...lignes, { qbo_id: a.id, qty: 1 }]); setQ(""); }}><b>{a.nom}</b><span>{fmt(a.prix)} · {a.famille_label}</span></div>)}</div>}
          </div>
        </div>
        <div className="re-actions">
          <span className="re-muted">Total HT du preset : <b>{fmt(total)}</b></span>
          <div className="re-actions-right">
            {p.id && <button className="re-btn" onClick={del}>Supprimer</button>}
            <button className="re-btn primary" disabled={busy || !p.nom} onClick={save}>Enregistrer</button>
          </div>
        </div>
      </div>
    );
  }

  function Presets({ cat, reload }) {
    const [editing, setEditing] = useState(null);
    const [list, setList] = useState(cat.presets);
    useEffect(() => setList(cat.presets), [cat]);
    return (
      <>
        <div className="re-actions" style={{ marginTop: 0 }}><span className="re-muted">Un preset coche des tuiles avec des quantités, dans le catalogue complet.</span><button className="re-btn primary" onClick={() => setEditing({ nom: "", lignes: [], ordre: 100 })}>Nouveau preset</button></div>
        {editing && <PresetEditor preset={editing} cat={cat} onSaved={(row) => { setEditing(null); reload({ force: true }); }} onDeleted={() => { setEditing(null); reload({ force: true }); }} />}
        <table>
          <thead><tr><th>Preset</th><th>Famille</th><th>Lignes</th><th>Total HT</th><th>Ordre</th><th></th></tr></thead>
          <tbody>{list.map(p => <tr key={p.id}><td><b>{p.nom}</b><div style={{ fontSize: 11, color: "#94a3b8" }}>{p.description}</div></td><td>{p.famille}</td><td>{p.lignes.length}</td><td>{fmt(p.lignes.reduce((s, l) => { const a = cat.byId.get(l.qbo_id); return s + (a ? a.prix * l.qty : 0); }, 0))}</td><td>{p.ordre}</td><td><button className="re-btn small" onClick={() => setEditing(p)}>Modifier</button></td></tr>)}</tbody>
        </table>
      </>
    );
  }

  function CatalogueAdmin({ isAdmin }) {
    const { cat, loading, error, reload } = window.CatalogueRE.useCatalogue();
    const [tab, setTab] = useState("articles");
    if (error) return <div className="re-admin"><div className="re-alert error">{error}</div></div>;
    if (loading || !cat) return <div className="re-admin">Chargement du catalogue…</div>;
    return (
      <div className="re-admin">
        <h1>Catalogue RE</h1>
        <div className="re-muted">{cat.articles.length} articles actifs des catégories RE de QuickBooks · synchronisé {cat.synced_at ? new Date(cat.synced_at).toLocaleString("fr-CA") : "—"} · <button className="re-link" onClick={() => reload({ refresh: true })}>relire QuickBooks maintenant</button></div>
        {!isAdmin && <div className="re-alert" style={{ marginTop: 10 }}>Lecture seule : seuls les administrateurs modifient le catalogue.</div>}
        <div className="re-admin-tabs">
          <button className={`re-chip ${tab === "articles" ? "on" : ""}`} onClick={() => setTab("articles")}>Articles et photos</button>
          <button className={`re-chip ${tab === "presets" ? "on" : ""}`} onClick={() => setTab("presets")}>Presets</button>
        </div>
        {tab === "articles" ? <Articles cat={cat} reload={reload} isAdmin={isAdmin} /> : <Presets cat={cat} reload={reload} />}
      </div>
    );
  }

  window.CatalogueAdmin = CatalogueAdmin;
})();
