// Caffè Italia · admin : tableau de bord, fiches clients, commandes saisies.
// ==========================================================================
// Une fiche client est une demande pro approuvée (table pro_requests). Les
// pros inscrits sur le site en ont une ; Francesco en crée lui-même pour les
// clients servis hors du site. Il y saisit les commandes passées par
// téléphone ou en tournée : produits, prix négocié, facture faite ailleurs
// (PDF déposé ici) et suivi du paiement.
//
// Écritures sensibles via api/admin.mjs (création de fiche, de commande,
// ouverture d'un accès au site). Le reste passe par les policies admin.

const { useState: _clUseState, useEffect: _clUseEffect, useMemo: _clUseMemo } = React;

const CL_REVENUE_STATUSES = ["paid", "invoiced", "shipped", "delivered"];
const CL_PAYMENT_METHODS = [
  ["virement", "Virement"], ["cheque", "Chèque"], ["especes", "Espèces"],
  ["carte", "Carte"], ["stripe", "Stripe"], ["autre", "Autre"],
];
const clEur = (n) => (Number(n) || 0).toLocaleString("fr-FR", { minimumFractionDigits: 2, maximumFractionDigits: 2 }) + " €";
const clDate = (d) => d ? new Date(d).toLocaleDateString("fr-FR") : "-";
const clToday = () => new Date().toISOString().slice(0, 10);
function clAddDays(isoDate, days){
  const d = new Date(isoDate + "T12:00:00Z"); d.setUTCDate(d.getUTCDate() + (Number(days) || 0));
  return d.toISOString().slice(0, 10);
}
const clIsOverdue = (o) => o.status === "invoiced" && o.invoice_due && o.invoice_due < clToday();
const clClientOrders = (c, orders) => orders.filter(o => o.client_id === c.id || (c.user_id && o.user_id === c.user_id));

// Appel à api/admin.mjs avec le jeton de l'admin connecté.
async function clAdminApi(body){
  const sess = window.sb ? (await window.sb.auth.getSession()).data.session : null;
  const r = await fetch("/api/admin", {
    method: "POST",
    headers: { "Content-Type": "application/json", ...(sess?.access_token ? { Authorization: `Bearer ${sess.access_token}` } : {}) },
    body: JSON.stringify(body),
  });
  let data = {}; try { data = await r.json(); } catch {}
  if (!r.ok) throw new Error(data.error || `Erreur ${r.status}`);
  return data;
}

// PDF de facture : bucket privé « invoices ». L'admin dépose ; l'admin et
// le client propriétaire de la commande ouvrent via un lien signé court.
async function clUploadInvoicePdf(orderId, file){
  if (!file) return null;
  if (file.type && file.type !== "application/pdf") throw new Error("Le fichier doit être un PDF");
  const safe = (file.name || "facture.pdf").replace(/[^A-Za-z0-9._-]/g, "_");
  const path = `${orderId}/${Date.now()}-${safe}`;
  const { error } = await window.sb.storage.from("invoices").upload(path, file, { contentType: "application/pdf", upsert: false });
  if (error) throw new Error(error.message);
  const { error: e2 } = await window.sb.from("orders").update({ invoice_pdf_path: path }).eq("id", orderId);
  if (e2) throw new Error(e2.message);
  return path;
}
async function openInvoicePdf(path){
  if (!path || !window.sb) return;
  const w = window.open("", "_blank");   // ouvert avant l'attente : pas de blocage de fenêtre
  const { data, error } = await window.sb.storage.from("invoices").createSignedUrl(path, 120);
  if (error || !data?.signedUrl) { if (w) w.close(); alert("Facture indisponible"); return; }
  if (w) w.location = data.signedUrl; else window.location.href = data.signedUrl;
}
window.openInvoicePdf = openInvoicePdf;

function clUseAdminData(){
  const [state, setState] = _clUseState({ orders: null, clients: null, err: null });
  const load = async () => {
    if (!window.sb) { setState(s => ({ ...s, err: "Supabase non disponible" })); return; }
    const [o, c] = await Promise.all([
      window.sb.from("orders").select("*").order("created_at", { ascending: false }).limit(2000),
      window.sb.from("pro_requests").select("*").eq("status", "approved").order("company", { ascending: true }),
    ]);
    if (o.error || c.error) { setState(s => ({ ...s, err: (o.error || c.error).message })); return; }
    setState({ orders: o.data || [], clients: c.data || [], err: null });
  };
  _clUseEffect(() => { load(); }, []);
  return { ...state, reload: load };
}

function ClCard({ label, value, hint, tone, onClick }){
  return (
    <div onClick={onClick} style={{
      padding:"18px 20px",background:"var(--paper-2)",borderRadius:8,cursor:onClick?"pointer":"default",
      border:"1px solid " + (tone === "warn" ? "var(--rosso)" : tone === "gold" ? "#caa451" : "var(--hairline)"),
    }}>
      <div style={{fontSize:11,letterSpacing:".1em",textTransform:"uppercase",color:"var(--muted)",fontWeight:600}}>{label}</div>
      <div style={{fontFamily:"var(--font-display)",fontSize:30,marginTop:6,color: tone === "warn" ? "var(--rosso)" : "var(--ink)"}}>{value}</div>
      {hint && <div style={{fontSize:12.5,color:"var(--muted)",marginTop:4}}>{hint}</div>}
    </div>
  );
}
function ClSection({ title, children, action }){
  return (
    <section style={{marginTop:28}}>
      <div style={{display:"flex",justifyContent:"space-between",alignItems:"baseline",gap:12,marginBottom:10}}>
        <h3 style={{fontSize:13,letterSpacing:".1em",textTransform:"uppercase",color:"var(--muted)",margin:0}}>{title}</h3>
        {action}
      </div>
      {children}
    </section>
  );
}
function ClStatus({ o }){
  if (clIsOverdue(o)) return <span className="chip chip-rosso" style={{fontSize:10}}>En retard</span>;
  const label = (ORDER_STATUS.find(x => x[0] === o.status) || [o.status, o.status])[1];
  const gold = o.status === "requested" || o.status === "invoiced";
  return <span className="chip" style={{fontSize:10,background: gold ? "#caa451" : "var(--paper)",color: gold ? "#0e0d0c" : "var(--ink)",border:"1px solid var(--hairline-strong)"}}>{o.status === "invoiced" ? "À régler" : label}</span>;
}

