/* cart.jsx — slide-out cart drawer + checkout flow */

const DELIVERY_FEE = 6.0;
const FREE_OVER = 60.0;

function CartDrawer({ open, items, soupsById, onClose, onInc, onDec, onRemove, onCheckout }) {
  const subtotal = items.reduce((s, it) => s + (soupsById[it.id]?.price || it.price || 0) * it.qty, 0);
  const count = items.reduce((s, it) => s + it.qty, 0);

  return (
    <React.Fragment>
      <div className={"scrim" + (open ? " open" : "")} onClick={onClose}></div>
      <aside className={"drawer" + (open ? " open" : "")} aria-hidden={!open}>
        <div className="drawer-head">
          <h3>Dein Warenkorb</h3>
          {count > 0 && <span className="count">· {count} {count === 1 ? "Artikel" : "Artikel"}</span>}
          <button className="icon-btn" onClick={onClose} aria-label="schliessen"><Icon.x /></button>
        </div>

        {items.length === 0 ? (
          <div className="cart-empty">
            <div className="ce-icon"><Icon.bowl /></div>
            <h4>Noch ist der Topf leer</h4>
            <p>Stöbere durch die Speisekarte und füge deine Lieblingssuppen hinzu.</p>
            <button className="btn btn-primary" style={{ marginTop: 18 }} onClick={onClose}>Suppen entdecken</button>
          </div>
        ) : (
          <React.Fragment>
            <div className="drawer-body">
              {items.map((it) => {
                const s = soupsById[it.id] || it;
                return (
                  <div className="cart-line" key={it.id}>
                    <div className="thumb"><Photo id={"cart-" + it.id} label="" tint={s.tint} /></div>
                    <div className="cl-main">
                      <div className="cl-top">
                        <div>
                          <h4>{s.name}</h4>
                          <div className="cl-meta">{s.size} · {CHF(s.price)}</div>
                        </div>
                        <button className="cl-rm" onClick={() => onRemove(it.id)} aria-label="entfernen"><Icon.x /></button>
                      </div>
                      <div className="cl-bot">
                        <Stepper qty={it.qty} onDec={() => onDec(it.id)} onInc={() => onInc(it.id)} />
                        <span className="cl-price">{CHF(s.price * it.qty)}</span>
                      </div>
                    </div>
                  </div>
                );
              })}
            </div>
            <div className="drawer-foot">
              <div className="row"><span>Zwischensumme</span><span>{CHF(subtotal)}</span></div>
              <div className="row" style={{ color: "var(--ink-mute)" }}>
                <span>Lieferung</span>
                <span>{subtotal >= FREE_OVER ? "gratis ab CHF 60" : "ab " + CHF(DELIVERY_FEE)}</span>
              </div>
              <div className="row total"><span>Total</span><span className="amt">{CHF(subtotal)}</span></div>
              <button className="btn btn-primary btn-block btn-lg" onClick={onCheckout}>
                Zur Kasse <Icon.arrowR />
              </button>
              <p className="note">Lieferung in Zürich & Zollikon · Versand kanton­weit</p>
            </div>
          </React.Fragment>
        )}
      </aside>
    </React.Fragment>
  );
}

