// Caffè Italia · tunnel de commande (particuliers)
// =================================================
// Compte (obligatoire) → adresse (gardée dans le compte) → livraison
// (Colissimo, point Mondial Relay autour de l'adresse, retrait chez Napoli
// Caffè) → récapitulatif et paiement Stripe. Stripe ne fait plus que
// l'encaissement : l'adresse et le point relais voyagent dans la session
// (api/checkout.mjs). Les pros passent par la commande sur validation du
// panier, jamais par ici.

const { useState: _coUseState, useEffect: _coUseEffect } = React;

const CO_STEPS = [["account", "Compte", "Account"], ["address", "Adresse", "Indirizzo"], ["delivery", "Livraison", "Consegna"], ["review", "Paiement", "Pagamento"]];
const coEur = (n) => `${Number(n).toFixed(2).replace(".", ",")} €`;

function CoSteps({ current, done, onGo }){
  const isIt = window.__LANG__ === "it";
  const idx = CO_STEPS.findIndex(s => s[0] === current);
  return (
    <ol style={{display:"flex",gap:6,listStyle:"none",padding:0,margin:"18px 0 28px",flexWrap:"wrap"}}>
      {CO_STEPS.map(([id, fr, it], i) => {
        const reachable = i < idx && done.includes(id);
        return (
          <li key={id}>
            <button disabled={!reachable} onClick={()=>reachable && onGo(id)} style={{
              display:"flex",alignItems:"center",gap:8,padding:"8px 14px",borderRadius:99,fontSize:12.5,fontWeight:600,
              background: i === idx ? "var(--ink)" : "transparent", color: i === idx ? "var(--paper)" : (i < idx ? "var(--ink)" : "var(--muted)"),
              border:"1px solid " + (i === idx ? "var(--ink)" : "var(--hairline-strong)"), cursor: reachable ? "pointer" : "default",
            }}>
              <span style={{fontFamily:"var(--font-display)",color: i === idx ? "var(--paper)" : "var(--rosso)"}}>{String(i + 1).padStart(2, "0")}</span>
              {isIt ? it : fr}
            </button>
          </li>
        );
      })}
    </ol>
  );
}

// ─── Étape 2 · adresse, préremplie depuis le compte ───────────────────────
function CoAddress({ session, value, onDone }){
  const isIt = window.__LANG__ === "it";
  const [form, setForm] = _coUseState(value);
  const [loading, setLoading] = _coUseState(!value);
  const [busy, setBusy] = _coUseState(false);
  const [err, setErr] = _coUseState(null);
  _coUseEffect(() => {
    if (value) return;
    (async () => {
      const { data } = await window.sb.from("profiles").select("*").eq("id", session.user.id).maybeSingle();
      setForm({
        name: data?.full_name || session.user.user_metadata?.full_name || "", phone: data?.phone || "",
        line1: data?.address_line || "", line2: data?.address_line2 || "", zip: data?.address_zip || "", city: data?.address_city || "",
      });
      setLoading(false);
    })();
  }, []);
  if (loading || !form) return <div style={{color:"var(--muted)"}}>{isIt ? "Caricamento…" : "Chargement…"}</div>;
  const set = (k, v) => setForm(p => ({ ...p, [k]: v }));

  const submit = async (e) => {
    e.preventDefault(); setErr(null);
    const f = Object.fromEntries(Object.entries(form).map(([k, v]) => [k, String(v || "").trim()]));
    if (!f.name || !f.line1 || !f.city) { setErr(isIt ? "Completa nome, indirizzo e città." : "Indiquez votre nom, votre adresse et votre ville."); return; }
    if ((f.phone.match(/\d/g) || []).length < 9) { setErr(isIt ? "Numero di telefono non valido." : "Numéro de téléphone invalide."); return; }
    if (!/^\d{5}$/.test(f.zip)) { setErr(isIt ? "CAP non valido." : "Code postal invalide."); return; }
    if (window.Shipping.isOutOfZone({ country: "FR", postal_code: f.zip })) {
      setErr(isIt ? "Consegniamo solo in Francia continentale (Corsica esclusa)." : "Nous livrons en France continentale uniquement, hors Corse."); return;
    }
    setBusy(true);
    const { error } = await window.sb.from("profiles").upsert({
      id: session.user.id, full_name: f.name, phone: f.phone, address_line: f.line1, address_line2: f.line2 || null,
      address_zip: f.zip, address_city: f.city, address_country: "France", updated_at: new Date().toISOString(),
    }, { onConflict: "id" });
    setBusy(false);
    if (error) { setErr(error.message); return; }
    onDone(f);
  };

  return (
    <form onSubmit={submit} style={{maxWidth:560}}>
      <AcField label={isIt ? "Nome e cognome" : "Nom et prénom"}><input value={form.name} onChange={e=>set("name", e.target.value)} autoComplete="name" required style={acInput}/></AcField>
      <AcField label={isIt ? "Telefono" : "Téléphone"} hint={isIt ? "Per il corriere e per avvisarti" : "Pour le transporteur et pour vous prévenir"}>
        <input type="tel" value={form.phone} onChange={e=>set("phone", e.target.value)} autoComplete="tel" required style={acInput}/>
      </AcField>
      <AcField label={isIt ? "Indirizzo" : "Adresse"}><input value={form.line1} onChange={e=>set("line1", e.target.value)} autoComplete="address-line1" required style={acInput}/></AcField>
      <AcField label={isIt ? "Complemento (facoltativo)" : "Complément (facultatif)"}><input value={form.line2} onChange={e=>set("line2", e.target.value)} autoComplete="address-line2" placeholder={isIt ? "Scala, interno, citofono…" : "Bâtiment, étage, digicode…"} style={acInput}/></AcField>
      <div style={{display:"grid",gridTemplateColumns:"140px 1fr",gap:14}} className="ac-zip-city">
        <AcField label={isIt ? "CAP" : "Code postal"}><input inputMode="numeric" maxLength={5} value={form.zip} onChange={e=>set("zip", e.target.value)} autoComplete="postal-code" required style={acInput}/></AcField>
        <AcField label={isIt ? "Città" : "Ville"}><input value={form.city} onChange={e=>set("city", e.target.value)} autoComplete="address-level2" required style={acInput}/></AcField>
      </div>
      <p style={{fontSize:12.5,color:"var(--muted)",margin:"0 0 14px"}}>{isIt ? "Francia continentale. L'indirizzo viene salvato nel tuo account." : "France continentale. L'adresse est enregistrée dans votre compte pour la prochaine fois."}</p>
      {err && <CoError msg={err}/>}
      <button type="submit" disabled={busy} className="btn btn-primary btn-lg">{busy ? "…" : (isIt ? "Continua" : "Continuer")} <IconArrow size={18}/></button>
    </form>
  );
}