// ─── Tableau de bord ───────────────────────────────────────────────────
function DashboardPanel({ goTab, openClient }){
  const { orders, clients, err } = clUseAdminData();
  const [lines, setLines] = _clUseState(null);
  _clUseEffect(() => {
    if (!orders) return;
    const since = new Date(); since.setMonth(since.getMonth() - 12);
    const ids = orders.filter(o => CL_REVENUE_STATUSES.includes(o.status) && new Date(o.created_at) >= since).map(o => o.id);
    if (ids.length === 0) { setLines([]); return; }
    (async () => {
      const all = [];
      for (let i = 0; i < ids.length; i += 150) {
        const { data } = await window.sb.from("order_items").select("order_id, product_id, product_name, qty, unit_price").in("order_id", ids.slice(i, i + 150));
        all.push(...(data || []));
      }
      setLines(all);
    })();
  }, [orders]);

  if (err) return <PanelError msg={err}/>;
  if (!orders || !clients) return <PanelLoading/>;

  const now = new Date();
  const monthKey = (d) => { const x = new Date(d); return x.getFullYear() * 12 + x.getMonth(); };
  const thisMonth = monthKey(now);
  const counted = orders.filter(o => CL_REVENUE_STATUSES.includes(o.status));
  const month = counted.filter(o => monthKey(o.created_at) === thisMonth);
  const sum = (list) => list.reduce((s, o) => s + Number(o.total || 0), 0);
  const monthManual = sum(month.filter(o => o.source === "manual"));
  const monthSitePro = sum(month.filter(o => o.source !== "manual" && o.pro));
  const monthSitePublic = sum(month.filter(o => o.source !== "manual" && !o.pro));
  const toValidate = orders.filter(o => o.status === "requested");
  // Les commandes saisies sont en général déjà livrées : seules celles du site comptent.
  const toDeliver = orders.filter(o => o.source !== "manual" && (o.status === "paid" || o.status === "shipped"));
  const unpaid = orders.filter(o => o.status === "invoiced")
    .sort((a, b) => (clIsOverdue(b) - clIsOverdue(a)) || String(a.invoice_due || "9").localeCompare(String(b.invoice_due || "9")));
  const overdue = unpaid.filter(clIsOverdue);

  const months = [];
  for (let i = 5; i >= 0; i--) {
    const k = thisMonth - i;
    const list = counted.filter(o => monthKey(o.created_at) === k);
    months.push({ k, label: new Date(Math.floor(k / 12), k % 12, 1).toLocaleDateString("fr-FR", { month: "short" }), site: sum(list.filter(o => o.source !== "manual")), manual: sum(list.filter(o => o.source === "manual")) });
  }
  const maxMonth = Math.max(1, ...months.map(m => m.site + m.manual));

  const year = new Date(); year.setMonth(year.getMonth() - 12);
  const clientName = (o) => o.company || o.shipping_name || "Client";
  const byClient = {};
  for (const o of counted.filter(o => new Date(o.created_at) >= year)) {
    const c = clients.find(c => o.client_id === c.id || (c.user_id && o.user_id === c.user_id));
    const key = c ? c.id : "x:" + clientName(o);
    byClient[key] = byClient[key] || { client: c, name: c ? c.company : clientName(o), total: 0, n: 0 };
    byClient[key].total += Number(o.total || 0); byClient[key].n++;
  }
  const topClients = Object.values(byClient).sort((a, b) => b.total - a.total).slice(0, 8);
  const byProduct = {};
  for (const l of lines || []) {
    const key = l.product_id || l.product_name;
    byProduct[key] = byProduct[key] || { name: l.product_name, qty: 0, ht: 0 };
    byProduct[key].qty += Number(l.qty || 0); byProduct[key].ht += Number(l.qty || 0) * Number(l.unit_price || 0);
  }
  const topProducts = Object.values(byProduct).sort((a, b) => b.qty - a.qty).slice(0, 8);
  const rowStyle = { display:"flex",justifyContent:"space-between",gap:12,padding:"10px 14px",borderTop:"1px solid var(--hairline)",fontSize:13.5,alignItems:"center" };

  return (
    <div>
      <div style={{display:"grid",gridTemplateColumns:"repeat(auto-fit,minmax(200px,1fr))",gap:12}}>
        <ClCard label={`Chiffre d'affaires · ${now.toLocaleDateString("fr-FR",{month:"long"})}`} value={clEur(sum(month))}
          hint={`Site ${clEur(monthSitePublic + monthSitePro)} · Hors site ${clEur(monthManual)}`}/>
        <ClCard label="À valider" value={toValidate.length} hint="Commandes pro du site à appeler" tone={toValidate.length ? "gold" : null} onClick={()=>goTab("orders")}/>
        <ClCard label="À livrer" value={toDeliver.length} hint="Payées ou en tournée" onClick={()=>goTab("orders")}/>
        <ClCard label="Factures à régler" value={clEur(sum(unpaid))} hint={overdue.length ? `${overdue.length} en retard · ${clEur(sum(overdue))}` : `${unpaid.length} facture(s)`} tone={overdue.length ? "warn" : null}/>
      </div>

      <ClSection title="Six derniers mois (TTC)">
        <div style={{display:"grid",gridTemplateColumns:"repeat(6,1fr)",gap:10,alignItems:"end",height:150,padding:"0 4px"}}>
          {months.map(m => (
            <div key={m.k} style={{display:"flex",flexDirection:"column",alignItems:"center",gap:6,height:"100%",justifyContent:"flex-end"}}>
              <div style={{fontSize:11,color:"var(--muted)"}}>{Math.round(m.site + m.manual).toLocaleString("fr-FR")} €</div>
              <div style={{width:"100%",maxWidth:56,display:"flex",flexDirection:"column",justifyContent:"flex-end",height:`${Math.max(2, (m.site + m.manual) / maxMonth * 100)}px`}}>
                <div style={{flex:m.manual,background:"#caa451",borderRadius:"3px 3px 0 0"}} title={`Hors site ${clEur(m.manual)}`}/>
                <div style={{flex:m.site,background:"var(--rosso)"}} title={`Site ${clEur(m.site)}`}/>
              </div>
              <div style={{fontSize:11.5,textTransform:"capitalize"}}>{m.label}</div>
            </div>
          ))}
        </div>
        <div style={{display:"flex",gap:16,fontSize:12,color:"var(--muted)",marginTop:8}}>
          <span><span style={{display:"inline-block",width:10,height:10,background:"var(--rosso)",marginRight:6}}/>Site</span>
          <span><span style={{display:"inline-block",width:10,height:10,background:"#caa451",marginRight:6}}/>Hors site</span>
        </div>
      </ClSection>

      <ClSection title={`Factures à régler · ${unpaid.length}`}>
        {unpaid.length === 0 ? <div style={{fontSize:13.5,color:"var(--muted)"}}>Aucune facture en attente.</div> : (
          <div style={{border:"1px solid var(--hairline)",borderRadius:8,overflow:"hidden"}}>
            {unpaid.slice(0, 15).map(o => {
              const c = clients.find(c => o.client_id === c.id || (c.user_id && o.user_id === c.user_id));
              return (
                <div key={o.id} style={{...rowStyle,cursor:c?"pointer":"default"}} onClick={()=> c && openClient(c.id)}>
                  <div style={{minWidth:0}}>
                    <b>{clientName(o)}</b>
                    <span style={{color:"var(--muted)",marginLeft:8,fontSize:12.5}}>{o.invoice_number ? `Facture ${o.invoice_number}` : o.source === "manual" ? "Saisie" : "Facture Stripe"} · {clDate(o.created_at)}</span>
                  </div>
                  <div style={{display:"flex",gap:10,alignItems:"center",whiteSpace:"nowrap"}}>
                    <span style={{fontSize:12.5,color: clIsOverdue(o) ? "var(--rosso)" : "var(--muted)"}}>{o.invoice_due ? `échéance ${clDate(o.invoice_due)}` : ""}</span>
                    <b>{clEur(o.total)}</b>
                  </div>
                </div>
              );
            })}
          </div>
        )}
      </ClSection>

      <div style={{display:"grid",gridTemplateColumns:"repeat(auto-fit,minmax(300px,1fr))",gap:20}}>
        <ClSection title="Meilleurs clients · 12 mois">
          {topClients.length === 0 ? <div style={{fontSize:13.5,color:"var(--muted)"}}>Pas encore de ventes.</div> : (
            <div style={{border:"1px solid var(--hairline)",borderRadius:8,overflow:"hidden"}}>
              {topClients.map((x, i) => (
                <div key={i} style={{...rowStyle,cursor:x.client?"pointer":"default"}} onClick={()=> x.client && openClient(x.client.id)}>
                  <span>{x.name} <span style={{color:"var(--muted)",fontSize:12}}>· {x.n} cde</span></span><b>{clEur(x.total)}</b>
                </div>
              ))}
            </div>
          )}
        </ClSection>
        <ClSection title="Produits les plus vendus · 12 mois">
          {lines === null ? <div style={{fontSize:13.5,color:"var(--muted)"}}>Chargement…</div> : topProducts.length === 0 ? <div style={{fontSize:13.5,color:"var(--muted)"}}>Pas encore de ventes.</div> : (
            <div style={{border:"1px solid var(--hairline)",borderRadius:8,overflow:"hidden"}}>
              {topProducts.map((p, i) => (
                <div key={i} style={rowStyle}><span style={{minWidth:0}}>{p.name}</span><b style={{whiteSpace:"nowrap"}}>{p.qty} u.</b></div>
              ))}
            </div>
          )}
        </ClSection>
      </div>
    </div>
  );
}

