// Booking.jsx · booking form tab with two modes:
//   1. Reserve a slot · full form with date/time/devices confirmation
//   2. Request more information · short form, routes to partnerships@reflective.global

const { useState } = React;

const ROLES = [
  'Principal or Head',
  'Deputy or Vice-principal',
  'Head of Academics',
  'Head of Department (Maths)',
  'Grade 6 or 7 Maths Teacher',
  'Other',
];

function generateSlots() {
  const today = new Date();
  const slots = [];
  let d = new Date(today);
  d.setDate(d.getDate() + 3);
  while (slots.length < 14) {
    const day = d.getDay();
    if (day !== 0 && day !== 6) slots.push(new Date(d));
    d.setDate(d.getDate() + 1);
  }
  return slots;
}
const DATE_FMT = { weekday: 'short', day: 'numeric', month: 'short' };
const DATE_VAL = (d) => d.toISOString().slice(0,10);

const RECAPTCHA_SITE_KEY = '6Le9KgktAAAAALZK62t9WADCOADCbcj875HIyFfE';

function getRecaptchaToken(action) {
  return new Promise((resolve, reject) => {
    function execute() {
      window.grecaptcha.execute(RECAPTCHA_SITE_KEY, { action }).then(resolve).catch(reject);
    }
    if (window.grecaptcha && window.grecaptcha.ready) {
      window.grecaptcha.ready(execute);
    } else {
      const iv = setInterval(() => {
        if (window.grecaptcha && window.grecaptcha.ready) {
          clearInterval(iv);
          window.grecaptcha.ready(execute);
        }
      }, 100);
    }
  });
}

