// ---- SÉRÈNE — pages : Panier, Checkout, Confirmation ------------------

const SHIPPING_THRESHOLD = 120;
const shippingCost = (sub) => (sub >= SHIPPING_THRESHOLD || sub === 0 ? 0 : 7.5);

/* =================== CART =================== */
function CartPage({ cart, setQty, removeItem, go }) {
  const sub = cart.reduce((s, i) => s + i.price * i.qty, 0);
  const ship = shippingCost(sub);
  const remain = Math.max(0, SHIPPING_THRESHOLD - sub);

  if (cart.length === 0) {
    return (
      <div className="page-fade container" style={{ padding: "90px 36px", textAlign: "center", minHeight: "50vh" }}>
        <div style={{ color: "var(--ink-faint)", display: "flex", justifyContent: "center", marginBottom: 24 }}><IconBag size={42} sw={1} /></div>
        <h1 style={{ fontSize: 40 }}>Votre panier est vide</h1>
        <p style={{ marginTop: 14, color: "var(--ink-soft)" }}>Quelques belles pièces vous attendent.</p>
        <div style={{ marginTop: 30 }}><button className="btn" onClick={() => go("category", { cat: "all" })}>Explorer la boutique</button></div>
      </div>
    );
  }

  return (
    <div className="page-fade container" style={{ padding: "44px 36px 90px" }}>
      <h1 style={{ fontSize: "clamp(34px, 5vw, 56px)", marginBottom: 8 }}>Votre panier</h1>
      <p style={{ color: "var(--ink-faint)", marginBottom: 40 }}>{cart.reduce((s, i) => s + i.qty, 0)} article{cart.reduce((s, i) => s + i.qty, 0) > 1 ? "s" : ""}</p>

      <div style={{ display: "grid", gridTemplateColumns: "1fr 360px", gap: 56, alignItems: "start" }} className="cart-grid">
        {/* Lines */}
        <div>
          {remain > 0 && (
            <div style={{ background: "var(--cream-deep)", borderRadius: "var(--radius-lg)", padding: "16px 20px", marginBottom: 28, fontSize: 13.5, color: "var(--ink-soft)", display: "flex", alignItems: "center", gap: 10 }}>
              <IconTruck size={18} sw={1.3} /> Plus que <strong style={{ fontWeight: 500, color: "var(--ink)" }}>{fmt(remain)}</strong> pour la livraison offerte.
            </div>
          )}
          {cart.map((i) => (
            <div key={i.key} style={{ display: "grid", gridTemplateColumns: "96px 1fr auto", gap: 20, padding: "24px 0", borderBottom: "1px solid var(--line-soft)" }}>
              <Ph label="" tone={i.tone} ratio="4 / 5" style={{ borderRadius: "var(--radius)" }} />
              <div>
                <div style={{ display: "flex", justifyContent: "space-between", gap: 12 }}>
                  <h3 style={{ fontSize: 21 }}>{i.name}</h3>
                </div>
                <p style={{ fontSize: 13, color: "var(--ink-faint)", margin: "5px 0 0" }}>{i.catName}{i.color ? " · " + i.color : ""}</p>
                <div style={{ marginTop: 18, display: "flex", alignItems: "center", gap: 18 }}>
                  <Stepper value={i.qty} onChange={(q) => setQty(i.key, q)} small />
                  <button onClick={() => removeItem(i.key)} style={{ background: "none", border: "none", color: "var(--ink-faint)", fontSize: 12.5, letterSpacing: "0.06em", cursor: "pointer", borderBottom: "1px solid var(--line)", padding: "0 0 2px" }}>Retirer</button>
                </div>
              </div>
              <div style={{ textAlign: "right", fontSize: 16, fontVariantNumeric: "tabular-nums" }}>{fmt(i.price * i.qty)}</div>
            </div>
          ))}
          <button onClick={() => go("category", { cat: "all" })} className="link-underline" style={{ background: "none", border: "none", borderBottom: "1px solid var(--ink)", marginTop: 30, display: "inline-flex", alignItems: "center", gap: 8 }}>
            Continuer mes achats
          </button>
        </div>

        {/* Summary */}
        <aside style={{ position: "sticky", top: 96, background: "var(--cream-deep)", borderRadius: "var(--radius-lg)", padding: 30 }}>
          <h3 style={{ fontSize: 24, marginBottom: 24 }}>Récapitulatif</h3>
          <SummaryRows sub={sub} ship={ship} />
          <button className="btn btn--block" style={{ marginTop: 26 }} onClick={() => go("checkout")}>Passer commande</button>
          <p style={{ fontSize: 11.5, color: "var(--ink-faint)", marginTop: 16, textAlign: "center", letterSpacing: "0.03em" }}>Paiement sécurisé · TVA incluse</p>
        </aside>
      </div>
    </div>
  );
}