// ─── Clients ───────────────────────────────────────────────────────────
function ClientsPanel({ flash, products, openId, onOpen }){
  const data = clUseAdminData();
  const [view, setView] = _clUseState("pros");     // pros · particuliers
  const [q, setQ] = _clUseState("");
  const [creating, setCreating] = _clUseState(false);

  if (data.err) return <PanelError msg={data.err}/>;
  if (!data.orders || !data.clients) return <PanelLoading/>;

  const current = openId ? data.clients.find(c => c.id === openId) : null;
  if (current) {
    return <ClientDetail client={current} orders={clClientOrders(current, data.orders)} products={products} flash={flash}
      onBack={()=>onOpen(null)} reload={data.reload}/>;
  }
  if (creating) {
    return <ClientForm flash={flash} onCancel={()=>setCreating(false)} onSaved={async (c)=>{ setCreating(false); await data.reload(); onOpen(c.id); }}/>;
  }

  const needle = q.trim().toLowerCase();
  const list = data.clients.filter(c => !needle || [c.company, c.full_name, c.email, c.phone, c.address_city].some(v => String(v || "").toLowerCase().includes(needle)));

  return (
    <div>
      <div style={{display:"flex",gap:8,marginBottom:18,flexWrap:"wrap",alignItems:"center"}}>
        {[["pros",`Clients pro · ${data.clients.length}`],["particuliers","Comptes particuliers"]].map(([id,label]) => (
          <button key={id} onClick={()=>setView(id)} style={{
            padding:"7px 13px",borderRadius:99,fontSize:12,fontWeight:600,
            background: view===id ? "var(--ink)" : "transparent", color: view===id ? "var(--paper)" : "var(--ink)",
            border:"1px solid " + (view===id ? "var(--ink)" : "var(--hairline-strong)"),
          }}>{label}</button>
        ))}
        {view === "pros" && <>
          <input value={q} onChange={e=>setQ(e.target.value)} placeholder="Rechercher un client…" style={{...inputStyle,flex:"1 1 200px",maxWidth:320,padding:"8px 12px"}}/>
          <button onClick={()=>setCreating(true)} className="btn btn-primary btn-sm" style={{marginLeft:"auto"}}>+ Nouveau client</button>
        </>}
      </div>
      {view === "particuliers" ? <CustomersPanel flash={flash}/> : list.length === 0 ? (
        <EmptyState label={needle ? "Aucun client ne correspond." : "Aucun client pro pour le moment."} hint="Créez une fiche pour un client servi hors du site, ou approuvez une demande pro."/>
      ) : (
        <div style={{border:"1px solid var(--hairline)",borderRadius:8,overflow:"auto"}}>
          <table style={{width:"100%",borderCollapse:"collapse",fontSize:13.5}} className="admin-table">
            <thead>
              <tr style={{background:"var(--paper-2)",fontSize:11,letterSpacing:".1em",textTransform:"uppercase",color:"var(--muted)"}}>
                <th style={th}>Client</th><th style={th}>Contact</th><th style={th}>Ville</th>
                <th style={{...th,textAlign:"right"}}>12 mois</th><th style={{...th,textAlign:"right"}}>À régler</th>
              </tr>
            </thead>
            <tbody>
              {list.map(c => {
                const os = clClientOrders(c, data.orders);
                const since = new Date(); since.setMonth(since.getMonth() - 12);
                const year = os.filter(o => CL_REVENUE_STATUSES.includes(o.status) && new Date(o.created_at) >= since).reduce((s, o) => s + Number(o.total || 0), 0);
                const due = os.filter(o => o.status === "invoiced");
                const late = due.some(clIsOverdue);
                return (
                  <tr key={c.id} onClick={()=>onOpen(c.id)} style={{borderTop:"1px solid var(--hairline)",cursor:"pointer"}}>
                    <td style={td} data-label="Client">
                      <div style={{fontWeight:600}}>{c.company}</div>
                      <div style={{display:"flex",gap:6,marginTop:4,flexWrap:"wrap"}}>
                        <span className="chip" style={{fontSize:10}}>{c.source === "admin" ? "Hors site" : "Inscrit sur le site"}</span>
                        {c.user_id && c.source === "admin" && <span className="chip" style={{fontSize:10}}>Accès site</span>}
                      </div>
                    </td>
                    <td style={td} data-label="Contact">{c.full_name}<div style={{fontSize:12,color:"var(--muted)"}}>{c.phone || c.email || "-"}</div></td>
                    <td style={td} data-label="Ville">{[c.address_zip, c.address_city].filter(Boolean).join(" ") || "-"}</td>
                    <td style={{...td,textAlign:"right"}} data-label="12 mois">{clEur(year)}</td>
                    <td style={{...td,textAlign:"right",color: late ? "var(--rosso)" : "var(--ink)",fontWeight: due.length ? 700 : 400}} data-label="À régler">
                      {due.length ? clEur(due.reduce((s, o) => s + Number(o.total || 0), 0)) : "-"}
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
      )}
    </div>
  );
}

const CL_EMPTY_CLIENT = { company:"", full_name:"", email:"", phone:"", siret:"", activity:"horeca",
  address_line1:"", address_line2:"", address_zip:"", address_city:"", payment_terms_days:30, notes:"" };

function ClientFields({ form, set }){
  const f = (k, label, extra = {}) => (
    <AdminField label={label}>
      <input value={form[k] || ""} onChange={e=>set(k, e.target.value)} style={inputStyle} {...extra}/>
    </AdminField>
  );
  return (
    <div style={{display:"grid",gridTemplateColumns:"repeat(auto-fit,minmax(240px,1fr))",gap:"4px 18px"}}>
      {f("company", "Établissement *")}
      {f("full_name", "Contact")}
      {f("phone", "Téléphone", { type:"tel" })}
      {f("email", "Email (pour l'accès au site)", { type:"email" })}
      {f("siret", "SIRET")}
      <AdminField label="Activité">
        <select value={form.activity || "horeca"} onChange={e=>set("activity", e.target.value)} style={inputStyle}>
          {(window.PRO_ACTIVITIES || [{ id:"horeca", fr:"Bar, restaurant, hôtel" }]).map(a => <option key={a.id} value={a.id}>{a.fr}</option>)}
        </select>
      </AdminField>
      {f("address_line1", "Adresse")}
      {f("address_line2", "Complément")}
      {f("address_zip", "Code postal", { inputMode:"numeric", maxLength:5 })}
      {f("address_city", "Ville")}
      <AdminField label="Facture">
        <select value={String(form.payment_terms_days || 0)} onChange={e=>set("payment_terms_days", Number(e.target.value))} style={inputStyle}>
          <option value="0">à réception</option><option value="30">à 30 jours</option>
        </select>
      </AdminField>
      <div style={{gridColumn:"1 / -1"}}>
        <AdminField label="Notes internes">
          <textarea value={form.notes || ""} onChange={e=>set("notes", e.target.value)} rows={2} style={{...inputStyle,resize:"vertical"}}/>
        </AdminField>
      </div>
    </div>
  );
}

function ClientForm({ flash, onCancel, onSaved }){
  const [form, setForm] = _clUseState(CL_EMPTY_CLIENT);
  const [busy, setBusy] = _clUseState(false);
  const set = (k, v) => setForm(p => ({ ...p, [k]: v }));
  const save = async () => {
    if (!form.company.trim()) { flash("Nom de l'établissement requis"); return; }
    setBusy(true);
    try { const { client } = await clAdminApi({ action: "client_create", client: form }); flash("Fiche créée"); onSaved(client); }
    catch (e) { flash(e.message); }
    setBusy(false);
  };
  return (
    <div style={{maxWidth:900}}>
      <button onClick={onCancel} style={{...iconBtn,marginBottom:14}}>← Retour aux clients</button>
      <h2 className="display" style={{fontSize:32,margin:"0 0 14px"}}>Nouveau client</h2>
      <ClientFields form={form} set={set}/>
      <div style={{display:"flex",gap:10,marginTop:18}}>
        <button onClick={save} disabled={busy} className="btn btn-primary">{busy ? "Création…" : "Créer la fiche"}</button>
        <button onClick={onCancel} className="btn btn-ghost">Annuler</button>
      </div>
    </div>
  );
}

function ClientDetail({ client, orders, products, flash, onBack, reload }){
  const [form, setForm] = _clUseState(client);
  const [editing, setEditing] = _clUseState(false);
  const [ordering, setOrdering] = _clUseState(false);
  const [access, setAccess] = _clUseState(null);    // { email, password } affiché une fois
  const [busy, setBusy] = _clUseState(false);
  _clUseEffect(() => { setForm(client); }, [client.id]);
  const set = (k, v) => setForm(p => ({ ...p, [k]: v }));

  const save = async () => {
    if (!String(form.company || "").trim()) { flash("Nom de l'établissement requis"); return; }
    if (form.address_zip && !/^\d{5}$/.test(form.address_zip)) { flash("Code postal invalide"); return; }
    const fields = {};
    for (const k of Object.keys(CL_EMPTY_CLIENT)) fields[k] = typeof form[k] === "string" ? (form[k].trim() || null) : form[k];
    fields.company = fields.company || client.company;
    if (fields.email) fields.email = fields.email.toLowerCase();
    setBusy(true);
    const { error } = await window.sb.from("pro_requests").update(fields).eq("id", client.id);
    setBusy(false);
    if (error) { flash(error.message); return; }
    flash("Fiche enregistrée"); setEditing(false); reload();
  };
  const openAccess = async () => {
    if (!client.email) { flash("Ajoutez d'abord un email à la fiche"); return; }
    if (!confirm(`Ouvrir un accès au site pour ${client.email} ?`)) return;
    setBusy(true);
    try {
      const r = await clAdminApi({ action: "client_access", client_id: client.id });
      setAccess(r); flash(r.existing ? "Compte existant rattaché" : "Accès créé"); reload();
    } catch (e) { flash(e.message); }
    setBusy(false);
  };

  const unpaid = orders.filter(o => o.status === "invoiced");
  const since = new Date(); since.setMonth(since.getMonth() - 12);
  const year = orders.filter(o => CL_REVENUE_STATUSES.includes(o.status) && new Date(o.created_at) >= since).reduce((s, o) => s + Number(o.total || 0), 0);

  if (ordering) {
    return <ManualOrderForm client={client} products={products} flash={flash} onCancel={()=>setOrdering(false)} onSaved={()=>{ setOrdering(false); reload(); }}/>;
  }

  return (
    <div>
      <button onClick={onBack} style={{...iconBtn,marginBottom:14}}>← Retour aux clients</button>
      <div style={{display:"flex",justifyContent:"space-between",gap:16,flexWrap:"wrap",alignItems:"flex-end"}}>
        <div>
          <h2 className="display" style={{fontSize:"clamp(28px,4vw,44px)",margin:0}}>{client.company}</h2>
          <div style={{fontSize:13.5,color:"var(--muted)",marginTop:6}}>
            {[client.full_name, client.phone, client.email].filter(Boolean).join(" · ") || "Aucun contact"}
          </div>
        </div>
        <div style={{display:"flex",gap:8,flexWrap:"wrap"}}>
          {client.phone && <a href={`tel:${client.phone.replace(/\s/g,"")}`} className="btn btn-sm" style={{background:"#1f8a5b",color:"#fff",border:"1px solid #1f8a5b"}}>Appeler</a>}
          <button onClick={()=>setOrdering(true)} className="btn btn-primary btn-sm">+ Nouvelle commande</button>
        </div>
      </div>

      <div style={{display:"grid",gridTemplateColumns:"repeat(auto-fit,minmax(180px,1fr))",gap:12,marginTop:18}}>
        <ClCard label="12 derniers mois" value={clEur(year)} hint={`${orders.length} commande(s) au total`}/>
        <ClCard label="À régler" value={clEur(unpaid.reduce((s, o) => s + Number(o.total || 0), 0))} hint={`${unpaid.length} facture(s)`} tone={unpaid.some(clIsOverdue) ? "warn" : null}/>
        <ClCard label="Conditions" value={client.payment_terms_days ? "30 jours" : "À réception"} hint="Livré par nos soins (camion)"/>
      </div>

      <ClSection title="Fiche" action={!editing && <button onClick={()=>setEditing(true)} style={iconBtn}>Modifier</button>}>
        {editing ? (
          <div>
            <ClientFields form={form} set={set}/>
            <div style={{display:"flex",gap:10,marginTop:14}}>
              <button onClick={save} disabled={busy} className="btn btn-primary btn-sm">Enregistrer</button>
              <button onClick={()=>{ setForm(client); setEditing(false); }} className="btn btn-ghost btn-sm">Annuler</button>
            </div>
          </div>
        ) : (
          <div style={{fontSize:13.5,lineHeight:1.7,padding:"12px 16px",background:"var(--paper-2)",borderRadius:8}}>
            {client.address_line1 ? <>{client.address_line1}{client.address_line2 ? `, ${client.address_line2}` : ""}, {client.address_zip} {client.address_city}<br/></> : <span style={{color:"var(--muted)"}}>Pas d'adresse<br/></span>}
            {client.siret && <>SIRET {client.siret}<br/></>}
            {client.notes && <span style={{color:"var(--muted)"}}>Note : {client.notes}</span>}
          </div>
        )}
      </ClSection>

      <ClSection title="Accès au site">
        {access ? (
          <div style={{padding:"14px 16px",border:"1px solid #caa451",borderRadius:8,fontSize:13.5,lineHeight:1.6}}>
            {access.existing ? <>Le compte <b>{access.email}</b> existait déjà : il est maintenant relié à cette fiche, avec les tarifs pro.</> : <>
              Transmettez ces identifiants au client par téléphone ou SMS. Le mot de passe ne sera plus affiché.<br/>
              Email : <b>{access.email}</b><br/>Mot de passe provisoire : <b style={{fontFamily:"ui-monospace,Menlo,monospace"}}>{access.password}</b>
            </>}
          </div>
        ) : client.user_id ? (
          <div style={{fontSize:13.5}}>Le client a un compte sur le site{client.email ? ` (${client.email})` : ""}. Il voit ses commandes et ses factures dans son espace.</div>
        ) : (
          <div style={{display:"flex",gap:12,alignItems:"center",flexWrap:"wrap",fontSize:13.5}}>
            <span style={{color:"var(--muted)"}}>Pas de compte. Avec un accès, le client commande en ligne aux tarifs pro et retrouve ses factures.</span>
            <button onClick={openAccess} disabled={busy} className="btn btn-ghost btn-sm">Ouvrir un accès au site</button>
          </div>
        )}
      </ClSection>

      <ClSection title={`Commandes · ${orders.length}`}>
        {orders.length === 0 ? <div style={{fontSize:13.5,color:"var(--muted)"}}>Aucune commande pour ce client.</div> : (
          <div style={{display:"grid",gap:8}}>
            {orders.map(o => <ClOrderRow key={o.id} o={o} flash={flash} reload={reload}/>)}
          </div>
        )}
      </ClSection>
    </div>
  );
}

// Une commande dans la fiche client : statut, facture, PDF, encaissement.
function ClOrderRow({ o, flash, reload }){
  const [open, setOpen] = _clUseState(false);
  const [lines, setLines] = _clUseState(null);
  const [busy, setBusy] = _clUseState(false);
  const toggle = async () => {
    setOpen(!open);
    if (!lines) { const { data } = await window.sb.from("order_items").select("*").eq("order_id", o.id); setLines(data || []); }
  };
  const markPaid = async (method) => {
    setBusy(true);
    const { error } = await window.sb.from("orders").update({ status: "paid", paid_at: new Date().toISOString(), payment_method: method || o.payment_method || null }).eq("id", o.id);
    setBusy(false);
    if (error) { flash(error.message); return; }
    flash("Commande marquée payée"); reload();
  };
  const markUnpaid = async () => {
    const { error } = await window.sb.from("orders").update({ status: "invoiced", paid_at: null }).eq("id", o.id);
    if (error) { flash(error.message); return; }
    reload();
  };
  const upload = async (file) => {
    if (!file) return;
    setBusy(true);
    try { await clUploadInvoicePdf(o.id, file); flash("Facture déposée"); reload(); } catch (e) { flash(e.message); }
    setBusy(false);
  };
  const remove = async () => {
    if (!confirm("Supprimer cette commande saisie ? Elle disparaîtra aussi de l'espace du client.")) return;
    if (o.invoice_pdf_path) await window.sb.storage.from("invoices").remove([o.invoice_pdf_path]);
    const { error } = await window.sb.from("orders").delete().eq("id", o.id);
    if (error) { flash(error.message); return; }
    flash("Commande supprimée"); reload();
  };
  const manual = o.source === "manual";
  return (
    <div style={{padding:"12px 16px",background:"var(--paper-2)",borderRadius:8,border:"1px solid " + (clIsOverdue(o) ? "var(--rosso)" : "var(--hairline)")}}>
      <div style={{display:"flex",justifyContent:"space-between",gap:12,flexWrap:"wrap",alignItems:"center"}}>
        <div style={{display:"flex",gap:10,alignItems:"center",flexWrap:"wrap",fontSize:13.5}}>
          <b>{clDate(o.created_at)}</b>
          <span className="chip" style={{fontSize:10}}>{manual ? "Saisie" : "Site"}</span>
          <ClStatus o={o}/>
          {o.invoice_number && <span style={{color:"var(--muted)"}}>Facture {o.invoice_number}</span>}
          {o.status === "invoiced" && o.invoice_due && <span style={{color: clIsOverdue(o) ? "var(--rosso)" : "var(--muted)"}}>échéance {clDate(o.invoice_due)}</span>}
          {o.status === "paid" && o.paid_at && <span style={{color:"var(--muted)"}}>payée le {clDate(o.paid_at)}{o.payment_method ? ` · ${(CL_PAYMENT_METHODS.find(m => m[0] === o.payment_method) || [0, o.payment_method])[1]}` : ""}</span>}
        </div>
        <b style={{fontSize:15}}>{clEur(o.total)}</b>
      </div>
      <div style={{display:"flex",gap:8,marginTop:10,flexWrap:"wrap",alignItems:"center"}}>
        <button onClick={toggle} style={iconBtn}>{open ? "Masquer les articles" : "Voir les articles"}</button>
        {o.invoice_pdf_path && <button onClick={()=>openInvoicePdf(o.invoice_pdf_path)} style={iconBtn}>Facture PDF</button>}
        {o.invoice_url && <a href={o.invoice_url} target="_blank" rel="noopener" style={iconBtn}>Facture Stripe ↗</a>}
        {manual && (
          <label style={{...iconBtn,cursor:"pointer"}}>
            {o.invoice_pdf_path ? "Remplacer le PDF" : "Déposer le PDF"}
            <input type="file" accept="application/pdf" style={{display:"none"}} onChange={e=>upload(e.target.files[0])}/>
          </label>
        )}
        {manual && o.status === "invoiced" && (
          <select disabled={busy} value="" onChange={e=>e.target.value && markPaid(e.target.value)} style={{...iconBtn,cursor:"pointer"}}>
            <option value="">Marquer payée…</option>
            {CL_PAYMENT_METHODS.filter(m => m[0] !== "stripe").map(([id, label]) => <option key={id} value={id}>{label}</option>)}
          </select>
        )}
        {manual && o.status === "paid" && <button onClick={markUnpaid} style={iconBtn}>Remettre à régler</button>}
        {manual && <button onClick={remove} style={{...iconBtn,color:"var(--rosso)",marginLeft:"auto"}}>Supprimer</button>}
      </div>
      {open && (
        <ul style={{margin:"10px 0 0",paddingLeft:18,fontSize:13.5}}>
          {(lines || []).map(li => <li key={li.id}>{li.qty} × {li.product_name} · {clEur(li.unit_price)} HT</li>)}
          {lines && lines.length === 0 && <li style={{color:"var(--muted)"}}>aucune ligne</li>}
          {Number(o.shipping) > 0 && <li>Port · {clEur(o.shipping)}</li>}
          {o.admin_note && <li style={{color:"var(--muted)"}}>Note : {o.admin_note}</li>}
        </ul>
      )}
    </div>
  );
}

// ─── Saisie d'une commande ─────────────────────────────────────────────
function ManualOrderForm({ client, products, flash, onCancel, onSaved }){
  const catalog = (products || []).slice().sort((a, b) => window.pick(a.name).localeCompare(window.pick(b.name), "fr"));
  const defaultHt = (p) => p ? (Number(p.proPrice) > 0 ? Number(p.proPrice) : Math.round(Number(p.price || 0) / (1 + Number(p.vatRate || 0) / 100) * 100) / 100) : 0;
  const [lines, setLines] = _clUseState([{ id: "", qty: 1, unit_ht: "" }]);
  const [form, setForm] = _clUseState(() => {
    const d = clToday();
    return { order_date: d, invoice_number: "", invoice_due: clAddDays(d, client.payment_terms_days || 0), shipping_ttc: "",
      paid: false, payment_method: "virement", note: "" };
  });
  const [file, setFile] = _clUseState(null);
  const [busy, setBusy] = _clUseState(false);
  const set = (k, v) => setForm(p => {
    const next = { ...p, [k]: v };
    if (k === "order_date" && v) next.invoice_due = clAddDays(v, client.payment_terms_days || 0);
    return next;
  });
  const setLine = (i, k, v) => setLines(prev => prev.map((l, j) => {
    if (j !== i) return l;
    const next = { ...l, [k]: v };
    if (k === "id") next.unit_ht = String(defaultHt(catalog.find(p => p.id === v)) || "");
    return next;
  }));

  const P = window.Pricing;
  const computed = lines.filter(l => l.id).map(l => {
    const p = catalog.find(x => x.id === l.id);
    const qty = Math.max(0, Math.round(Number(l.qty) || 0));
    const ht = Number(String(l.unit_ht).replace(",", ".")) || 0;
    return { ht: Math.round(ht * qty * 100) / 100, vat: P.lineVat(ht, qty, p ? p.vatRate : 0) };
  });
  const subtotal = computed.reduce((s, x) => s + x.ht, 0);
  const tax = computed.reduce((s, x) => s + x.vat, 0);
  const shipping = Number(String(form.shipping_ttc).replace(",", ".")) || 0;
  const total = Math.round((subtotal + tax + shipping) * 100) / 100;

  const save = async () => {
    const items = lines.filter(l => l.id).map(l => ({ id: l.id, qty: Math.round(Number(l.qty)), unit_ht: Number(String(l.unit_ht).replace(",", ".")) }));
    if (items.length === 0) { flash("Ajoutez au moins un produit"); return; }
    setBusy(true);
    try {
      const { order } = await clAdminApi({ action: "order_create", client_id: client.id, items,
        shipping_ttc: shipping, order_date: form.order_date, invoice_number: form.invoice_number,
        invoice_due: form.paid ? null : form.invoice_due, paid: form.paid,
        payment_method: form.paid ? form.payment_method : null, note: form.note });
      if (file) {
        try { await clUploadInvoicePdf(order.id, file); }
        catch (e) { flash(`Commande créée, mais le PDF n'a pas été déposé : ${e.message}`); setBusy(false); onSaved(); return; }
      }
      flash("Commande enregistrée"); onSaved();
    } catch (e) { flash(e.message); }
    setBusy(false);
  };

  return (
    <div style={{maxWidth:980}}>
      <button onClick={onCancel} style={{...iconBtn,marginBottom:14}}>← Retour à la fiche</button>
      <h2 className="display" style={{fontSize:32,margin:"0 0 4px"}}>Nouvelle commande</h2>
      <div style={{fontSize:13.5,color:"var(--muted)",marginBottom:18}}>{client.company}</div>

      <ClSection title="Produits (prix HT)">
        <div style={{display:"grid",gap:8}}>
          {lines.map((l, i) => {
            const p = catalog.find(x => x.id === l.id);
            return (
              <div key={i} style={{display:"grid",gridTemplateColumns:"minmax(200px,1fr) 80px 120px 110px auto",gap:8,alignItems:"center"}} className="mo-line">
                <select value={l.id} onChange={e=>setLine(i, "id", e.target.value)} style={inputStyle}>
                  <option value="">Choisir un produit…</option>
                  {catalog.map(p => <option key={p.id} value={p.id}>{window.pick(p.name)}{p.active ? "" : " (retiré)"}</option>)}
                </select>
                <input type="number" min="1" step="1" value={l.qty} onChange={e=>setLine(i, "qty", e.target.value)} style={inputStyle} aria-label="Quantité"/>
                <input inputMode="decimal" value={l.unit_ht} onChange={e=>setLine(i, "unit_ht", e.target.value)} placeholder="Prix HT" style={inputStyle} aria-label="Prix unitaire HT"/>
                <span style={{fontSize:12.5,color:"var(--muted)"}}>{p ? `TVA ${String(p.vatRate).replace(".", ",")} %` : ""}</span>
                <button onClick={()=>setLines(prev => prev.length > 1 ? prev.filter((_, j) => j !== i) : [{ id: "", qty: 1, unit_ht: "" }])} style={iconBtn} aria-label="Retirer">×</button>
              </div>
            );
          })}
          <button onClick={()=>setLines(prev => [...prev, { id: "", qty: 1, unit_ht: "" }])} style={{...iconBtn,justifySelf:"start"}}>+ Ajouter un produit</button>
        </div>
      </ClSection>

      <ClSection title="Facture et paiement">
        <div style={{display:"grid",gridTemplateColumns:"repeat(auto-fit,minmax(200px,1fr))",gap:"4px 18px"}}>
          <AdminField label="Date de la commande"><input type="date" value={form.order_date} onChange={e=>set("order_date", e.target.value)} style={inputStyle}/></AdminField>
          <AdminField label="N° de facture"><input value={form.invoice_number} onChange={e=>set("invoice_number", e.target.value)} placeholder="ex. F-2026-042" style={inputStyle}/></AdminField>
          <AdminField label="Frais de port TTC"><input inputMode="decimal" value={form.shipping_ttc} onChange={e=>set("shipping_ttc", e.target.value)} placeholder="0" style={inputStyle}/></AdminField>
          <AdminField label="Paiement">
            <select value={form.paid ? "paid" : "due"} onChange={e=>set("paid", e.target.value === "paid")} style={inputStyle}>
              <option value="due">À régler</option><option value="paid">Déjà payée</option>
            </select>
          </AdminField>
          {form.paid ? (
            <AdminField label="Moyen de paiement">
              <select value={form.payment_method} onChange={e=>set("payment_method", e.target.value)} style={inputStyle}>
                {CL_PAYMENT_METHODS.filter(m => m[0] !== "stripe").map(([id, label]) => <option key={id} value={id}>{label}</option>)}
              </select>
            </AdminField>
          ) : (
            <AdminField label="Échéance"><input type="date" value={form.invoice_due} onChange={e=>set("invoice_due", e.target.value)} style={inputStyle}/></AdminField>
          )}
          <AdminField label="Facture PDF">
            <input type="file" accept="application/pdf" onChange={e=>setFile(e.target.files[0] || null)} style={{fontSize:13,padding:"8px 0"}}/>
          </AdminField>
          <div style={{gridColumn:"1 / -1"}}>
            <AdminField label="Note interne"><input value={form.note} onChange={e=>set("note", e.target.value)} style={inputStyle}/></AdminField>
          </div>
        </div>
      </ClSection>

      <div style={{marginTop:22,padding:"16px 18px",background:"var(--paper-2)",borderRadius:8,display:"flex",gap:24,flexWrap:"wrap",alignItems:"center",justifyContent:"space-between"}}>
        <div style={{fontSize:13.5,lineHeight:1.7}}>
          Sous-total HT <b>{clEur(subtotal)}</b> · TVA <b>{clEur(tax)}</b>{shipping ? <> · Port <b>{clEur(shipping)}</b></> : null}<br/>
          <span style={{fontSize:18}}>Total TTC <b>{clEur(total)}</b></span>
        </div>
        <div style={{display:"flex",gap:10}}>
          <button onClick={onCancel} className="btn btn-ghost">Annuler</button>
          <button onClick={save} disabled={busy} className="btn btn-primary">{busy ? "Enregistrement…" : "Enregistrer la commande"}</button>
        </div>
      </div>
      <p style={{fontSize:12.5,color:"var(--muted)",marginTop:10}}>Vérifiez que le total correspond à votre facture. Le client la retrouvera dans son espace s'il a un accès au site.</p>
      <style>{`@media (max-width:720px){ .mo-line{grid-template-columns:minmax(0,1fr) 56px 84px 36px !important} .mo-line > select{min-width:0} .mo-line > span{display:none} }`}</style>
    </div>
  );
}

Object.assign(window, { DashboardPanel, ClientsPanel, openInvoicePdf });