// ---------- Reserve a slot ----------
function ReserveSlotForm() {
  const [submitted, setSubmitted] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [submitError, setSubmitError] = useState('');
  const [errors, setErrors] = useState({});
  const [form, setForm] = useState({
    firstName: '', surname: '', schoolName: '', role: ROLES[0],
    grade: '7', students: '',
    date: '', time: 'morning',
    devicesOk: false,
  });
  const slots = generateSlots();
  const set = (k, v) => setForm(f => ({ ...f, [k]: v }));

  function validate() {
    const e = {};
    if (!form.firstName.trim()) e.firstName = 'Required';
    if (!form.surname.trim()) e.surname = 'Required';
    if (!form.schoolName.trim()) e.schoolName = 'Required';
    if (!form.students || +form.students < 1) e.students = 'Enter a number';
    if (+form.students > 200) e.students = 'Max 200 per session';
    if (!form.date) e.date = 'Pick a date';
    if (!form.devicesOk) e.devicesOk = 'Please confirm';
    setErrors(e);
    return Object.keys(e).length === 0;
  }

  async function handleSubmit(ev) {
    ev.preventDefault();
    if (!validate()) return;
    setSubmitting(true);
    setSubmitError('');
    const slot = slots.find(s => DATE_VAL(s) === form.date);
    try {
      const captchaToken = await getRecaptchaToken('reserve');
      const res = await fetch('https://formspree.io/f/xykvrvpr', {
        method: 'POST',
        headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' },
        body: JSON.stringify({
          firstName: form.firstName,
          surname: form.surname,
          schoolName: form.schoolName,
          role: form.role,
          grade: form.grade,
          students: form.students,
          preferredDate: slot ? slot.toLocaleDateString('en-ZA', DATE_FMT) : form.date,
          preferredTime: form.time,
          devicesConfirmed: 'Yes',
          'g-recaptcha-response': captchaToken,
        }),
      });
      if (res.ok) {
        setSubmitted(true);
        if (typeof window !== 'undefined') window.scrollTo({ top: 0, behavior: 'smooth' });
      } else {
        const data = await res.json().catch(() => ({}));
        setSubmitError((data.errors || []).map(e => e.message).join(' ') || 'Something went wrong. Please try again.');
      }
    } catch {
      setSubmitError('Could not send your request. Please check your connection and try again.');
    } finally {
      setSubmitting(false);
    }
  }

  function reset() {
    setSubmitted(false); setErrors({}); setSubmitError('');
    setForm({ firstName: '', surname: '', schoolName: '', role: ROLES[0], grade: '7', students: '', date: '', time: 'morning', devicesOk: false });
  }

  if (submitted) {
    const slot = slots.find(s => DATE_VAL(s) === form.date);
    return (
      <div className="pb-form-shell pb-success">
        <div className="pb-success-check">
          <svg width="36" height="36" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.6" strokeLinecap="round" strokeLinejoin="round"><polyline points="20 6 9 17 4 12"/></svg>
        </div>
        <h3>You are booked in. We will be in touch shortly.</h3>
        <p>
          We have received your request to assess <strong style={{ color: 'var(--graphite-950, #1c1b2f)' }}>{form.students} Grade {form.grade} learners</strong> at <strong style={{ color: 'var(--graphite-950, #1c1b2f)' }}>{form.schoolName}</strong>{slot ? <>, with a preferred date of <strong style={{ color: 'var(--graphite-950, #1c1b2f)' }}>{slot.toLocaleDateString('en-ZA', DATE_FMT)} ({form.time})</strong></> : ''}. A member of the Numerate team will confirm the slot within one working day.
        </p>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 12, width: '100%', maxWidth: 600, margin: '8px 0 24px' }}>
          {[
            { h: '1. Confirmation', p: 'A confirmation email within one working day' },
            { h: '2. Logistics',    p: 'A short call to confirm date, devices and class size' },
            { h: '3. On the day',   p: 'Our facilitator arrives with everything needed' },
          ].map((s, i) => (
            <div key={i} style={{ padding: 16, background: 'var(--pb-beige)', borderRadius: 12, textAlign: 'left' }}>
              <p style={{ fontSize: 13, fontWeight: 600, color: 'var(--graphite-950, #1c1b2f)', margin: '0 0 4px' }}>{s.h}</p>
              <p style={{ fontSize: 12.5, lineHeight: 1.4, color: 'var(--text-tertiary, #475467)', margin: 0 }}>{s.p}</p>
            </div>
          ))}
        </div>
        <div style={{ display: 'flex', gap: 10 }}>
          <button className="pb-btn pb-btn-secondary" onClick={reset}>Book another school</button>
          <a className="pb-btn pb-btn-primary" href="#report" onClick={(e)=>{e.preventDefault(); window.__pbGoTab('report');}}>See what you will receive</a>
        </div>
      </div>
    );
  }

  return (
    <form className="pb-form-shell" onSubmit={handleSubmit} noValidate>
      <div className="pb-form-grid">
        <div className="pb-field">
          <label htmlFor="firstName">First name<span className="req">*</span></label>
          <input id="firstName" className={`pb-input ${errors.firstName ? 'invalid' : ''}`}
            value={form.firstName} onChange={e => set('firstName', e.target.value)} placeholder="Thandi"/>
          {errors.firstName && <span className="pb-error">{errors.firstName}</span>}
        </div>
        <div className="pb-field">
          <label htmlFor="surname">Surname<span className="req">*</span></label>
          <input id="surname" className={`pb-input ${errors.surname ? 'invalid' : ''}`}
            value={form.surname} onChange={e => set('surname', e.target.value)} placeholder="Mokoena"/>
          {errors.surname && <span className="pb-error">{errors.surname}</span>}
        </div>
        <div className="pb-field full">
          <label htmlFor="schoolName">School name<span className="req">*</span></label>
          <input id="schoolName" className={`pb-input ${errors.schoolName ? 'invalid' : ''}`}
            value={form.schoolName} onChange={e => set('schoolName', e.target.value)} placeholder="Greenfield Preparatory"/>
          {errors.schoolName && <span className="pb-error">{errors.schoolName}</span>}
        </div>
        <div className="pb-field full">
          <label htmlFor="role">Your role at the school<span className="req">*</span></label>
          <select id="role" className="pb-select" value={form.role} onChange={e => set('role', e.target.value)}>
            {ROLES.map(r => <option key={r}>{r}</option>)}
          </select>
        </div>

        <div className="pb-field">
          <label>Grade to be assessed<span className="req">*</span></label>
          <div className="pb-radio-group" role="radiogroup">
            {['6', '7'].map(g => (
              <label className={`pb-radio-pill ${form.grade === g ? 'is-active' : ''}`} key={g}>
                <input type="radio" name="grade" value={g} checked={form.grade === g} onChange={() => set('grade', g)}/>
                Grade {g}
              </label>
            ))}
          </div>
        </div>
        <div className="pb-field">
          <label htmlFor="students">Number of learners to assess<span className="req">*</span></label>
          <input id="students" type="number" inputMode="numeric" min="1" max="200"
            className={`pb-input ${errors.students ? 'invalid' : ''}`}
            value={form.students} onChange={e => set('students', e.target.value)} placeholder="e.g. 28"/>
          {errors.students ? <span className="pb-error">{errors.students}</span> :
            <span className="pb-help">One device per learner required</span>}
        </div>

        <div className="pb-field">
          <label htmlFor="date">Preferred date<span className="req">*</span></label>
          <select id="date" className={`pb-select ${errors.date ? 'invalid' : ''}`}
            value={form.date} onChange={e => set('date', e.target.value)}>
            <option value="">Choose a weekday...</option>
            {slots.map(s => (
              <option key={DATE_VAL(s)} value={DATE_VAL(s)}>
                {s.toLocaleDateString('en-ZA', DATE_FMT)}
              </option>
            ))}
          </select>
          {errors.date && <span className="pb-error">{errors.date}</span>}
        </div>
        <div className="pb-field">
          <label>Preferred time<span className="req">*</span></label>
          <div className="pb-radio-group" role="radiogroup">
            {[
              { v: 'morning',  l: 'Morning' },
              { v: 'midday',   l: 'Midday' },
              { v: 'afternoon', l: 'Afternoon' },
            ].map(t => (
              <label className={`pb-radio-pill ${form.time === t.v ? 'is-active' : ''}`} key={t.v}>
                <input type="radio" name="time" value={t.v} checked={form.time === t.v} onChange={() => set('time', t.v)}/>
                {t.l}
              </label>
            ))}
          </div>
        </div>

        <div className="pb-field full">
          <label className="pb-checkbox-row">
            <input type="checkbox" checked={form.devicesOk} onChange={e => set('devicesOk', e.target.checked)}/>
            <span>
              <strong>We have what we need.</strong> I confirm that our school has sufficient devices for a one-to-one learner ratio and a stable internet connection on the day of the assessment.
            </span>
          </label>
          {errors.devicesOk && <span className="pb-error" style={{ marginTop: 4 }}>{errors.devicesOk}</span>}
        </div>

        {submitError && (
          <div className="pb-field full">
            <p className="pb-error" style={{ fontSize: 13 }}>{submitError}</p>
          </div>
        )}

        <div className="pb-field full" style={{ marginTop: 4 }}>
          <button type="submit" className="pb-btn pb-btn-primary pb-btn-lg" style={{ width: '100%' }} disabled={submitting}>
            {submitting ? 'Sending…' : 'Send my booking request'}
          </button>
          <p className="pb-fine" style={{ marginTop: 12, textAlign: 'center' }}>
            Free of charge · No obligation · Your data is never shared with third parties
          </p>
        </div>
      </div>
    </form>
  );
}

