// Enquiry modal — collects an enquiry (no direct booking) and emails the team
const { useState: useStateBk, useEffect: useEffectBk, useMemo: useMemoBk } = React;

function BookingModal({ onClose, lang, prefillTopic }) {
  // If opened from a specific "Bring Jishad to your stage" format, match it to
  // an interest so we can pre-select it and skip the "choose interest" step.
  const matchedInterest = (() => {
    const p = (prefillTopic || '').trim();
    if (!p) return null;
    return (window.SESSION_TYPES || []).find(s => s.t === p || p.includes(s.t) || s.t.includes(p)) || null;
  })();

  const [step, setStep] = useStateBk(matchedInterest ? 1 : 0);
  const [picked, setPicked] = useStateBk(matchedInterest ? matchedInterest.id : null);
  const [form, setForm] = useStateBk({ name: '', email: '', phone: '', topic: matchedInterest ? '' : (prefillTopic || '') });
  const [sending, setSending] = useStateBk(false);
  const [submitError, setSubmitError] = useStateBk('');
  const [hp, setHp] = useStateBk(''); // honeypot — must stay empty

  // 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: 'Enquiry',
        step1: 'What are you interested in?', step2: 'Your details', step3: 'Enquiry sent',
        back: 'Back', next: 'Next', confirm: 'Send enquiry',
        name: 'Full name', email: 'Email', phone: 'Phone (with country code)', topic: 'How can we help?',
        booked: 'Thank you!', bookedSub: 'Our team will contact you shortly.',
        callback: 'We usually get back within one working day.',
        ticketInterest: 'Interest', ticketName: 'Name', ticketRef: 'Ref',
        closeIt: 'Close',
        empty: 'Add your details to continue'
      }
    : {
        title: 'അന്വേഷണം',
        step1: 'എന്തിനെക്കുറിച്ചാണ് അന്വേഷണം?', step2: 'നിങ്ങളുടെ വിശദാംശങ്ങൾ', step3: 'അന്വേഷണം അയച്ചു',
        back: 'പിന്നോട്ട്', next: 'അടുത്തത്', confirm: 'അന്വേഷണം അയക്കൂ',
        name: 'പേര്', email: 'ഇമെയിൽ', phone: 'ഫോൺ (രാജ്യ കോഡ് സഹിതം)', topic: 'എങ്ങനെ സഹായിക്കാം?',
        booked: 'നന്ദി!', bookedSub: 'ഞങ്ങളുടെ ടീം ഉടൻ നിങ്ങളെ ബന്ധപ്പെടും.',
        callback: 'സാധാരണ ഒരു പ്രവൃത്തിദിവസത്തിനുള്ളിൽ ഞങ്ങൾ മറുപടി നൽകും.',
        ticketInterest: 'താൽപ്പര്യം', ticketName: 'പേര്', ticketRef: 'റഫ്',
        closeIt: 'അടയ്ക്കൂ',
        empty: 'തുടരാൻ വിശദാംശങ്ങൾ ചേർക്കൂ'
      };

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

  // Interest options = a general option + the speaking / session formats.
  const interestOptions = useMemoBk(() => {
    const general = lang === 'en'
      ? { id: 'general', t: 'General enquiry', d: 'Not sure yet — I just want to get in touch.' }
      : { id: 'general', t: 'പൊതു അന്വേഷണം', d: 'ഉറപ്പില്ല — വെറുതെ ബന്ധപ്പെടണം.' };
    return [general, ...(window.SESSION_TYPES || [])];
  }, [lang]);

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

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

  const interestName = (interestOptions.find(s => s.id === picked) || {}).t || '';

  // Send the enquiry to the server (send-booking.php → Resend), then show success.
  // Promise chain (not async/await) to stay safe under in-browser Babel.
  const submitEnquiry = () => {
    if (!canStep2 || sending) return;
    setSubmitError('');
    setSending(true);
    let httpOk = false;
    fetch('send-booking.php', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        name: form.name.trim(),
        email: form.email.trim(),
        phone: form.phone.trim(),
        topic: form.topic.trim(),
        interest: interestName,
        ref: refCode,
        company: hp, // honeypot
      }),
    })
      .then((res) => { httpOk = res.ok; return res.json().catch(() => ({})); })
      .then((data) => {
        if (!httpOk || !data.ok) {
          throw new Error(data.error || (lang === 'en' ? 'Something went wrong. Please try again.' : 'എന്തോ കുഴപ്പം. വീണ്ടും ശ്രമിക്കൂ.'));
        }
        setStep(2);
      })
      .catch((err) => {
        setSubmitError(err.message || (lang === 'en' ? 'Could not send. Please try again.' : 'അയക്കാനായില്ല. വീണ്ടും ശ്രമിക്കൂ.'));
      })
      .then(() => setSending(false));
  };

  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 }}>{labels.title}</div>
            <div className="display">{stepNames[step]}</div>
          </div>
          <button className="modal-close" onClick={onClose} aria-label="Close">×</button>
        </div>

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

        <div className="modal-body">
          {step === 0 && (
            <div className="session-pick">
              {interestOptions.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>
                  {(s.price || s.duration) && (
                    <div>
                      <div className="st-p">{s.price}</div>
                      <div className="st-dur">{s.duration}</div>
                    </div>
                  )}
                </label>
              ))}
            </div>
          )}

          {step === 1 && (
            <div>
              {picked && (
                <div style={{ display: 'inline-flex', alignItems: 'center', gap: 8, fontSize: 13, fontWeight: 700, color: 'var(--accent)', background: 'var(--paper)', border: '1px solid var(--line)', borderRadius: 999, padding: '7px 14px', marginBottom: 18 }}>
                  <span style={{ width: 7, height: 7, borderRadius: '50%', background: 'var(--accent)' }} />
                  {interestName}
                </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>
              {/* honeypot — hidden from people, bots tend to fill it */}
              <input type="text" name="company" tabIndex={-1} autoComplete="off" aria-hidden="true"
                value={hp} onChange={(e) => setHp(e.target.value)}
                style={{ position: 'absolute', left: '-9999px', width: 1, height: 1, opacity: 0 }}/>
            </div>
          )}

          {step === 2 && (
            <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.ticketInterest}</b><span>{interestName}</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 ? interestName : '—')}
            {step === 1 && (submitError
              ? <span style={{ color: '#E63946' }}>{submitError}</span>
              : (canStep2 ? '✓ ' + form.name : labels.empty))}
            {step === 2 && refCode}
          </div>
          <div className="actions">
            {step === 1 && (
              <button className="btn btn-ghost" onClick={() => setStep(0)}>{labels.back}</button>
            )}
            {step === 0 && (
              <button className="btn btn-primary" disabled={!canStep1} style={{ opacity: canStep1 ? 1 : 0.4 }} onClick={() => setStep(1)}>
                {labels.next} <Arrow/>
              </button>
            )}
            {step === 1 && (
              <button className="btn btn-primary" disabled={!canStep2 || sending} style={{ opacity: (canStep2 && !sending) ? 1 : 0.4 }} onClick={submitEnquiry}>
                {sending ? (lang === 'en' ? 'Sending…' : 'അയക്കുന്നു…') : <>{labels.confirm} <Arrow/></>}
              </button>
            )}
            {step === 2 && (
              <button className="btn btn-primary" onClick={onClose}>{labels.closeIt}</button>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}

window.BookingModal = BookingModal;