function CoError({ msg }){
  return <div style={{padding:"10px 12px",margin:"0 0 14px",background:"rgba(220,40,50,.1)",border:"1px solid var(--rosso)",borderRadius:6,color:"var(--rosso)",fontSize:13}}>{msg}</div>;
}

// ─── Écran ─────────────────────────────────────────────────────────────
function CheckoutScreen({ items, pro, navigate, onEditCart }){
  const isIt = window.__LANG__ === "it";
  const session = useSession();
  const [step, setStep] = _coUseState("address");
  const [done, setDone] = _coUseState(["account"]);
  const [address, setAddress] = _coUseState(null);
  const [delivery, setDelivery] = _coUseState({ mode: "courier", relay: null });
  const [authMode, setAuthMode] = _coUseState("login");
  const [paying, setPaying] = _coUseState(false);
  const [err, setErr] = _coUseState(null);
  // Retour arrière depuis Stripe : le bouton ne doit pas rester figé.
  _coUseEffect(() => {
    const onShow = (e) => { if (e.persisted) setPaying(false); };
    window.addEventListener("pageshow", onShow);
    return () => window.removeEventListener("pageshow", onShow);
  }, []);

  const wrap = (children) => (
    <main className="wrap" style={{padding:"40px 32px 80px",maxWidth:980}}>
      <div className="eyebrow" style={{color:"var(--rosso)"}}>{isIt ? "Ordine" : "Commande"}</div>
      <h1 className="display" style={{fontSize:"clamp(40px,7vw,88px)",margin:"8px 0 0",lineHeight:.9}}>{isIt ? "Il tuo ordine" : "Votre commande"}</h1>
      {children}
    </main>
  );

  if (session === undefined) return wrap(<div style={{marginTop:24,color:"var(--muted)"}}>{isIt ? "Caricamento…" : "Chargement…"}</div>);
  if (pro && pro.isPro) return wrap(
    <div style={{marginTop:24}}>
      <p>{isIt ? "Gli ordini professionali si inviano dal carrello : Francesco li conferma per telefono." : "Les commandes pro s'envoient depuis le panier : Francesco les confirme par téléphone."}</p>
      <button onClick={onEditCart} className="btn btn-primary" style={{marginTop:12}}>{isIt ? "Apri il carrello" : "Ouvrir le panier"}</button>
    </div>
  );
  if (!items || items.length === 0) return wrap(
    <div style={{marginTop:24}}>
      <p>{isIt ? "Il carrello è vuoto." : "Votre panier est vide."}</p>
      <button onClick={()=>navigate({ page: "all" })} className="btn btn-primary" style={{marginTop:12}}>{isIt ? "Vai alla bottega" : "Découvrir la boutique"}</button>
    </div>
  );

  const current = !session ? "account" : step;
  const cfg = window.SHIPPING || { grid: [], relayGrid: [], threshold: 50 };
  const subtotal = items.reduce((s, i) => s + i.price * i.qty, 0);
  const quote = window.Shipping.quoteShipping({ items, grid: cfg.grid, relayGrid: cfg.relayGrid, threshold: cfg.threshold, subtotal, handDelivery: false }) || [];
  const chosen = quote.find(o => o.mode === delivery.mode) || quote[0];
  const total = subtotal + (chosen ? chosen.amount : 0);
  const go = (id) => setStep(id);
  const finish = (id, next) => { setDone(d => d.includes(id) ? d : [...d, id]); setStep(next); window.scrollTo({ top: 0 }); };

  const pay = async () => {
    setErr(null); setPaying(true);
    try {
      const sess = (await window.sb.auth.getSession()).data.session;
      const r = await fetch("/api/checkout", {
        method: "POST",
        headers: { "Content-Type": "application/json", ...(sess?.access_token ? { Authorization: `Bearer ${sess.access_token}` } : {}) },
        body: JSON.stringify({
          items: items.map(i => ({ id: i.id, qty: i.qty })), lang: window.__LANG__ || "fr", address,
          delivery: { mode: chosen.mode, relay: chosen.mode === "relay" ? delivery.relay : null },
        }),
      });
      const data = await r.json();
      if (!r.ok || !data.url) throw new Error(data.error || "Erreur inconnue");
      window.location.href = data.url;
    } catch (e) { setErr(e.message); setPaying(false); }
  };

  const summary = (
    <aside style={{padding:20,background:"var(--paper-2)",borderRadius:8,border:"1px solid var(--hairline)",alignSelf:"start"}}>
      <div className="eyebrow" style={{fontSize:10.5}}>{isIt ? "Riepilogo" : "Récapitulatif"}</div>
      <ul style={{listStyle:"none",padding:0,margin:"10px 0"}}>
        {items.map(i => (
          <li key={i.id} style={{display:"flex",justifyContent:"space-between",gap:10,fontSize:13.5,padding:"5px 0"}}>
            <span>{i.qty} × {pick(i.name)}</span><span style={{whiteSpace:"nowrap"}}>{coEur(i.price * i.qty)}</span>
          </li>
        ))}
      </ul>
      <div style={{borderTop:"1px solid var(--hairline)",paddingTop:8,fontSize:13.5,display:"grid",gap:4}}>
        <div style={{display:"flex",justifyContent:"space-between"}}><span>{isIt ? "Subtotale" : "Sous-total"}</span><span>{coEur(subtotal)}</span></div>
        <div style={{display:"flex",justifyContent:"space-between"}}><span>{isIt ? "Consegna" : "Livraison"}</span>
          <span>{current === "account" || current === "address" ? (isIt ? "al passo 3" : "à l'étape 3") : (chosen.amount === 0 ? t("cart.delivery_free") : coEur(chosen.amount))}</span></div>
        <div style={{display:"flex",justifyContent:"space-between",fontWeight:700,fontSize:16,marginTop:6}}><span>Total</span>
          <span>{coEur(current === "account" || current === "address" ? subtotal : total)}</span></div>
      </div>
      <button onClick={onEditCart} style={{marginTop:12,fontSize:12.5,textDecoration:"underline",color:"var(--muted)"}}>{isIt ? "Modifica il carrello" : "Modifier le panier"}</button>
    </aside>
  );

  let body;
  if (current === "account") {
    body = (
      <div style={{maxWidth:480}}>
        <p style={{fontSize:14,color:"var(--muted)",marginTop:0}}>{isIt ? "Accedi o crea un account per ordinare. Il carrello resta com'è." : "Connectez-vous ou créez un compte pour commander. Votre panier est conservé."}</p>
        {authMode === "login" ? <LoginForm onSwitch={()=>setAuthMode("signup")}/> : <SignupForm onSwitch={()=>setAuthMode("login")}/>}
      </div>
    );
  } else if (current === "address") {
    body = <CoAddress session={session} value={address} onDone={(a)=>{ setAddress(a); finish("address", "delivery"); }}/>;
  } else if (current === "delivery") {
    body = (
      <div style={{maxWidth:560}}>
        <DeliveryPicker quote={quote} value={{ mode: chosen.mode, relay: delivery.relay }} onChange={setDelivery} brand={cfg.relayBrand} postCode={address?.zip}/>
        {chosen.mode === "courier" && <p style={{fontSize:13,color:"var(--muted)"}}>{isIt ? "Consegna a" : "Livré à"} : {address.name}, {address.line1}{address.line2 ? `, ${address.line2}` : ""}, {address.zip} {address.city}</p>}
        {err && <CoError msg={err}/>}
        <button onClick={()=>{
          if (chosen.mode === "relay" && !delivery.relay) { setErr(isIt ? "Scegli un punto di ritiro." : "Choisissez un point relais."); return; }
          setErr(null); finish("delivery", "review");
        }} className="btn btn-primary btn-lg" style={{marginTop:8}}>{isIt ? "Continua" : "Continuer"} <IconArrow size={18}/></button>
      </div>
    );
  } else {
    const where = chosen.mode === "relay" ? `${delivery.relay.name}, ${delivery.relay.line1}, ${delivery.relay.zip} ${delivery.relay.city}`
      : chosen.mode === "pickup" ? `${window.Shipping.PICKUP.name}, ${window.Shipping.PICKUP.line1}, ${window.Shipping.PICKUP.zip} ${window.Shipping.PICKUP.city}`
      : `${address.line1}${address.line2 ? `, ${address.line2}` : ""}, ${address.zip} ${address.city}`;
    const delay = { courier: isIt ? "2-4 giorni lavorativi" : "2 à 4 jours ouvrés", relay: isIt ? "3-5 giorni lavorativi" : "3 à 5 jours ouvrés",
      pickup: isIt ? "pronto entro 24 h lavorative, ti chiamiamo" : "prête sous 24 h ouvrées, Francesco vous appelle" }[chosen.mode];
    body = (
      <div style={{maxWidth:560,display:"grid",gap:14}}>
        <div style={{padding:16,border:"1px solid var(--hairline)",borderRadius:8,fontSize:14,lineHeight:1.6}}>
          <div className="eyebrow" style={{fontSize:10.5}}>{isIt ? "Consegna" : "Livraison"}</div>
          <b>{pick(chosen.label)}</b><br/>{address.name} · {address.phone}<br/>{where}<br/>
          <span style={{color:"var(--muted)"}}>{delay}</span>
          <div><button onClick={()=>go("delivery")} style={{fontSize:12.5,textDecoration:"underline",marginTop:6}}>{isIt ? "Modifica" : "Modifier"}</button></div>
        </div>
        <p style={{fontSize:12.5,color:"var(--muted)",margin:0}}>
          {isIt ? <>Cliccando su « Paga il mio ordine » accetti le <a onClick={()=>navigate({ page: "page", slug: "cgv" })} style={{textDecoration:"underline",cursor:"pointer"}}>condizioni generali di vendita</a> e ti impegni a pagare {coEur(total)}.</>
                : <>En cliquant sur « Payer ma commande », vous acceptez les <a onClick={()=>navigate({ page: "page", slug: "cgv" })} style={{textDecoration:"underline",cursor:"pointer"}}>conditions générales de vente</a> et vous vous engagez à payer {coEur(total)}.</>}
        </p>
        {err && <CoError msg={err}/>}
        <button onClick={pay} disabled={paying} className="btn btn-rosso btn-lg" style={{opacity:paying?.6:1}}>
          {paying ? (isIt ? "Reindirizzamento…" : "Redirection…") : <>{isIt ? "Paga il mio ordine" : "Payer ma commande"} · {coEur(total)} <IconArrow size={18}/></>}
        </button>
        <div style={{fontSize:11.5,color:"var(--muted)"}}>{t("cart.pay_note")}</div>
      </div>
    );
  }

  return wrap(
    <>
      <CoSteps current={current} done={done} onGo={go}/>
      <div style={{display:"grid",gridTemplateColumns:"minmax(0,1fr) 320px",gap:40}} className="co-grid">
        <div>{body}</div>
        {summary}
      </div>
      <style>{`@media (max-width:860px){ .co-grid{grid-template-columns:1fr !important} .co-grid > aside{order:-1} }`}</style>
    </>
  );
}

Object.assign(window, { CheckoutScreen });