const SummaryRows = ({ sub, ship }) => (
  <div style={{ display: "flex", flexDirection: "column", gap: 13 }}>
    <Row label="Sous-total" value={fmt(sub)} />
    <Row label="Livraison" value={ship === 0 ? "Offerte" : fmt(ship)} muted={ship === 0} />
    <div style={{ borderTop: "1px solid var(--line)", margin: "8px 0" }} />
    <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline" }}>
      <span style={{ fontSize: 16 }}>Total</span>
      <span style={{ fontSize: 22, fontFamily: "var(--font-display)", fontVariantNumeric: "tabular-nums" }}>{fmt(sub + ship)}</span>
    </div>
  </div>
);
const Row = ({ label, value, muted }) => (
  <div style={{ display: "flex", justifyContent: "space-between", fontSize: 14.5 }}>
    <span style={{ color: "var(--ink-soft)" }}>{label}</span>
    <span style={{ fontVariantNumeric: "tabular-nums", color: muted ? "var(--sage-deep)" : "var(--ink)" }}>{value}</span>
  </div>
);

/* =================== CHECKOUT =================== */
function CheckoutPage({ cart, go, placeOrder }) {
  const sub = cart.reduce((s, i) => s + i.price * i.qty, 0);
  const ship = shippingCost(sub);
  const [step, setStep] = useState(1);
  const [form, setForm] = useState({
    email: "", first: "", last: "", address: "", zip: "", city: "",
    delivery: "standard", card: "", exp: "", cvc: "", name: "",
  });
  const [errors, setErrors] = useState({});

  const set = (k) => (e) => setForm({ ...form, [k]: e.target.value });

  const deliveryFee = form.delivery === "express" ? 14 : ship;
  const total = sub + deliveryFee;

  if (cart.length === 0) {
    return (
      <div className="page-fade container" style={{ padding: "90px 36px", textAlign: "center" }}>
        <h1 style={{ fontSize: 36 }}>Aucun article à régler</h1>
        <div style={{ marginTop: 26 }}><button className="btn" onClick={() => go("category", { cat: "all" })}>Retour à la boutique</button></div>
      </div>
    );
  }

  const validateStep1 = () => {
    const e = {};
    if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(form.email)) e.email = "Email invalide";
    if (!form.first.trim()) e.first = "Requis";
    if (!form.last.trim()) e.last = "Requis";
    if (!form.address.trim()) e.address = "Requis";
    if (!/^\d{5}$/.test(form.zip)) e.zip = "5 chiffres";
    if (!form.city.trim()) e.city = "Requis";
    setErrors(e);
    return Object.keys(e).length === 0;
  };
  const validateStep2 = () => {
    const e = {};
    if (form.card.replace(/\s/g, "").length < 16) e.card = "16 chiffres";
    if (!/^\d{2}\/\d{2}$/.test(form.exp)) e.exp = "MM/AA";
    if (!/^\d{3}$/.test(form.cvc)) e.cvc = "3 chiffres";
    if (!form.name.trim()) e.name = "Requis";
    setErrors(e);
    return Object.keys(e).length === 0;
  };

  return (
    <div className="page-fade container" style={{ padding: "30px 36px 90px" }}>
      <button onClick={() => go("cart")} className="link-underline" style={{ background: "none", border: "none", borderBottom: "1px solid var(--ink)", marginBottom: 30 }}>← Retour au panier</button>

      <div style={{ display: "grid", gridTemplateColumns: "1fr 380px", gap: 64, alignItems: "start" }} className="cart-grid">
        <div>
          {/* Steps indicator */}
          <div style={{ display: "flex", gap: 28, marginBottom: 40, borderBottom: "1px solid var(--line-soft)", paddingBottom: 20 }}>
            {["Livraison", "Paiement"].map((s, i) => (
              <div key={i} style={{ display: "flex", alignItems: "center", gap: 10, opacity: step >= i + 1 ? 1 : 0.4 }}>
                <span style={{ width: 26, height: 26, borderRadius: "50%", border: "1px solid var(--ink)", display: "flex", alignItems: "center", justifyContent: "center", fontSize: 12, background: step > i + 1 ? "var(--ink)" : "transparent", color: step > i + 1 ? "var(--cream)" : "var(--ink)" }}>
                  {step > i + 1 ? <IconCheck size={13} /> : i + 1}
                </span>
                <span style={{ fontSize: 13, letterSpacing: "0.1em", textTransform: "uppercase" }}>{s}</span>
              </div>
            ))}
          </div>

          {step === 1 && (
            <div>
              <h2 style={{ fontSize: 28, marginBottom: 22 }}>Coordonnées</h2>
              <Field label="Email" err={errors.email}><input value={form.email} onChange={set("email")} placeholder="votre@email.fr" style={inp} /></Field>
              <div style={twoCol}>
                <Field label="Prénom" err={errors.first}><input value={form.first} onChange={set("first")} style={inp} /></Field>
                <Field label="Nom" err={errors.last}><input value={form.last} onChange={set("last")} style={inp} /></Field>
              </div>
              <h2 style={{ fontSize: 28, margin: "34px 0 22px" }}>Adresse de livraison</h2>
              <Field label="Adresse" err={errors.address}><input value={form.address} onChange={set("address")} placeholder="12 rue des Lilas" style={inp} /></Field>
              <div style={{ display: "grid", gridTemplateColumns: "140px 1fr", gap: 16 }}>
                <Field label="Code postal" err={errors.zip}><input value={form.zip} onChange={set("zip")} maxLength={5} style={inp} /></Field>
                <Field label="Ville" err={errors.city}><input value={form.city} onChange={set("city")} style={inp} /></Field>
              </div>

              <h2 style={{ fontSize: 28, margin: "34px 0 18px" }}>Mode de livraison</h2>
              <DeliveryOption active={form.delivery === "standard"} onClick={() => setForm({ ...form, delivery: "standard" })}
                title="Standard · 2–4 jours" price={ship === 0 ? "Offerte" : fmt(ship)} note="Colissimo suivi, emballage zéro plastique" />
              <DeliveryOption active={form.delivery === "express"} onClick={() => setForm({ ...form, delivery: "express" })}
                title="Express · 24 h" price={fmt(14)} note="Chronopost, livraison le lendemain" />

              <button className="btn btn--block" style={{ marginTop: 30 }} onClick={() => { if (validateStep1()) { setStep(2); window.scrollTo(0, 0); } }}>Continuer vers le paiement</button>
            </div>
          )}

          {step === 2 && (
            <div>
              <h2 style={{ fontSize: 28, marginBottom: 8 }}>Paiement</h2>
              <p style={{ fontSize: 13.5, color: "var(--ink-faint)", marginBottom: 24, display: "flex", alignItems: "center", gap: 8 }}>
                <IconCheck size={15} /> Connexion chiffrée — démonstration, aucun débit réel.
              </p>
              <Field label="Numéro de carte" err={errors.card}>
                <input value={form.card} onChange={(e) => setForm({ ...form, card: formatCard(e.target.value) })} placeholder="4242 4242 4242 4242" maxLength={19} style={inp} inputMode="numeric" />
              </Field>
              <div style={twoCol}>
                <Field label="Expiration" err={errors.exp}><input value={form.exp} onChange={(e) => setForm({ ...form, exp: formatExp(e.target.value) })} placeholder="MM/AA" maxLength={5} style={inp} inputMode="numeric" /></Field>
                <Field label="CVC" err={errors.cvc}><input value={form.cvc} onChange={(e) => setForm({ ...form, cvc: e.target.value.replace(/\D/g, "").slice(0, 3) })} placeholder="123" maxLength={3} style={inp} inputMode="numeric" /></Field>
              </div>
              <Field label="Nom sur la carte" err={errors.name}><input value={form.name} onChange={set("name")} style={inp} /></Field>

              <div style={{ display: "flex", gap: 14, marginTop: 30 }}>
                <button className="btn btn--ghost" onClick={() => setStep(1)} style={{ flex: "0 0 auto" }}>Retour</button>
                <button className="btn" style={{ flex: 1 }} onClick={() => { if (validateStep2()) placeOrder({ ...form, total, deliveryFee }); }}>Payer {fmt(total)}</button>
              </div>
            </div>
          )}
        </div>

        {/* Order summary */}
        <aside style={{ position: "sticky", top: 96, background: "var(--cream-deep)", borderRadius: "var(--radius-lg)", padding: 30 }}>
          <h3 style={{ fontSize: 22, marginBottom: 20 }}>Votre commande</h3>
          <div style={{ display: "flex", flexDirection: "column", gap: 16, marginBottom: 22, maxHeight: 280, overflowY: "auto" }}>
            {cart.map((i) => (
              <div key={i.key} style={{ display: "flex", gap: 13, alignItems: "center" }}>
                <div style={{ position: "relative", flexShrink: 0 }}>
                  <Ph label="" tone={i.tone} ratio="1 / 1" style={{ width: 52, borderRadius: "var(--radius)" }} />
                  <span style={{ position: "absolute", top: -7, right: -7, background: "var(--ink)", color: "var(--cream)", fontSize: 10.5, width: 19, height: 19, borderRadius: "50%", display: "flex", alignItems: "center", justifyContent: "center" }}>{i.qty}</span>
                </div>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 14, fontFamily: "var(--font-display)" }}>{i.name}</div>
                  <div style={{ fontSize: 12, color: "var(--ink-faint)" }}>{i.color || i.catName}</div>
                </div>
                <span style={{ fontSize: 13.5, fontVariantNumeric: "tabular-nums" }}>{fmt(i.price * i.qty)}</span>
              </div>
            ))}
          </div>
          <div style={{ borderTop: "1px solid var(--line)", paddingTop: 18 }}>
            <SummaryRows sub={sub} ship={deliveryFee} />
          </div>
        </aside>
      </div>
    </div>
  );
}