/* ---------------- CHECKOUT ---------------- */
function Checkout({ items, soupsById, onClose, onDone }) {
  const [step, setStep] = React.useState("details"); // details | pay | confirm
  const [method, setMethod] = React.useState("delivery");
  const [form, setForm] = React.useState({ name: "", email: "", phone: "", street: "", zip: "", city: "Zürich", notes: "" });
  const [pay, setPay] = React.useState({ card: "", exp: "", cvc: "", holder: "" });
  const [errors, setErrors] = React.useState({});
  const [orderNo] = React.useState(() => "SK-" + Math.floor(1000 + Math.random() * 9000));
  const [processing, setProcessing] = React.useState(false);

  const subtotal = items.reduce((s, it) => s + (soupsById[it.id]?.price || it.price || 0) * it.qty, 0);
  const fee = method === "pickup" ? 0 : subtotal >= FREE_OVER ? 0 : DELIVERY_FEE;
  const total = subtotal + fee;

  const set = (k, v) => { setForm((f) => ({ ...f, [k]: v })); setErrors((e) => ({ ...e, [k]: null })); };

  const validateDetails = () => {
    const e = {};
    if (!form.name.trim()) e.name = "Bitte Name angeben";
    if (!/\S+@\S+\.\S+/.test(form.email)) e.email = "Gültige E-Mail angeben";
    if (!form.phone.trim()) e.phone = "Telefon für Rückfragen";
    if (method === "delivery") {
      if (!form.street.trim()) e.street = "Strasse & Nr. angeben";
      if (!/^\d{4}$/.test(form.zip.trim())) e.zip = "PLZ";
    }
    setErrors(e);
    return Object.keys(e).length === 0;
  };

  const goPay = () => { if (validateDetails()) { setStep("pay"); window.scrollTo(0, 0); } };

  const doPay = (e) => {
    e.preventDefault();
    setProcessing(true);
    setTimeout(() => { setProcessing(false); setStep("confirm"); onDone(); }, 1400);
  };

  const steps = [
    { id: "details", n: 1, lbl: "Angaben" },
    { id: "pay", n: 2, lbl: "Zahlung" },
    { id: "confirm", n: 3, lbl: "Bestätigung" },
  ];
  const stepIdx = steps.findIndex((s) => s.id === step);

  // formatting helpers for the mock card form
  const fmtCard = (v) => v.replace(/\D/g, "").slice(0, 16).replace(/(.{4})/g, "$1 ").trim();
  const fmtExp = (v) => { const d = v.replace(/\D/g, "").slice(0, 4); return d.length > 2 ? d.slice(0, 2) + "/" + d.slice(2) : d; };

  const Summary = () => (
    <aside className="co-summary">
      <h3>Deine Bestellung</h3>
      {items.map((it) => {
        const s = soupsById[it.id] || it;
        return (
          <div className="co-sum-line" key={it.id}>
            <span className="qx">{it.qty}×</span>
            <span className="nm">{s.name}<br/><span style={{ color: "var(--ink-mute)", fontSize: 12 }}>{s.size}</span></span>
            <span className="pr">{CHF(s.price * it.qty)}</span>
          </div>
        );
      })}
      <div className="co-sum-tot">
        <div className="row"><span>Zwischensumme</span><span>{CHF(subtotal)}</span></div>
        <div className="row"><span>{method === "pickup" ? "Abholung" : "Lieferung"}</span><span>{fee === 0 ? "gratis" : CHF(fee)}</span></div>
        <div className="row grand"><span>Total</span><span className="amt">{CHF(total)}</span></div>
      </div>
    </aside>
  );

  return (
    <div className="checkout">
      <div className="co-bar">
        <div className="wrap co-bar-in">
          <button className="co-back" onClick={step === "confirm" ? onClose : (step === "pay" ? () => setStep("details") : onClose)}>
            <Icon.arrowL /> {step === "confirm" ? "Zum Shop" : "Zurück"}
          </button>
          <div className="co-steps">
            {steps.map((s, i) => (
              <React.Fragment key={s.id}>
                {i > 0 && <span className="co-divider"></span>}
                <span className={"co-step" + (i === stepIdx ? " active" : "") + (i < stepIdx ? " done" : "")}>
                  <span className="dot">{i < stepIdx ? <Icon.check /> : s.n}</span>
                  <span className="lbl">{s.lbl}</span>
                </span>
              </React.Fragment>
            ))}
          </div>
          <div style={{ width: 90 }}></div>
        </div>
      </div>

      <div className="co-main">
        <div className="wrap">
          {step === "details" && (
            <div className="co-layout">
              <div className="co-form">
                <h2>Lieferung & Kontakt</h2>
                <p className="co-lead">Kein Konto nötig – Christine bestätigt deine Bestellung per Nachricht.</p>

                <div className="co-section-title">Wie möchtest du erhalten?</div>
                <div className="seg">
                  <div className={"seg-opt" + (method === "delivery" ? " on" : "")} onClick={() => setMethod("delivery")}>
                    <span className="so-ic"><Icon.truck /></span>
                    <div><b>Lieferung</b><span>Zürich & Zollikon · Di & Fr</span></div>
                  </div>
                  <div className={"seg-opt" + (method === "pickup" ? " on" : "")} onClick={() => setMethod("pickup")}>
                    <span className="so-ic"><Icon.store /></span>
                    <div><b>Abholung</b><span>Wollishofen · gratis</span></div>
                  </div>
                </div>

                <div className="co-section-title">Deine Angaben</div>
                <div className="field">
                  <label>Name</label>
                  <input className={errors.name ? "err" : ""} value={form.name} onChange={(e) => set("name", e.target.value)} placeholder="Vor- und Nachname" />
                  {errors.name && <div className="err-msg">{errors.name}</div>}
                </div>
                <div className="field-row">
                  <div className="field">
                    <label>E-Mail</label>
                    <input className={errors.email ? "err" : ""} value={form.email} onChange={(e) => set("email", e.target.value)} placeholder="du@email.ch" />
                    {errors.email && <div className="err-msg">{errors.email}</div>}
                  </div>
                  <div className="field">
                    <label>Telefon</label>
                    <input className={errors.phone ? "err" : ""} value={form.phone} onChange={(e) => set("phone", e.target.value)} placeholder="079 123 45 67" />
                    {errors.phone && <div className="err-msg">{errors.phone}</div>}
                  </div>
                </div>

                {method === "delivery" && (
                  <React.Fragment>
                    <div className="co-section-title">Lieferadresse</div>
                    <div className="field">
                      <label>Strasse & Nr.</label>
                      <input className={errors.street ? "err" : ""} value={form.street} onChange={(e) => set("street", e.target.value)} placeholder="Seestrasse 12" />
                      {errors.street && <div className="err-msg">{errors.street}</div>}
                    </div>
                    <div className="field-row">
                      <div className="field" style={{ maxWidth: 140 }}>
                        <label>PLZ</label>
                        <input className={errors.zip ? "err" : ""} value={form.zip} onChange={(e) => set("zip", e.target.value)} placeholder="8038" inputMode="numeric" />
                        {errors.zip && <div className="err-msg">{errors.zip}</div>}
                      </div>
                      <div className="field">
                        <label>Ort</label>
                        <input value={form.city} onChange={(e) => set("city", e.target.value)} />
                      </div>
                    </div>
                  </React.Fragment>
                )}

                <div className="field" style={{ marginTop: 8 }}>
                  <label>Notiz für Christine <span style={{ color: "var(--ink-mute)", fontWeight: 400 }}>(optional)</span></label>
                  <textarea value={form.notes} onChange={(e) => set("notes", e.target.value)} placeholder="z.B. bitte beim Nachbarn abgeben, weniger Salz, Wunschtermin …"></textarea>
                </div>

                <button className="btn btn-primary btn-lg btn-block" style={{ marginTop: 10 }} onClick={goPay}>
                  Weiter zur Zahlung <Icon.arrowR />
                </button>
              </div>
              <Summary />
            </div>
          )}

          {step === "pay" && (
            <div className="co-layout">
              <div className="co-form">
                <h2>Zahlung</h2>
                <p className="co-lead">Sicher bezahlen – deine Suppen werden danach frisch für dich gekocht.</p>
                <form className="pay-card" onSubmit={doPay}>
                  <div className="field">
                    <label>Karteninhaber:in</label>
                    <input required value={pay.holder} onChange={(e) => setPay({ ...pay, holder: e.target.value })} placeholder="Name auf der Karte" />
                  </div>
                  <div className="field">
                    <label>Kartennummer</label>
                    <div className="card-input-wrap">
                      <input required value={pay.card} onChange={(e) => setPay({ ...pay, card: fmtCard(e.target.value) })} placeholder="4242 4242 4242 4242" inputMode="numeric" />
                      <span className="brand-ic"><span>VISA</span></span>
                    </div>
                  </div>
                  <div className="field-row">
                    <div className="field">
                      <label>Ablauf</label>
                      <input required value={pay.exp} onChange={(e) => setPay({ ...pay, exp: fmtExp(e.target.value) })} placeholder="MM/JJ" inputMode="numeric" />
                    </div>
                    <div className="field">
                      <label>CVC</label>
                      <input required value={pay.cvc} onChange={(e) => setPay({ ...pay, cvc: e.target.value.replace(/\D/g, "").slice(0, 4) })} placeholder="123" inputMode="numeric" />
                    </div>
                  </div>
                  <button className="btn btn-primary btn-lg btn-block" type="submit" disabled={processing} style={{ marginTop: 8 }}>
                    {processing ? "Wird verarbeitet …" : <React.Fragment><Icon.lock /> {CHF(total)} bezahlen</React.Fragment>}
                  </button>
                  <div className="pay-secure"><Icon.lock /> Verschlüsselte Zahlung · powered by Stripe</div>
                  <div className="demo-note"><Icon.info /> Demo-Modus: Es wird keine echte Zahlung ausgeführt. Beliebige Testdaten funktionieren.</div>
                </form>
              </div>
              <Summary />
            </div>
          )}

          {step === "confirm" && (
            <div className="confirm">
              <div className="check"><Icon.check /></div>
              <span className="c-ord">Bestellung {orderNo}</span>
              <h1>Danke, {form.name.split(" ")[0] || "und bis bald"}!</h1>
              <p className="c-lead">Deine Bestellung ist bei Christine eingegangen. Du erhältst gleich eine Bestätigung an <b>{form.email}</b>.</p>
              <div className="c-card">
                <div className="cc-row"><span className="k">{method === "pickup" ? "Abholung" : "Lieferung an"}</span><span className="v">{method === "pickup" ? "Wollishofen, nach Vereinbarung" : `${form.street}, ${form.zip} ${form.city}`}</span></div>
                <div className="cc-row"><span className="k">Suppen</span><span className="v">{items.reduce((s, it) => s + it.qty, 0)} Portionen</span></div>
                <div className="cc-row"><span className="k">Voraussichtlich</span><span className="v">{method === "pickup" ? "ab morgen abholbereit" : "nächster Liefertag (Di/Fr)"}</span></div>
                <div className="cc-row" style={{ borderTop: "1px solid var(--line)", marginTop: 6, paddingTop: 14 }}><span className="k">Bezahlt</span><span className="v">{CHF(total)}</span></div>
              </div>
              <button className="btn btn-primary btn-lg" onClick={onClose}>Zurück zum Shop</button>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { CartDrawer, Checkout });