// ---------- Request more information ----------
function MoreInfoForm() {
  const [submitted, setSubmitted] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [submitError, setSubmitError] = useState('');
  const [errors, setErrors] = useState({});
  const [form, setForm] = useState({
    firstName: '', surname: '', schoolName: '', role: ROLES[0], email: '', notes: '',
  });
  const set = (k, v) => setForm(f => ({ ...f, [k]: v }));

  function validate() {
    const e = {};
    if (!form.firstName.trim()) e.firstName = 'Required';
    if (!form.surname.trim()) e.surname = 'Required';
    if (!form.schoolName.trim()) e.schoolName = 'Required';
    if (!form.email.trim()) e.email = 'Required';
    else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.email.trim())) e.email = 'Enter a valid email';
    setErrors(e);
    return Object.keys(e).length === 0;
  }

  async function handleSubmit(ev) {
    ev.preventDefault();
    if (!validate()) return;
    setSubmitting(true);
    setSubmitError('');
    try {
      const captchaToken = await getRecaptchaToken('more_info');
      const res = await fetch('https://formspree.io/f/mojbgbnv', {
        method: 'POST',
        headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' },
        body: JSON.stringify({
          firstName: form.firstName,
          surname: form.surname,
          schoolName: form.schoolName,
          role: form.role,
          email: form.email,
          notes: form.notes,
          'g-recaptcha-response': captchaToken,
        }),
      });
      if (res.ok) {
        setSubmitted(true);
        if (typeof window !== 'undefined') window.scrollTo({ top: 0, behavior: 'smooth' });
      } else {
        const data = await res.json().catch(() => ({}));
        setSubmitError((data.errors || []).map(e => e.message).join(' ') || 'Something went wrong. Please try again.');
      }
    } catch {
      setSubmitError('Could not send your request. Please check your connection and try again.');
    } finally {
      setSubmitting(false);
    }
  }

  if (submitted) {
    return (
      <div className="pb-form-shell pb-success">
        <div className="pb-success-check">
          <svg width="36" height="36" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.6" strokeLinecap="round" strokeLinejoin="round"><polyline points="20 6 9 17 4 12"/></svg>
        </div>
        <h3>Thank you. We will be in touch within one working day.</h3>
        <p>
          A member of the Numerate team will email <strong style={{ color: 'var(--graphite-950, #1c1b2f)' }}>{form.email}</strong> to answer your questions and walk through what Project Baseline looks like for {form.schoolName}.
        </p>
        <p style={{ fontSize: 14, color: 'var(--text-tertiary, #475467)' }}>
          You can also reach us directly at <a href="mailto:partnerships@reflective.global" style={{ color: 'var(--insight-violet, #7C3AED)', fontWeight: 600 }}>partnerships@reflective.global</a>.
        </p>
      </div>
    );
  }

  return (
    <form className="pb-form-shell" onSubmit={handleSubmit} noValidate>
      <div className="pb-form-grid">
        <div className="pb-field">
          <label htmlFor="i-firstName">First name<span className="req">*</span></label>
          <input id="i-firstName" className={`pb-input ${errors.firstName ? 'invalid' : ''}`}
            value={form.firstName} onChange={e => set('firstName', e.target.value)} placeholder="Thandi"/>
          {errors.firstName && <span className="pb-error">{errors.firstName}</span>}
        </div>
        <div className="pb-field">
          <label htmlFor="i-surname">Surname<span className="req">*</span></label>
          <input id="i-surname" className={`pb-input ${errors.surname ? 'invalid' : ''}`}
            value={form.surname} onChange={e => set('surname', e.target.value)} placeholder="Mokoena"/>
          {errors.surname && <span className="pb-error">{errors.surname}</span>}
        </div>
        <div className="pb-field full">
          <label htmlFor="i-schoolName">School name<span className="req">*</span></label>
          <input id="i-schoolName" className={`pb-input ${errors.schoolName ? 'invalid' : ''}`}
            value={form.schoolName} onChange={e => set('schoolName', e.target.value)} placeholder="Greenfield Preparatory"/>
          {errors.schoolName && <span className="pb-error">{errors.schoolName}</span>}
        </div>
        <div className="pb-field">
          <label htmlFor="i-role">Your role<span className="req">*</span></label>
          <select id="i-role" className="pb-select" value={form.role} onChange={e => set('role', e.target.value)}>
            {ROLES.map(r => <option key={r}>{r}</option>)}
          </select>
        </div>
        <div className="pb-field">
          <label htmlFor="i-email">Email<span className="req">*</span></label>
          <input id="i-email" type="email" className={`pb-input ${errors.email ? 'invalid' : ''}`}
            value={form.email} onChange={e => set('email', e.target.value)} placeholder="you@school.co.za"/>
          {errors.email && <span className="pb-error">{errors.email}</span>}
        </div>
        <div className="pb-field full">
          <label htmlFor="i-notes">What would you like to know? <span className="pb-help" style={{ marginLeft: 4 }}>(optional)</span></label>
          <textarea id="i-notes" className="pb-input" rows="4"
            value={form.notes} onChange={e => set('notes', e.target.value)}
            placeholder="Any questions about the diagnostic, logistics, the report, or how Numerate might support your school..."
            style={{ resize: 'vertical', minHeight: 100, fontFamily: 'inherit' }}/>
        </div>
        {submitError && (
          <div className="pb-field full">
            <p className="pb-error" style={{ fontSize: 13 }}>{submitError}</p>
          </div>
        )}

        <div className="pb-field full" style={{ marginTop: 4 }}>
          <button type="submit" className="pb-btn pb-btn-primary pb-btn-lg" style={{ width: '100%' }} disabled={submitting}>
            {submitting ? 'Sending…' : 'Send my question'}
          </button>
          <p className="pb-fine" style={{ marginTop: 12, textAlign: 'center' }}>
            Or email us directly at <a href="mailto:partnerships@reflective.global" style={{ color: 'var(--insight-violet, #7C3AED)', fontWeight: 600 }}>partnerships@reflective.global</a>
          </p>
        </div>
      </div>
    </form>
  );
}

