/* Tefi — Booking flow modal: Service → Date → Time → Details → Confirmed (i18n) */

function BookingModal({ open, onClose, initialService, lang = 'en' }) {
  const t = React.useMemo(() => window.makeT(lang), [lang]);
  const dict = window.TEFI_I18N[lang] || window.TEFI_I18N.en;
  const locale = dict.locale || 'en-GB';

  const [step, setStep] = React.useState(0);
  const [service, setService] = React.useState(initialService || null);
  const [date, setDate] = React.useState(null);
  const [time, setTime] = React.useState(null);
  const [details, setDetails] = React.useState({ name: '', email: '', phone: '', notes: '' });
  const [submitted, setSubmitted] = React.useState(false);
  const [calMonth, setCalMonth] = React.useState(() => {
    const t2 = new Date(); t2.setDate(1); t2.setHours(0,0,0,0); return t2;
  });

  React.useEffect(() => {
    if (open) {
      setStep(initialService ? 1 : 0);
      setService(initialService || null);
      setDate(null); setTime(null); setSubmitted(false);
      setDetails({ name: '', email: '', phone: '', notes: '' });
      document.body.style.overflow = 'hidden';
    } else {
      document.body.style.overflow = '';
    }
    return () => { document.body.style.overflow = ''; };
  }, [open, initialService]);

  React.useEffect(() => {
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    if (open) window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [open, onClose]);

  if (!open) return null;

  const allServices = window.TEFI_SERVICES;
  // bookable = anything not in the extras (add-ons) category
  const services = allServices.filter(s => !s.addon);
  const cats = window.TEFI_CATEGORIES.filter(c => c.key !== 'extras');
  const avail = window.TEFI_AVAILABILITY;

  const canNext = (() => {
    if (step === 0) return !!service;
    if (step === 1) return !!date;
    if (step === 2) return !!time;
    if (step === 3) return details.name.trim() && /^.+@.+\..+$/.test(details.email);
    return false;
  })();

  const next = () => {
    if (step < 3) setStep(step + 1);
    else { setSubmitted(true); setStep(4); }
  };
  const back = () => { if (step > 0) setStep(step - 1); };

  const fmtDate = (d) => d ? d.toLocaleDateString(locale, { weekday: 'long', day: 'numeric', month: 'long' }) : '';
  const fmtWeekday = (d) => d ? d.toLocaleDateString(locale, { weekday: 'long' }) : '';

  const serviceName = (s) => s ? (dict.items[s.key]?.name || s.key) : '';

  return (
    <div className="modal-backdrop" onClick={(e) => { if (e.target === e.currentTarget) onClose(); }}>
      <div className="modal-card">
        {/* Header */}
        <div className="px-7 md:px-10 py-6 flex items-center justify-between border-b" style={{ borderColor: 'rgba(42,36,27,0.12)' }}>
          <div>
            <div className="label-tiny" style={{ color: 'var(--label-color)' }}>{t('booking.label')}</div>
            <div className="font-display mt-1" style={{ fontSize: '1.5rem', lineHeight: 1 }}>
              {step === 4 ? t('booking.titleDone') : t('booking.title')}
            </div>
          </div>
          <button onClick={onClose} className="opacity-60 hover:opacity-100 transition-opacity" aria-label="Close">
            <Icon.X size={20} />
          </button>
        </div>

        {/* Stepper */}
        {step < 4 && (
          <div className="px-7 md:px-10 pt-5 pb-2 flex items-center gap-2">
            {[0,1,2,3].map(i => (
              <div key={i} className={`step-dot ${i === step ? 'active' : i < step ? 'done' : ''}`}></div>
            ))}
            <div className="ml-3 text-xs" style={{ color: 'var(--ink-soft)' }}>
              {t('booking.stepNames')[step]} · {t('booking.stepCounter').replace('{n}', step + 1)}
            </div>
          </div>
        )}

        {/* Body — only this part scrolls; header + footer stay pinned */}
        <div className="modal-body px-7 md:px-10 py-6">
          {step === 0 && (
            <div className="space-y-7">
              <p className="text-sm" style={{ color: 'var(--ink-soft)' }}>{t('booking.lead')}</p>
              {cats.map(cat => {
                const items = services.filter(s => s.cat === cat.key);
                if (!items.length) return null;
                const meta = dict.cats[cat.key];
                return (
                  <div key={cat.key}>
                    <div className="flex items-baseline gap-3 mb-3 pb-2 border-b" style={{ borderColor: 'rgba(42,36,27,0.10)' }}>
                      <span style={{ fontSize: '1.1rem' }} aria-hidden>{cat.icon}</span>
                      <span className="font-display" style={{ fontSize: '1rem' }}>{meta.name}</span>
                      <span className="text-xs ml-auto" style={{ color: 'var(--ink-soft)' }}>{meta.tag}</span>
                    </div>
                    <div className="space-y-2">
                      {items.map(s => {
                        const item = dict.items[s.key];
                        return (
                          <button
                            key={s.key}
                            onClick={() => setService(s)}
                            className={`option-tile ${service?.key === s.key ? 'selected' : ''}`}
                          >
                            <div className="flex items-baseline gap-4 min-w-0 flex-1">
                              <span className="font-display text-xs shrink-0" style={{ color: 'var(--label-color)', minWidth: 24 }}>{s.code}</span>
                              <div className="min-w-0">
                                <div className="font-display flex items-center gap-2 flex-wrap" style={{ fontSize: '1.05rem' }}>
                                  {item.name}
                                  {s.popular && <span className="badge-popular">{t('services.popular')}</span>}
                                </div>
                                <div className="text-xs mt-1" style={{ color: 'var(--ink-soft)' }}>{item.desc}</div>
                              </div>
                            </div>
                            <span className="font-display shrink-0 tabular-nums" style={{ fontSize: '1.05rem' }}>{s.price}</span>
                          </button>
                        );
                      })}
                    </div>
                  </div>
                );
              })}
            </div>
          )}

          {step === 1 && (
            <Calendar
              month={calMonth}
              setMonth={setCalMonth}
              avail={avail}
              selected={date}
              onSelect={setDate}
              t={t}
              locale={locale}
            />
          )}

          {step === 2 && date && (
            <div>
              <div className="mb-4">
                <div className="label-tiny" style={{ color: 'var(--label-color)' }}>{t('booking.pickDay')}</div>
                <div className="font-display mt-1" style={{ fontSize: '1.5rem' }}>{fmtDate(date)}</div>
              </div>
              <div className="text-sm mb-4" style={{ color: 'var(--ink-soft)' }}>{t('booking.timeLead')}</div>
              <TimeSlots date={date} avail={avail} selected={time} onSelect={setTime} t={t} />
            </div>
          )}

          {step === 3 && (
            <div className="space-y-7">
              <div>
                <label className="label-tiny block mb-2" style={{ color: 'var(--label-color)' }}>{t('booking.yourName')}</label>
                <input className="input-bare" placeholder={t('booking.namePh')} value={details.name} onChange={(e) => setDetails({...details, name: e.target.value})} />
              </div>
              <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div>
                  <label className="label-tiny block mb-2" style={{ color: 'var(--label-color)' }}>{t('booking.email')}</label>
                  <input className="input-bare" type="email" placeholder={t('booking.emailPh')} value={details.email} onChange={(e) => setDetails({...details, email: e.target.value})} />
                </div>
                <div>
                  <label className="label-tiny block mb-2" style={{ color: 'var(--label-color)' }}>{t('booking.phone')}</label>
                  <input className="input-bare" placeholder={t('booking.phonePh')} value={details.phone} onChange={(e) => setDetails({...details, phone: e.target.value})} />
                </div>
              </div>
              <div>
                <label className="label-tiny block mb-2" style={{ color: 'var(--label-color)' }}>{t('booking.notes')}</label>
                <input className="input-bare" placeholder={t('booking.notesPh')} value={details.notes} onChange={(e) => setDetails({...details, notes: e.target.value})} />
              </div>
              {/* Summary */}
              <div className="mt-4 p-5 rounded" style={{ background: 'rgba(42,36,27,0.04)' }}>
                <div className="label-tiny mb-3" style={{ color: 'var(--label-color)' }}>{t('booking.summary')}</div>
                <div className="grid grid-cols-2 gap-y-2 text-sm">
                  <div style={{ color: 'var(--ink-soft)' }}>{t('booking.service')}</div>
                  <div className="font-display text-right">{serviceName(service)}</div>
                  <div style={{ color: 'var(--ink-soft)' }}>{t('booking.date')}</div>
                  <div className="font-display text-right">{fmtDate(date)}</div>
                  <div style={{ color: 'var(--ink-soft)' }}>{t('booking.time')}</div>
                  <div className="font-display text-right">{time}</div>
                  <div style={{ color: 'var(--ink-soft)' }}>{t('booking.total')}</div>
                  <div className="font-display text-right">{service?.price}</div>
                </div>
              </div>
            </div>
          )}

          {step === 4 && (
            <div className="text-center py-8">
              <div className="mx-auto mb-6 flex items-center justify-center" style={{ width: 64, height: 64, borderRadius: '50%', background: 'var(--accent)', color: 'var(--cream)' }}>
                <Icon.Check size={28} />
              </div>
              <div className="font-display mb-3" style={{ fontSize: '2.25rem', lineHeight: 1 }}>
                {t('booking.seeYou1')} <em style={{ color: 'var(--accent-deep)', fontWeight: 300 }}>{fmtWeekday(date)}</em>{t('booking.seeYou2')}
              </div>
              <p className="text-sm mb-6" style={{ color: 'var(--ink-soft)', maxWidth: 380, margin: '0 auto 24px' }}>
                {(() => {
                  const raw = t('booking.confirmBody');
                  const parts = raw.split('{email}');
                  return (
                    <>
                      {parts[0]}
                      <strong style={{ color: 'var(--ink)' }}>{details.email}</strong>
                      {parts[1]}
                    </>
                  );
                })()}
              </p>
              <div className="p-5 rounded text-left max-w-sm mx-auto" style={{ background: 'rgba(42,36,27,0.04)' }}>
                <div className="font-display mb-2" style={{ fontSize: '1.125rem' }}>{serviceName(service)}</div>
                <div className="text-sm" style={{ color: 'var(--ink-soft)' }}>{fmtDate(date)} · {time} · {service?.price}</div>
              </div>
            </div>
          )}
        </div>

        {/* Footer actions */}
        <div className="px-7 md:px-10 py-5 flex items-center justify-between border-t" style={{ borderColor: 'rgba(42,36,27,0.12)' }}>
          {step < 4 ? (
            <>
              <button className="btn-ghost" onClick={step === 0 ? onClose : back}>
                ← {step === 0 ? t('booking.cancel') : t('booking.back')}
              </button>
              <button className="btn-primary" disabled={!canNext} onClick={next}>
                {step === 3 ? t('booking.confirm') : t('booking.cont')} <Icon.ArrowUpRight size={14} />
              </button>
            </>
          ) : (
            <>
              <div className="text-xs" style={{ color: 'var(--ink-soft)' }}>{t('booking.ref')} · TEFI-{Math.floor(1000 + Math.random()*9000)}</div>
              <button className="btn-primary" onClick={onClose}>{t('booking.done')}</button>
            </>
          )}
        </div>
      </div>
    </div>
  );
}

function Calendar({ month, setMonth, avail, selected, onSelect, t, locale }) {
  const today = new Date(); today.setHours(0,0,0,0);
  const y = month.getFullYear(), m = month.getMonth();
  const first = new Date(y, m, 1);
  const startDay = (first.getDay() + 6) % 7;
  const daysInMonth = new Date(y, m + 1, 0).getDate();
  const monthName = first.toLocaleDateString(locale, { month: 'long', year: 'numeric' });

  const cells = [];
  for (let i = 0; i < startDay; i++) cells.push(null);
  for (let d = 1; d <= daysInMonth; d++) cells.push(new Date(y, m, d));

  const isSame = (a, b) => a && b && a.toDateString() === b.toDateString();
  const key = (d) => d.toISOString().slice(0,10);

  const canPrev = () => {
    const today2 = new Date(); today2.setDate(1); today2.setHours(0,0,0,0);
    return month > today2;
  };

  const weekDays = t('booking.weekDays');

  return (
    <div>
      <div className="flex items-center justify-between mb-5">
        <button
          onClick={() => canPrev() && setMonth(new Date(y, m - 1, 1))}
          className="opacity-60 hover:opacity-100 transition-opacity disabled:opacity-20"
          disabled={!canPrev()}
          aria-label="Previous month"
        >
          <Icon.ChevronLeft />
        </button>
        <div className="font-display" style={{ fontSize: '1.5rem', textTransform: 'capitalize' }}>{monthName}</div>
        <button onClick={() => setMonth(new Date(y, m + 1, 1))} className="opacity-60 hover:opacity-100 transition-opacity" aria-label="Next month">
          <Icon.ChevronRight />
        </button>
      </div>
      <div className="grid grid-cols-7 gap-1 mb-2 label-tiny" style={{ color: 'var(--ink-soft)' }}>
        {weekDays.map(d => (
          <div key={d} className="text-center py-2" style={{ fontSize: 10 }}>{d}</div>
        ))}
      </div>
      <div className="grid grid-cols-7 gap-1">
        {cells.map((d, i) => {
          if (!d) return <div key={`e${i}`} className="cal-day dim"></div>;
          const k = key(d);
          const info = avail[k];
          const past = d < today;
          const isToday = isSame(d, today);
          const isSel = isSame(d, selected);
          const open = info && info.open && !past;
          const allBooked = info && info.open && info.unavail && info.slots.every(s => info.unavail.has(s));
          const cls = past || !info?.open ? 'unavail' : (allBooked ? 'unavail' : 'avail');
          return (
            <div
              key={k}
              className={`cal-day ${cls} ${isSel ? 'selected' : ''} ${isToday ? 'today' : ''}`}
              onClick={() => open && !allBooked && onSelect(d)}
            >
              {d.getDate()}
            </div>
          );
        })}
      </div>
      <div className="flex items-center gap-5 mt-5 text-xs" style={{ color: 'var(--ink-soft)' }}>
        <div className="flex items-center gap-2"><span className="inline-block" style={{ width: 8, height: 8, borderRadius: '50%', background: 'var(--accent)' }}></span> {t('booking.legendToday')}</div>
        <div className="flex items-center gap-2"><span className="inline-block" style={{ width: 8, height: 8, borderRadius: 2, background: 'var(--ink)' }}></span> {t('booking.legendSelected')}</div>
        <div>{t('booking.legendClosed')}</div>
      </div>
    </div>
  );
}

function TimeSlots({ date, avail, selected, onSelect, t }) {
  const k = date.toISOString().slice(0,10);
  const info = avail[k];
  if (!info || !info.open) return <div>{t('booking.noAvail')}</div>;
  return (
    <div className="flex flex-wrap gap-2">
      {info.slots.map(s => {
        const taken = info.unavail && info.unavail.has(s);
        return (
          <button
            key={s}
            disabled={taken}
            className={`time-pill ${selected === s ? 'selected' : ''}`}
            onClick={() => !taken && onSelect(s)}
          >
            {s}{taken ? ` · ${t('booking.booked')}` : ''}
          </button>
        );
      })}
    </div>
  );
}

window.BookingModal = BookingModal;
