// ── Reservierungs-Modal ──────────────────────────────────────────────────────
function dayLabel(offset) {
  const d = new Date();
  d.setDate(d.getDate() + offset);
  const wd = ["So", "Mo", "Di", "Mi", "Do", "Fr", "Sa"][d.getDay()];
  if (offset === 0) return { key: offset, top: "Heute", sub: `${wd}. ${d.getDate()}.${d.getMonth() + 1}.`, dow: d.getDay() };
  if (offset === 1) return { key: offset, top: "Morgen", sub: `${wd}. ${d.getDate()}.${d.getMonth() + 1}.`, dow: d.getDay() };
  return { key: offset, top: wd, sub: `${d.getDate()}.${d.getMonth() + 1}.`, dow: d.getDay() };
}

function ReserveModal({ open, onClose }) {
  const days = React.useMemo(() => Array.from({ length: 7 }, (_, i) => dayLabel(i)), [open]);
  const [day, setDay] = React.useState(days[0]);
  const [people, setPeople] = React.useState(2);
  const [time, setTime] = React.useState(null);
  const [form, setForm] = React.useState({ name: "", phone: "" });
  const [touched, setTouched] = React.useState(false);
  const [done, setDone] = React.useState(null);

  React.useEffect(() => {
    if (open) { setDone(null); setTouched(false); setTime(null); setDay(days[0]); setPeople(2); }
  }, [open]);
  React.useEffect(() => {
    const on = (e) => e.key === "Escape" && onClose();
    if (open) { document.addEventListener("keydown", on); document.body.style.overflow = "hidden"; }
    return () => { document.removeEventListener("keydown", on); document.body.style.overflow = ""; };
  }, [open]);

  if (!open) return null;

  // 7 Tage geöffnet; Mittagsservice Mo–Fr, Abendservice täglich bis 24 Uhr
  const closed = false;
  const lunch = [1, 2, 3, 4, 5].includes(day.dow) ? ["11:00", "11:30", "12:00", "12:30", "13:00", "13:30"] : [];
  const dinner = ["17:00", "17:30", "18:00", "18:30", "19:00", "19:30", "20:00", "20:30", "21:00", "21:30", "22:00"];

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

  const submit = () => {
    setTouched(true);
    if (!ready) return;
    setDone({ num: "RV-" + String(Math.floor(1000 + Math.random() * 9000)), day, people, time, name: form.name.trim() });
  };

  return (
    <div className="fixed inset-0 z-[60] flex sm:items-center justify-center anim-fade" role="dialog" aria-modal="true" aria-label="Tisch reservieren">
      <div className="absolute inset-0 bg-ink/55 backdrop-blur-sm" onClick={onClose} />
      <div className="relative w-full sm:max-w-lg bg-paper sm:rounded-xl2 overflow-hidden mt-auto sm:mt-0 max-h-[94vh] flex flex-col anim-sheet shadow-2xl">
        {/* Header */}
        <div className="shrink-0 flex items-center justify-between gap-3 px-6 h-16 border-b border-line">
          <div>
            <div className="font-mono text-[10px] uppercase tracking-[0.2em] text-terra">Prenotazione</div>
            <h2 className="font-serif text-[22px] leading-none text-ink">{done ? "Reserviert" : "Tisch reservieren"}</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>

        <div className="flex-1 overflow-y-auto px-6">
          {done ? (
            <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">A presto, {done.name.split(" ")[0]}!</h3>
              <p className="text-[15.5px] text-muted mt-2">Wir freuen uns auf deinen Besuch.</p>
              <div className="mt-7 bg-card border border-line rounded-xl2 p-6 text-left space-y-4">
                <div className="flex items-center justify-between"><span className="text-[14px] text-muted">Reservierung</span><span className="font-mono text-[15px] text-ink">{done.num}</span></div>
                <div className="flex items-center gap-3 pt-4 border-t border-line">
                  <Ico.clock className="w-6 h-6 text-terra" />
                  <div>
                    <div className="font-serif text-2xl text-ink leading-tight">{done.day.top}, {done.time} Uhr</div>
                    <div className="text-[13px] text-muted">{done.people} {done.people === 1 ? "Person" : "Personen"} · {done.day.sub}</div>
                  </div>
                </div>
                <p className="text-[13px] text-muted pt-1 flex items-center gap-2"><Ico.pin className="w-4 h-4 text-terra" /> {RESTAURANT.address.street}, {RESTAURANT.address.city}</p>
              </div>
              <p className="text-[12.5px] text-muted mt-5">Bei Änderungen erreichst du uns unter {RESTAURANT.phone}.</p>
            </div>
          ) : (
            <div className="py-5 space-y-7">
              {/* Personen */}
              <div>
                <div className="font-medium text-[15px] text-ink mb-2.5">Wie viele Personen?</div>
                <div className="flex items-center gap-2 flex-wrap">
                  {[1, 2, 3, 4, 5, 6].map((n) => (
                    <button key={n} onClick={() => setPeople(n)}
                      className={cx("w-12 h-12 rounded-xl border text-[16px] font-medium tabular-nums transition-colors",
                        people === n ? "border-terra bg-terra/8 text-ink" : "border-line bg-card text-ink/80 hover:border-ink/25")}>{n}</button>
                  ))}
                  <button onClick={() => setPeople(Math.max(7, people + 1))}
                    className={cx("h-12 px-4 rounded-xl border text-[15px] font-medium transition-colors",
                      people >= 7 ? "border-terra bg-terra/8 text-ink" : "border-line bg-card text-ink/80 hover:border-ink/25")}>
                    {people >= 7 ? `${people} Pers.` : "7+"}
                  </button>
                </div>
              </div>

              {/* Datum */}
              <div>
                <div className="font-medium text-[15px] text-ink mb-2.5">An welchem Tag?</div>
                <div className="flex gap-2 overflow-x-auto no-sb -mx-1 px-1 pb-1">
                  {days.map((d) => (
                    <button key={d.key} onClick={() => { setDay(d); setTime(null); }}
                      className={cx("shrink-0 w-[72px] py-2.5 rounded-xl border text-center transition-colors",
                        day.key === d.key ? "border-terra bg-terra/8" : "border-line bg-card hover:border-ink/25")}>
                      <div className="text-[14px] font-medium text-ink">{d.top}</div>
                      <div className="text-[11px] text-muted mt-0.5">{d.sub}</div>
                    </button>
                  ))}
                </div>
              </div>

              {/* Uhrzeit */}
              <div>
                <div className="font-medium text-[15px] text-ink mb-2.5">Um wie viel Uhr?</div>
                {closed ? (
                  <div className="rounded-xl border border-line bg-card px-4 py-4 text-[14px] text-muted">
                    Am Montag ist Ruhetag. Bitte wähle einen anderen Tag. 🌿
                  </div>
                ) : (
                  <div className="space-y-3">
                    {lunch.length > 0 && (
                      <div>
                        <div className="font-mono text-[10px] uppercase tracking-widest text-muted mb-2">Mittag</div>
                        <div className="grid grid-cols-5 gap-2">
                          {lunch.map((t) => (
                            <button key={t} onClick={() => setTime(t)}
                              className={cx("h-11 rounded-xl border text-[14px] tabular-nums transition-colors",
                                time === t ? "border-terra bg-terra/8 text-ink font-medium" : "border-line bg-card text-ink/80 hover:border-ink/25")}>{t}</button>
                          ))}
                        </div>
                      </div>
                    )}
                    <div>
                      <div className="font-mono text-[10px] uppercase tracking-widest text-muted mb-2">Abend</div>
                      <div className="grid grid-cols-5 gap-2">
                        {dinner.map((t) => (
                          <button key={t} onClick={() => setTime(t)}
                            className={cx("h-11 rounded-xl border text-[14px] tabular-nums transition-colors",
                              time === t ? "border-terra bg-terra/8 text-ink font-medium" : "border-line bg-card text-ink/80 hover:border-ink/25")}>{t}</button>
                        ))}
                      </div>
                    </div>
                  </div>
                )}
              </div>

              {/* Kontakt */}
              <div className="space-y-4">
                <div>
                  <label className="font-medium text-[15px] text-ink mb-2 block" htmlFor="rname">Name</label>
                  <input id="rname" 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")} />
                </div>
                <div>
                  <label className="font-medium text-[15px] text-ink mb-2 block" htmlFor="rphone">Telefon</label>
                  <input id="rphone" 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")} />
                </div>
              </div>
            </div>
          )}
        </div>

        {/* Footer */}
        <div className="shrink-0 border-t border-line p-4 sm:p-5 bg-paper" style={{ paddingBottom: "max(1rem, env(safe-area-inset-bottom))" }}>
          {done ? (
            <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>
          ) : (
            <button onClick={submit}
              className={cx("w-full h-14 rounded-full font-medium text-[16px] transition-colors",
                ready ? "bg-terra text-white hover:bg-terra-d" : "bg-terra/45 text-white cursor-not-allowed")}>
              {time && !closed ? `Reservieren · ${day.top}, ${time} Uhr` : "Reservierung anfragen"}
            </button>
          )}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { ReserveModal });