// ---------- Top-level Booking tab ----------
function Booking() {
  const [mode, setMode] = useState('book');
  return (
    <section className="pb-section" data-screen-label="Book your slot">
      <div className="pb-container-narrow">
        <div className="pb-section-head" style={{ marginBottom: 32, textAlign: 'center', maxWidth: 'none' }}>
          <div style={{ display: 'inline-flex', justifyContent: 'center', marginBottom: 18 }}>
            <ProjectBaselineMark size={56}/>
          </div>
          <span className="pb-eyebrow">{mode === 'book' ? 'Reserve your slot' : 'Have questions first?'}</span>
          <h2 className="pb-display-lg" style={{ marginTop: 12 }}>
            {mode === 'book' ? "Reserve your school's Grade 6 or 7 diagnostic." : 'Tell us what you would like to know.'}
          </h2>
          <p className="pb-lead" style={{ marginTop: 14, marginLeft: 'auto', marginRight: 'auto' }}>
            {mode === 'book'
              ? 'Phase 1 is limited to 25 schools nationally, with 13 slots remaining. Pick a preferred date and we will confirm within one working day.'
              : 'No pressure. A short note here will reach the Numerate team directly. We will get back to you with whatever you need.'}
          </p>

          <div className="pb-booking-toggle">
            <button className={`pb-booking-toggle-tab ${mode === 'book' ? 'is-active' : ''}`} onClick={() => setMode('book')}>
              <span className="pb-booking-toggle-num">1</span>
              <span className="pb-booking-toggle-text">
                <strong>Reserve a slot</strong>
                <span>Pick a date · we confirm in 24 hours</span>
              </span>
            </button>
            <button className={`pb-booking-toggle-tab ${mode === 'info' ? 'is-active' : ''}`} onClick={() => setMode('info')}>
              <span className="pb-booking-toggle-num">2</span>
              <span className="pb-booking-toggle-text">
                <strong>Get more information first</strong>
                <span>Ask a question · partnerships@reflective.global</span>
              </span>
            </button>
          </div>
        </div>

        {mode === 'book' ? <ReserveSlotForm/> : <MoreInfoForm/>}
      </div>
    </section>
  );
}

Object.assign(window, { Booking });
