// Multi-step booking modal
const { useState: useStateBk, useEffect: useEffectBk, useMemo: useMemoBk } = React;

function BookingModal({ onClose, lang, prefillTopic }) {
  const [step, setStep] = useStateBk(0);
  const [picked, setPicked] = useStateBk(null);
  const [date, setDate] = useStateBk(null);
  const [time, setTime] = useStateBk(null);
  const [calMonth, setCalMonth] = useStateBk(() => {
    const d = new Date();
    return { y: d.getFullYear(), m: d.getMonth() };
  });
  const [form, setForm] = useStateBk({ name: '', email: '', phone: '', topic: prefillTopic || '' });

  // ESC close
  useEffectBk(() => {
    const h = (e) => { if (e.key === 'Escape') onClose(); };
    document.addEventListener('keydown', h);
    document.body.style.overflow = 'hidden';
    return () => { document.removeEventListener('keydown', h); document.body.style.overflow = ''; };
  }, [onClose]);

  const labels = lang === 'en'
    ? {
        title: 'Book a session',
        step1: 'Choose session', step2: 'Pick date & time', step3: 'Your details', step4: 'Confirmed',
        back: 'Back', next: 'Next', confirm: 'Confirm booking',
        name: 'Full name', email: 'Email', phone: 'Phone (with country code)', topic: 'What would you like to work on?',
        booked: 'See you then.', bookedSub: "You'll receive a calendar invite and meeting link by email.",
        callback: 'Our team will call you back shortly to confirm your booking.',
        ticketSession: 'Session', ticketDate: 'Date', ticketTime: 'Time', ticketName: 'Name', ticketRef: 'Ref',
        closeIt: 'Close',
        empty: 'Pick a date and time to continue'
      }
    : {
        title: 'സെഷൻ ബുക്ക് ചെയ്യൂ',
        step1: 'സെഷൻ തിരഞ്ഞെടുക്കൂ', step2: 'തീയതിയും സമയവും', step3: 'വിശദാംശങ്ങൾ', step4: 'സ്ഥിരീകരിച്ചു',
        back: 'പിന്നോട്ട്', next: 'അടുത്തത്', confirm: 'ബുക്കിംഗ് സ്ഥിരീകരിക്കൂ',
        name: 'പേര്', email: 'ഇമെയിൽ', phone: 'ഫോൺ (രാജ്യ കോഡ് സഹിതം)', topic: 'എന്തിൽ പ്രവർത്തിക്കണം?',
        booked: 'കാണാം.', bookedSub: 'ഇമെയിലിൽ കലണ്ടർ ക്ഷണവും മീറ്റിംഗ് ലിങ്കും ലഭിക്കും.',
        callback: 'ബുക്കിംഗ് സ്ഥിരീകരിക്കാൻ ഞങ്ങളുടെ ടീം ഉടൻ നിങ്ങളെ തിരികെ വിളിക്കും.',
        ticketSession: 'സെഷൻ', ticketDate: 'തീയതി', ticketTime: 'സമയം', ticketName: 'പേര്', ticketRef: 'റഫ്',
        closeIt: 'അടയ്ക്കൂ',
        empty: 'തുടരാൻ തീയതിയും സമയവും തിരഞ്ഞെടുക്കൂ'
      };

  const stepNames = [labels.step1, labels.step2, labels.step3, labels.step4];

  // Calendar
  const today = new Date(); today.setHours(0,0,0,0);
  const daysInMonth = new Date(calMonth.y, calMonth.m + 1, 0).getDate();
  const firstDow = new Date(calMonth.y, calMonth.m, 1).getDay();
  const monthName = new Date(calMonth.y, calMonth.m, 1).toLocaleString(lang === 'en' ? 'en' : 'ml', { month: 'long', year: 'numeric' });
  const dowLabels = lang === 'en' ? ['Su','Mo','Tu','We','Th','Fr','Sa'] : ['ഞാ','തി','ചൊ','ബു','വ്യാ','വെ','ശ'];

  const slots = ['10:00', '11:30', '14:00', '15:30', '17:00', '18:30', '20:00', '21:30'];

  const canStep1 = !!picked;
  const canStep2 = !!date && !!time;
  const canStep3 = form.name.trim() && form.email.includes('@') && form.phone.trim().length >= 6;

  const refCode = useMemoBk(() => 'JB-' + Math.random().toString(36).slice(2, 8).toUpperCase(), []);

  const dateStr = date ? new Date(date.y, date.m, date.d).toLocaleDateString(lang === 'en' ? 'en-IN' : 'ml-IN', { weekday: 'short', day: 'numeric', month: 'long', year: 'numeric' }) : '';

  return (
    <div className="modal-back" onClick={(e) => { if (e.target.classList.contains('modal-back')) onClose(); }}>
      <div className="modal" role="dialog" aria-modal="true">
        <div className="modal-head">
          <div>
            <div className="kicker" style={{ marginBottom: 6 }}>{step < 3 ? `${labels.title}` : labels.step4}</div>
            <div className="display">{stepNames[step]}</div>
          </div>
          <button className="modal-close" onClick={onClose} aria-label="Close">×</button>
        </div>

        {step < 3 && (
          <div className="step-bar">
            {[0,1,2].map((i) => (
              <div key={i} className={`step ${step === i ? 'cur' : ''} ${step > i ? 'done' : ''}`}/>
            ))}
          </div>
        )}

        <div className="modal-body">
          {step === 0 && (
            <div className="session-pick">
              {window.SESSION_TYPES.map((s) => (
                <label key={s.id} className={picked === s.id ? 'selected' : ''}>
                  <input type="radio" name="st" value={s.id} checked={picked === s.id} onChange={() => setPicked(s.id)}/>
                  <div>
                    <div className="st-t">{s.t}</div>
                    <div className="st-d">{s.d}</div>
                  </div>
                  <div>
                    <div className="st-p">{s.price}</div>
                    <div className="st-dur">{s.duration}</div>
                  </div>
                </label>
              ))}
            </div>
          )}

          {step === 1 && (
            <div>
              <div className="cal-nav">
                <button onClick={() => setCalMonth(prev => {
                  const m = prev.m - 1;
                  return m < 0 ? { y: prev.y - 1, m: 11 } : { y: prev.y, m };
                })}>‹</button>
                <div className="m">{monthName}</div>
                <button onClick={() => setCalMonth(prev => {
                  const m = prev.m + 1;
                  return m > 11 ? { y: prev.y + 1, m: 0 } : { y: prev.y, m };
                })}>›</button>
              </div>
              <div className="cal-grid">
                {dowLabels.map((d, i) => <div key={'h'+i} className="cal-dow">{d}</div>)}
                {Array.from({ length: firstDow }).map((_, i) => <div key={'e'+i} className="cal-day empty"/>)}
                {Array.from({ length: daysInMonth }, (_, i) => i + 1).map((d) => {
                  const dt = new Date(calMonth.y, calMonth.m, d);
                  const past = dt < today;
                  const isToday = dt.getTime() === today.getTime();
                  const sel = date && date.y === calMonth.y && date.m === calMonth.m && date.d === d;
                  return (
                    <button key={d} className={`cal-day ${sel ? 'selected' : ''} ${isToday ? 'today' : ''}`} disabled={past} onClick={() => setDate({ y: calMonth.y, m: calMonth.m, d })}>
                      {d}
                    </button>
                  );
                })}
              </div>
              <div className="kicker" style={{ marginTop: 8 }}>{lang === 'en' ? 'Times shown in IST · Pick a slot' : 'IST സമയം · ഒരു സ്ലോട്ട് തിരഞ്ഞെടുക്കൂ'}</div>
              <div className="time-grid">
                {slots.map((s) => (
                  <button key={s} className={`time-slot ${time === s ? 'selected' : ''}`} disabled={!date} onClick={() => setTime(s)}>
                    {s}
                  </button>
                ))}
              </div>
            </div>
          )}

          {step === 2 && (
            <div>
              <div className="form-row">
                <label>{labels.name}</label>
                <input value={form.name} onChange={(e) => setForm({ ...form, name: e.target.value })} required/>
              </div>
              <div className="form-row">
                <label>{labels.email}</label>
                <input type="email" value={form.email} onChange={(e) => setForm({ ...form, email: e.target.value })} required/>
              </div>
              <div className="form-row">
                <label>{labels.phone}</label>
                <input value={form.phone} onChange={(e) => setForm({ ...form, phone: e.target.value })} placeholder="+91 9876543210"/>
              </div>
              <div className="form-row">
                <label>{labels.topic}</label>
                <textarea value={form.topic} onChange={(e) => setForm({ ...form, topic: e.target.value })} placeholder={lang === 'en' ? 'A line or two about what you want to talk through.' : 'എന്താണ് സംസാരിക്കാൻ ആഗ്രഹിക്കുന്നതെന്ന് ഒരു വരി.'}/>
              </div>
            </div>
          )}

          {step === 3 && (
            <div className="confirm">
              <div className="confirm-check"><Check/></div>
              <h3>{labels.booked}</h3>
              <p>{labels.bookedSub}</p>
              <div className="callback-note">
                <span className="callback-icon" aria-hidden="true">
                  <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72c.13.96.36 1.9.7 2.81a2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45c.91.34 1.85.57 2.81.7A2 2 0 0 1 22 16.92z"/></svg>
                </span>
                <span>{labels.callback}</span>
              </div>
              <div className="ticket">
                <div className="ticket-row"><b>{labels.ticketRef}</b><span style={{ fontFamily: 'var(--mono)' }}>{refCode}</span></div>
                <div className="ticket-row"><b>{labels.ticketSession}</b><span>{window.SESSION_TYPES.find(s => s.id === picked)?.t}</span></div>
                <div className="ticket-row"><b>{labels.ticketDate}</b><span>{dateStr}</span></div>
                <div className="ticket-row"><b>{labels.ticketTime}</b><span>{time} IST</span></div>
                <div className="ticket-row"><b>{labels.ticketName}</b><span>{form.name}</span></div>
              </div>
            </div>
          )}
        </div>

        <div className="modal-foot">
          <div className="summary">
            {step === 0 && (picked ? window.SESSION_TYPES.find(s => s.id === picked)?.t : '—')}
            {step === 1 && (canStep2 ? `${dateStr} · ${time}` : labels.empty)}
            {step === 2 && (canStep3 ? '✓ ' + form.name : '—')}
            {step === 3 && refCode}
          </div>
          <div className="actions">
            {step > 0 && step < 3 && (
              <button className="btn btn-ghost" onClick={() => setStep(step - 1)}>{labels.back}</button>
            )}
            {step < 2 && (
              <button className="btn btn-primary" disabled={step === 0 ? !canStep1 : !canStep2} style={{ opacity: (step === 0 ? canStep1 : canStep2) ? 1 : 0.4 }} onClick={() => setStep(step + 1)}>
                {labels.next} <Arrow/>
              </button>
            )}
            {step === 2 && (
              <button className="btn btn-primary" disabled={!canStep3} style={{ opacity: canStep3 ? 1 : 0.4 }} onClick={() => setStep(3)}>
                {labels.confirm} <Arrow/>
              </button>
            )}
            {step === 3 && (
              <button className="btn btn-primary" onClick={onClose}>{labels.closeIt}</button>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}

window.BookingModal = BookingModal;