const inp = {
  width: "100%", padding: "13px 15px", border: "1px solid var(--line)", borderRadius: "var(--radius)",
  fontFamily: "var(--font-ui)", fontSize: 14.5, color: "var(--ink)", background: "var(--paper)", fontWeight: 300,
};
const twoCol = { display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16 };

const Field = ({ label, err, children }) => (
  <label style={{ display: "block", marginBottom: 16 }}>
    <span style={{ display: "flex", justifyContent: "space-between", fontSize: 12, letterSpacing: "0.06em", color: "var(--ink-soft)", marginBottom: 7 }}>
      {label} {err && <span style={{ color: "var(--blush-deep)", letterSpacing: 0 }}>{err}</span>}
    </span>
    {children}
  </label>
);

const DeliveryOption = ({ active, onClick, title, price, note }) => (
  <button onClick={onClick} style={{
    width: "100%", textAlign: "left", display: "flex", alignItems: "center", gap: 14,
    padding: "16px 18px", marginBottom: 12, background: active ? "var(--paper)" : "transparent",
    border: active ? "1.5px solid var(--ink)" : "1px solid var(--line)", borderRadius: "var(--radius-lg)", cursor: "pointer",
  }}>
    <span style={{ width: 18, height: 18, borderRadius: "50%", border: "1.5px solid " + (active ? "var(--ink)" : "var(--line)"), flexShrink: 0, display: "flex", alignItems: "center", justifyContent: "center" }}>
      {active && <span style={{ width: 9, height: 9, borderRadius: "50%", background: "var(--ink)" }} />}
    </span>
    <span style={{ flex: 1 }}>
      <span style={{ display: "block", fontSize: 14.5, color: "var(--ink)" }}>{title}</span>
      <span style={{ display: "block", fontSize: 12.5, color: "var(--ink-faint)", marginTop: 2 }}>{note}</span>
    </span>
    <span style={{ fontSize: 14, fontVariantNumeric: "tabular-nums" }}>{price}</span>
  </button>
);

