// ── Abhol-Slots generieren ───────────────────────────────────────────────────
function buildSlots() {
  const open = 17 * 60;        // 17:00
  const close = 22 * 60 + 30;  // 22:30
  const now = new Date();
  const nowMin = now.getHours() * 60 + now.getMinutes();
  const earliest = Math.max(open, Math.ceil((nowMin + 20) / 15) * 15);
  const slots = [];
  for (let m = open; m <= close; m += 15) {
    slots.push({ value: pad(m), disabled: m < earliest });
  }
  return { slots, earliest: pad(earliest <= close ? earliest : open) };
}
function pad(min) {
  const h = Math.floor(min / 60), m = min % 60;
  return String(h).padStart(2, "0") + ":" + String(m).padStart(2, "0");
}

// ── Warenkorb-Zeile ──────────────────────────────────────────────────────────
function CartLine({ item, onQty, onRemove }) {
  return (
    <div className="flex gap-3.5 py-4">
      <FoodPlaceholder tone={item.tone} label="" showLabel={false} className="w-16 h-16 shrink-0" rounded="rounded-xl" />
      <div className="flex-1 min-w-0">
        <div className="flex items-start justify-between gap-2">
          <h4 className="font-serif text-[17px] leading-snug text-ink truncate">{item.name}</h4>
          <span className="font-mono text-[13.5px] text-ink whitespace-nowrap tabular-nums">{CHF(item.unit * item.qty)}</span>
        </div>
        {item.options.filter((o) => !/^(Ohne|Normal)/.test(o.value)).map((o) => (
          <div key={o.label} className="text-[12.5px] text-muted">{o.value}</div>
        ))}
        {item.note && <div className="text-[12.5px] text-muted italic">„{item.note}"</div>}
        <div className="mt-2 flex items-center justify-between">
          <div className="flex items-center gap-1 border border-line rounded-full">
            <button onClick={() => onQty(item.key, item.qty - 1)} className="w-8 h-8 grid place-items-center rounded-full hover:bg-ink/5" aria-label="Weniger"><Ico.minus className="w-4 h-4" /></button>
            <span className="w-6 text-center text-[14px] tabular-nums">{item.qty}</span>
            <button onClick={() => onQty(item.key, item.qty + 1)} className="w-8 h-8 grid place-items-center rounded-full hover:bg-ink/5" aria-label="Mehr"><Ico.plus className="w-4 h-4" /></button>
          </div>
          <button onClick={() => onRemove(item.key)} className="text-[12.5px] text-muted hover:text-terra transition-colors underline-offset-2 hover:underline">Entfernen</button>
        </div>
      </div>
    </div>
  );
}

// ── Cart-Panel mit Flow ──────────────────────────────────────────────────────
function CartPanel({ open, cart, onClose, onQty, onRemove, onClear, onBrowse }) {
  const [step, setStep] = React.useState("cart"); // cart | time | checkout | done
  const [slot, setSlot] = React.useState(null);    // null = asap
  const [form, setForm] = React.useState({ name: "", phone: "" });
  const [pay, setPay] = React.useState("twint");
  const [touched, setTouched] = React.useState(false);
  const [order, setOrder] = React.useState(null);
  const { slots, earliest } = React.useMemo(buildSlots, [open]);

  React.useEffect(() => {
    if (open) { setStep("cart"); setTouched(false); }
  }, [open]);
  React.useEffect(() => {
    document.body.style.overflow = open ? "hidden" : "";
    return () => { document.body.style.overflow = ""; };
  }, [open]);

  const count = cart.reduce((s, i) => s + i.qty, 0);
  const subtotal = cart.reduce((s, i) => s + i.unit * i.qty, 0);
  const pickupAt = slot || earliest;

  const nameOk = form.name.trim().length >= 2;
  const phoneOk = form.phone.replace(/\D/g, "").length >= 9;
  const formOk = nameOk && phoneOk;

  const place = () => {
    setTouched(true);
    if (!formOk) return;
    const num = "OL-" + String(Math.floor(1000 + Math.random() * 9000));
    setOrder({ num, at: pickupAt, total: subtotal, items: count, name: form.name.trim(), pay });
    setStep("done");
    onClear();
  };

  const PAYMENTS = [
    { id: "twint", label: "TWINT", hint: "QR beim Abholen" },
    { id: "card", label: "Karte", hint: "Vor Ort kontaktlos" },
    { id: "cash", label: "Bei Abholung", hint: "Bar oder Karte" },
  ];

  if (!open) return null;

  return (
    <div className="fixed inset-0 z-[55]" role="dialog" aria-modal="true" aria-label="Warenkorb">
      <div className="absolute inset-0 bg-ink/50 backdrop-blur-sm anim-fade" onClick={onClose} />
      <div className="absolute inset-x-0 bottom-0 sm:inset-y-0 sm:right-0 sm:left-auto sm:inset-x-auto
                      w-full sm:w-[440px] bg-paper flex flex-col
                      max-h-[94vh] sm:max-h-none sm:h-full rounded-t-3xl sm:rounded-none shadow-2xl anim-sheet">

        {/* Header */}
        <div className="shrink-0 flex items-center justify-between gap-3 px-5 sm:px-6 h-16 border-b border-line">
          <div className="flex items-center gap-3">
            {step !== "cart" && step !== "done" && (
              <button onClick={() => setStep(step === "checkout" ? "time" : "cart")} className="w-9 h-9 -ml-1 grid place-items-center rounded-full hover:bg-ink/5 rotate-180" aria-label="Zurück"><Ico.arrow className="w-5 h-5" /></button>
            )}
            <h2 className="font-serif text-[22px] text-ink">
              {step === "cart" && "Dein Warenkorb"}
              {step === "time" && "Abholzeit"}
              {step === "checkout" && "Deine Angaben"}
              {step === "done" && "Bestätigt"}
            </h2>
          </div>
          <button onClick={onClose} className="w-10 h-10 grid place-items-center rounded-full hover:bg-ink/5" aria-label="Schliessen"><Ico.close className="w-6 h-6" /></button>
        </div>

        {/* Stepper */}
        {step !== "done" && (
          <div className="shrink-0 flex items-center gap-1.5 px-5 sm:px-6 py-3 border-b border-line">
            {["cart", "time", "checkout"].map((s, i) => {
              const order = { cart: 0, time: 1, checkout: 2 };
              const cur = order[step];
              const me = i;
              return (
                <React.Fragment key={s}>
                  <span className={cx("h-1.5 rounded-full transition-all flex-1", me <= cur ? "bg-terra" : "bg-line")} />
                </React.Fragment>
              );
            })}
          </div>
        )}

        {/* Body */}
        <div className="flex-1 overflow-y-auto px-5 sm:px-6">
          {/* STEP CART */}
          {step === "cart" && (
            cart.length === 0 ? (
              <div className="h-full flex flex-col items-center justify-center text-center py-16">
                <div className="w-16 h-16 rounded-full bg-ink/5 grid place-items-center text-muted mb-5"><Ico.bag className="w-8 h-8" /></div>
                <p className="font-serif text-xl text-ink">Noch nichts drin</p>
                <p className="text-[15px] text-muted mt-2 max-w-[240px]">Stöbere durch die Speisekarte und leg deine Favoriten hier ab.</p>
                <button onClick={() => { onClose(); onBrowse(); }} className="mt-6 h-12 px-6 rounded-full bg-terra text-white font-medium">Zur Speisekarte</button>
              </div>
            ) : (
              <div className="divide-y divide-line">
                {cart.map((i) => <CartLine key={i.key} item={i} onQty={onQty} onRemove={onRemove} />)}
                <button onClick={() => { onClose(); onBrowse(); }} className="w-full text-left py-4 text-[14px] text-terra hover:underline underline-offset-2">+ Weitere Gerichte hinzufügen</button>
              </div>
            )
          )}

          {/* STEP TIME */}
          {step === "time" && (
            <div className="py-5">
              <p className="text-[15px] text-muted mb-5">Wann möchtest du abholen? <span className="text-ink">{RESTAURANT.address.street}, {RESTAURANT.address.city}</span></p>
              <button onClick={() => setSlot(null)}
                className={cx("w-full flex items-center justify-between gap-3 h-14 px-4 rounded-xl border mb-3 transition-colors",
                  slot === null ? "border-terra bg-terra/8" : "border-line bg-card hover:border-ink/25")}>
                <span className="flex items-center gap-3"><Ico.clock className="w-5 h-5 text-terra" /><span className="text-[15px] font-medium text-ink">So bald wie möglich</span></span>
                <span className="font-mono text-[13px] text-muted">~ {earliest}</span>
              </button>
              <div className="font-mono text-[11px] uppercase tracking-widest text-muted mt-6 mb-3">Oder Zeit wählen — heute</div>
              <div className="grid grid-cols-3 gap-2">
                {slots.map((s) => (
                  <button key={s.value} disabled={s.disabled} onClick={() => setSlot(s.value)}
                    className={cx("h-12 rounded-xl border text-[15px] tabular-nums transition-colors",
                      s.disabled ? "border-line/60 text-muted/40 cursor-not-allowed" :
                      slot === s.value ? "border-terra bg-terra/8 text-ink font-medium" : "border-line bg-card text-ink/80 hover:border-ink/25")}>
                    {s.value}
                  </button>
                ))}
              </div>
            </div>
          )}

          {/* STEP CHECKOUT */}
          {step === "checkout" && (
            <div className="py-5 space-y-6">
              <div>
                <label className="font-medium text-[15px] text-ink mb-2 block" htmlFor="cname">Name</label>
                <input id="cname" value={form.name} onChange={(e) => setForm((f) => ({ ...f, name: e.target.value }))}
                  placeholder="Vor- und Nachname" autoComplete="name"
                  className={cx("w-full h-13 py-3.5 px-4 rounded-xl border bg-card text-[15px] text-ink placeholder:text-muted/60 outline-none transition-colors",
                    touched && !nameOk ? "border-terra" : "border-line focus:border-terra")} />
                {touched && !nameOk && <p className="text-[12.5px] text-terra mt-1.5">Bitte gib deinen Namen an.</p>}
              </div>
              <div>
                <label className="font-medium text-[15px] text-ink mb-2 block" htmlFor="cphone">Telefon</label>
                <input id="cphone" value={form.phone} onChange={(e) => setForm((f) => ({ ...f, phone: e.target.value }))}
                  placeholder="079 123 45 67" inputMode="tel" autoComplete="tel"
                  className={cx("w-full h-13 py-3.5 px-4 rounded-xl border bg-card text-[15px] text-ink placeholder:text-muted/60 outline-none transition-colors",
                    touched && !phoneOk ? "border-terra" : "border-line focus:border-terra")} />
                {touched && !phoneOk && <p className="text-[12.5px] text-terra mt-1.5">Für Rückfragen zur Bestellung.</p>}
              </div>
              <div>
                <div className="font-medium text-[15px] text-ink mb-2">Zahlung</div>
                <div className="grid gap-2">
                  {PAYMENTS.map((p) => {
                    const on = pay === p.id;
                    return (
                      <button key={p.id} onClick={() => setPay(p.id)}
                        className={cx("flex items-center justify-between gap-3 h-14 px-4 rounded-xl border transition-colors",
                          on ? "border-terra bg-terra/8" : "border-line bg-card hover:border-ink/25")}>
                        <span className="flex items-center gap-3">
                          <span className={cx("w-4 h-4 rounded-full border-2 grid place-items-center", on ? "border-terra" : "border-ink/30")}>{on && <span className="w-2 h-2 rounded-full bg-terra" />}</span>
                          <span className="text-[15px] font-medium text-ink">{p.label}</span>
                        </span>
                        <span className="text-[12.5px] text-muted">{p.hint}</span>
                      </button>
                    );
                  })}
                </div>
                <p className="text-[12px] text-muted mt-3 leading-relaxed">Die Bezahlung erfolgt vor Ort bei der Abholung — hier wird nichts belastet.</p>
              </div>
            </div>
          )}

          {/* STEP DONE */}
          {step === "done" && order && (
            <div className="py-10 text-center anim-pop">
              <div className="w-20 h-20 mx-auto rounded-full bg-olive/12 text-olive grid place-items-center mb-6"><Ico.check className="w-10 h-10" /></div>
              <h3 className="font-serif text-[30px] leading-tight text-ink">Grazie, {order.name.split(" ")[0]}!</h3>
              <p className="text-[15.5px] text-muted mt-2">Deine Bestellung ist aufgegeben.</p>
              <div className="mt-7 bg-card border border-line rounded-xl2 p-6 text-left">
                <div className="flex items-center justify-between pb-4 border-b border-line">
                  <span className="text-[14px] text-muted">Bestellnummer</span>
                  <span className="font-mono text-[15px] text-ink">{order.num}</span>
                </div>
                <div className="py-4 border-b border-line flex items-center gap-3">
                  <Ico.clock className="w-6 h-6 text-terra" />
                  <div>
                    <div className="text-[13px] text-muted">Bereit zur Abholung um</div>
                    <div className="font-serif text-2xl text-ink leading-tight">{order.at} Uhr</div>
                  </div>
                </div>
                <div className="pt-4 flex items-center justify-between text-[14px]">
                  <span className="text-muted">{order.items} Artikel · {PAYMENTS.find((p) => p.id === order.pay).label}</span>
                  <span className="font-mono text-ink">{CHF(order.total)}</span>
                </div>
              </div>
              <p className="text-[13px] text-muted mt-5 leading-relaxed flex items-center justify-center gap-2"><Ico.pin className="w-4 h-4 text-terra" /> {RESTAURANT.address.street}, {RESTAURANT.address.city}</p>
            </div>
          )}
        </div>

        {/* Footer-Aktionen */}
        {step !== "done" && cart.length > 0 && (
          <div className="shrink-0 border-t border-line p-4 sm:p-5 bg-paper" style={{ paddingBottom: "max(1rem, env(safe-area-inset-bottom))" }}>
            <div className="flex items-center justify-between mb-3">
              <span className="text-[14px] text-muted">{step === "cart" ? "Zwischensumme" : "Total"} · {count} Artikel</span>
              <span className="font-serif text-2xl text-ink">{CHF(subtotal)}</span>
            </div>
            {step === "cart" && (
              <button onClick={() => setStep("time")} className="w-full h-14 rounded-full bg-terra text-white font-medium text-[16px] hover:bg-terra-d transition-colors flex items-center justify-center gap-2">
                Weiter zur Abholzeit <Ico.arrow className="w-5 h-5" />
              </button>
            )}
            {step === "time" && (
              <button onClick={() => setStep("checkout")} className="w-full h-14 rounded-full bg-terra text-white font-medium text-[16px] hover:bg-terra-d transition-colors flex items-center justify-center gap-2">
                Weiter · Abholung {pickupAt} Uhr <Ico.arrow className="w-5 h-5" />
              </button>
            )}
            {step === "checkout" && (
              <button onClick={place} className="w-full h-14 rounded-full bg-terra text-white font-medium text-[16px] hover:bg-terra-d transition-colors">
                Bestellung aufgeben · {CHF(subtotal)}
              </button>
            )}
          </div>
        )}
        {step === "done" && (
          <div className="shrink-0 border-t border-line p-4 sm:p-5 bg-paper" style={{ paddingBottom: "max(1rem, env(safe-area-inset-bottom))" }}>
            <button onClick={onClose} className="w-full h-14 rounded-full bg-ink text-paper font-medium text-[16px] hover:opacity-90 transition-opacity">Fertig</button>
          </div>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { CartPanel, buildSlots });
