// Reservation: date/time/party -> details -> confirmation
const { useState: useStateRV, useMemo: useMemoRV, useEffect: useEffectRV } = React;

function ReservationModal({ open, onClose }) {
  const { t, lang } = useT();
  const store = useLnStore();
  const mode = store.serviceModes.reservation;
  if (mode !== 'online') {
    return <ServiceFallbackModal open={open} onClose={onClose} service="reservation" />;
  }
  const rt = t.reservation;
  const [step, setStep] = useStateRV('slot');
  const [selectedDate, setSelectedDate] = useStateRV(null);
  const [selectedTime, setSelectedTime] = useStateRV(null);
  const [party, setParty] = useStateRV(2);
  const [details, setDetails] = useStateRV({ name: '', phone: '', email: '', occasion: '', note: '' });
  const [errors, setErrors] = useStateRV({});
  const [ref] = useStateRV(() => 'RSV-' + Math.floor(Math.random()*9000+1000));

  useEffectRV(() => {
    if (!open) {
      setTimeout(() => {
        setStep('slot'); setSelectedDate(null); setSelectedTime(null); setParty(2);
        setDetails({ name: '', phone: '', email: '', occasion: '', note: '' }); setErrors({});
      }, 250);
    }
  }, [open]);

  const dates = useMemoRV(() => Object.keys(AVAILABILITY).sort(), []);
  const monthLabel = useMemoRV(() => {
    if (!selectedDate) return null;
    return formatDate(selectedDate, lang, { weekday: 'long', day: 'numeric', month: 'long' });
  }, [selectedDate, lang]);

  const slots = selectedDate ? AVAILABILITY[selectedDate] : [];

  const submit = () => {
    const e = {};
    if (!details.name.trim()) e.name = rt.errReq;
    if (!/^[0-9 +().-]{6,}$/.test(details.phone.trim())) e.phone = rt.errPhone;
    if (details.email && !/^\S+@\S+\.\S+$/.test(details.email.trim())) e.email = rt.errEmail;
    setErrors(e);
    if (Object.keys(e).length === 0) {
      lnAddReservation({
        ref,
        date: selectedDate,
        time: selectedTime,
        party,
        customer: { name: details.name, phone: details.phone, email: details.email, occasion: details.occasion, note: details.note },
      });
      setStep('done');
    }
  };

  const formatDatePill = (iso) => {
    const locale = lang === 'fr' ? 'fr-FR' : 'en-GB';
    const d = new Date(iso);
    return {
      dow: d.toLocaleDateString(locale, { weekday: 'short' }),
      day: d.getDate(),
      month: d.toLocaleDateString(locale, { month: 'short' }),
    };
  };

  return (
    <Modal open={open} onClose={onClose} width={820} title={step === 'done' ? null : rt.title}>
      {step === 'slot' && (
        <div className="ln-modal-section">
          <p style={{ margin: '0 0 22px', color: 'var(--ink-soft)', fontSize: 15, lineHeight: 1.6, maxWidth: 560 }}>{rt.intro}</p>
          <div style={{ marginBottom: 22 }}>
            <div style={{ fontSize: 12, fontWeight: 600, letterSpacing: '0.04em', textTransform: 'uppercase', color: 'var(--ink-soft)', marginBottom: 10 }}>{rt.party}</div>
            <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
              {[1,2,3,4,5,6,7,8].map(n => {
                const active = party === n;
                return (
                  <button key={n} onClick={() => setParty(n)} style={{
                    width: 44, height: 44, borderRadius: 10,
                    background: active ? 'var(--ink)' : 'var(--card)',
                    color: active ? 'var(--paper)' : 'var(--ink)',
                    border: active ? '1px solid var(--ink)' : '1px solid var(--line)',
                    fontWeight: 600, fontSize: 15 }}>{n}</button>
                );
              })}
              <button onClick={() => setParty(9)} style={{
                height: 44, padding: '0 14px', borderRadius: 10,
                background: party >= 9 ? 'var(--ink)' : 'var(--card)',
                color: party >= 9 ? 'var(--paper)' : 'var(--ink)',
                border: party >= 9 ? '1px solid var(--ink)' : '1px solid var(--line)',
                fontWeight: 600, fontSize: 13 }}>{rt.call}</button>
            </div>
          </div>
          <div style={{ marginBottom: 22 }}>
            <div style={{ fontSize: 12, fontWeight: 600, letterSpacing: '0.04em', textTransform: 'uppercase', color: 'var(--ink-soft)', marginBottom: 10 }}>{rt.date}</div>
            <div style={{ display: 'flex', gap: 8, overflowX: 'auto', paddingBottom: 4 }}>
              {dates.map(iso => {
                const { dow, day, month } = formatDatePill(iso);
                const active = iso === selectedDate;
                const anyAvail = AVAILABILITY[iso].some(s => s.available);
                return (
                  <button key={iso} onClick={() => { setSelectedDate(iso); setSelectedTime(null); }} disabled={!anyAvail}
                    style={{ display: 'flex', flexDirection: 'column', alignItems: 'center',
                      minWidth: 64, padding: '10px 10px', borderRadius: 12,
                      background: active ? 'var(--accent)' : 'var(--card)',
                      color: active ? '#fff' : (anyAvail ? 'var(--ink)' : 'var(--muted)'),
                      border: active ? '1px solid var(--accent)' : '1px solid var(--line)',
                      opacity: anyAvail ? 1 : 0.55, cursor: anyAvail ? 'pointer' : 'not-allowed' }}>
                    <span style={{ fontSize: 11, fontWeight: 500, letterSpacing: '0.04em', textTransform: 'uppercase' }}>{dow}</span>
                    <span className="serif" style={{ fontSize: 22, fontWeight: 600, lineHeight: 1 }}>{day}</span>
                    <span style={{ fontSize: 11 }}>{month}</span>
                  </button>
                );
              })}
            </div>
          </div>
          {selectedDate && (
            <div style={{ marginBottom: 22, animation: 'slideInRight .25s ease' }}>
              <div style={{ fontSize: 12, fontWeight: 600, letterSpacing: '0.04em', textTransform: 'uppercase', color: 'var(--ink-soft)', marginBottom: 10 }}>
                {rt.timeFor(party, monthLabel)}
              </div>
              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(88px, 1fr))', gap: 8 }}>
                {slots.map(s => {
                  const active = s.time === selectedTime;
                  return (
                    <button key={s.time} onClick={() => s.available && setSelectedTime(s.time)} disabled={!s.available}
                      style={{ padding: '12px 10px', borderRadius: 10,
                        background: active ? 'var(--accent)' : 'var(--card)',
                        color: active ? '#fff' : (s.available ? 'var(--ink)' : 'var(--muted)'),
                        border: active ? '1px solid var(--accent)' : '1px solid var(--line)',
                        fontWeight: 600, fontSize: 14,
                        cursor: s.available ? 'pointer' : 'not-allowed',
                        opacity: s.available ? 1 : 0.45,
                        textDecoration: s.available ? 'none' : 'line-through' }}>{s.time}</button>
                  );
                })}
              </div>
              <p style={{ fontSize: 12, color: 'var(--muted)', marginTop: 8 }}>{rt.greyed}</p>
            </div>
          )}
          <div style={{ display: 'flex', justifyContent: 'flex-end', gap: 10 }}>
            <Button variant="ghost" onClick={onClose}>{rt.cancel}</Button>
            <Button variant="primary" size="lg" disabled={!selectedDate || !selectedTime} onClick={() => setStep('details')}>
              {rt.continue} <Icon.arrow />
            </Button>
          </div>
        </div>
      )}

      {step === 'details' && (
        <div className="ln-modal-section">
          <Button variant="ghost" size="sm" onClick={() => setStep('slot')} style={{ marginBottom: 18 }}>{rt.changeSlot}</Button>
          <div style={{ background: 'var(--paper-warm)', padding: '14px 18px', borderRadius: 12, display: 'flex', gap: 22, marginBottom: 22, flexWrap: 'wrap', fontSize: 14 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}><Icon.calendar /> {monthLabel}</div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}><Icon.clock /> {selectedTime}</div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>👥 {party} {party > 1 ? rt.guests : rt.guest}</div>
          </div>
          <div className="ln-form-grid">
            <Field label={rt.resName} error={errors.name}>
              <TextInput value={details.name} onChange={e => setDetails({ ...details, name: e.target.value })} placeholder={rt.placeholders.name} />
            </Field>
            <Field label={rt.phone} error={errors.phone}>
              <TextInput value={details.phone} onChange={e => setDetails({ ...details, phone: e.target.value })} placeholder={rt.placeholders.phone} />
            </Field>
            <Field label={rt.email} error={errors.email} style={{ gridColumn: '1 / -1' }}>
              <TextInput value={details.email} onChange={e => setDetails({ ...details, email: e.target.value })} placeholder={rt.placeholders.email} />
            </Field>
            <Field label={rt.occasion} style={{ gridColumn: '1 / -1' }}>
              <select value={details.occasion} onChange={e => setDetails({ ...details, occasion: e.target.value })} style={{ ...inputStyle, padding: '12px 14px' }}>
                <option value="">{rt.occasionNone}</option>
                {rt.occasions.map(o => <option key={o}>{o}</option>)}
              </select>
            </Field>
            <Field label={rt.request} style={{ gridColumn: '1 / -1' }}>
              <textarea value={details.note} onChange={e => setDetails({ ...details, note: e.target.value })} rows={3} placeholder={rt.requestPh} style={{ ...inputStyle, resize: 'vertical' }} />
            </Field>
          </div>
          <div style={{ display: 'flex', justifyContent: 'flex-end', gap: 10, marginTop: 22 }}>
            <Button variant="ghost" onClick={() => setStep('slot')}>{rt.back}</Button>
            <Button variant="primary" size="lg" onClick={submit}>{rt.confirm} <Icon.arrow /></Button>
          </div>
        </div>
      )}

      {step === 'done' && (
        <div className="ln-modal-section-confirm" style={{ textAlign: 'center', maxWidth: 520, margin: '0 auto' }}>
          <div style={{ width: 72, height: 72, borderRadius: 999, background: 'color-mix(in oklab, var(--ok) 15%, transparent)', color: 'var(--ok)', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', marginBottom: 20 }}>
            <Icon.check size={32} />
          </div>
          <h2 className="serif" style={{ margin: '0 0 10px', fontSize: 30, fontWeight: 600 }}>{rt.doneTitle}</h2>
          <p style={{ margin: 0, color: 'var(--ink-soft)', fontSize: 15, lineHeight: 1.6 }}>
            {rt.doneBody(details.name.split(' ')[0] || '', party, monthLabel, selectedTime, ref)}
          </p>
          <div style={{ display: 'flex', justifyContent: 'center', gap: 12, marginTop: 24, flexWrap: 'wrap' }}>
            <Button variant="primary" onClick={onClose}>{rt.backToSite}</Button>
          </div>
        </div>
      )}
    </Modal>
  );
}

Object.assign(window, { ReservationModal });