const formatCard = (v) => v.replace(/\D/g, "").slice(0, 16).replace(/(.{4})/g, "$1 ").trim();
const formatExp = (v) => { const d = v.replace(/\D/g, "").slice(0, 4); return d.length >= 3 ? d.slice(0, 2) + "/" + d.slice(2) : d; };

/* =================== CONFIRMATION =================== */
function ConfirmationPage({ order, go }) {
  useEffect(() => { window.scrollTo(0, 0); }, []);
  const num = order?.num || "SR-00000";
  return (
    <div className="page-fade container" style={{ padding: "80px 36px 100px", maxWidth: 680, textAlign: "center" }}>
      <div style={{ width: 64, height: 64, borderRadius: "50%", background: "var(--sage)", color: "var(--ink)", display: "flex", alignItems: "center", justifyContent: "center", margin: "0 auto 28px" }}>
        <IconCheck size={30} sw={1.5} />
      </div>
      <div className="eyebrow" style={{ marginBottom: 16 }}>Commande confirmée</div>
      <h1 style={{ fontSize: "clamp(34px, 5vw, 52px)" }}>Merci{order?.first ? ", " + order.first : ""}.</h1>
      <p style={{ marginTop: 18, color: "var(--ink-soft)", fontSize: 16, lineHeight: 1.7 }}>
        Votre commande <strong style={{ fontWeight: 500, color: "var(--ink)" }}>{num}</strong> est en préparation dans nos ateliers.
        Un email de confirmation arrive à l'instant{order?.email ? " sur " + order.email : ""}.
      </p>

      <div style={{ background: "var(--cream-deep)", borderRadius: "var(--radius-lg)", padding: 28, marginTop: 38, textAlign: "left", display: "grid", gridTemplateColumns: "1fr 1fr", gap: 22 }}>
        <div>
          <div className="eyebrow" style={{ marginBottom: 8 }}>Livraison</div>
          <p style={{ fontSize: 14.5, lineHeight: 1.6, color: "var(--ink-soft)" }}>
            {order?.first} {order?.last}<br />{order?.address}<br />{order?.zip} {order?.city}
          </p>
        </div>
        <div>
          <div className="eyebrow" style={{ marginBottom: 8 }}>Total réglé</div>
          <p style={{ fontSize: 26, fontFamily: "var(--font-display)" }}>{fmt(order?.total || 0)}</p>
          <p style={{ fontSize: 13, color: "var(--ink-faint)", marginTop: 4 }}>{order?.delivery === "express" ? "Express · 24 h" : "Standard · 2–4 jours"}</p>
        </div>
      </div>

      <div style={{ marginTop: 40 }}><button className="btn" onClick={() => go("home")}>Retour à l'accueil</button></div>
    </div>
  );
}

Object.assign(window, { CartPage, CheckoutPage, ConfirmationPage, SummaryRows, shippingCost, SHIPPING_THRESHOLD });
