// Interactive Book-a-Tour multi-step modal
function TourModal({ open, onClose, programmeBias }) {
  const [step, setStep] = React.useState(0);
  const [data, setData] = React.useState({
    childAge: '',
    programme: programmeBias || '',
    visitType: 'in-person',
    date: '',
    time: '',
    parentName: '',
    email: '',
    phone: '',
    notes: '',
  });
  const [done, setDone] = React.useState(false);

  React.useEffect(() => {
    if (open) { setStep(0); setDone(false); if (programmeBias) setData(d => ({ ...d, programme: programmeBias })); }
  }, [open, programmeBias]);

  if (!open) return null;

  const update = (k, v) => setData(d => ({ ...d, [k]: v }));

  const ageBands = [
    { id: 'infants', label: 'Infants & Toddlers', sub: '9 months – 3 yrs' },
    { id: 'preKG',   label: 'Pre-KG',             sub: '3 – 4 yrs' },
    { id: 'kg1',     label: 'KG1',                sub: '4 – 5 yrs' },
    { id: 'kg2',     label: 'KG2',                sub: '5 – 6 yrs' },
  ];

  const dates = (() => {
    const out = []; const now = new Date();
    for (let i = 1; i <= 8; i++) { const d = new Date(now); d.setDate(now.getDate() + i); if (d.getDay() === 5 || d.getDay() === 6) continue; out.push(d); } // skip weekends (Fri/Sat UAE)
    return out;
  })();
  const fmtDate = (d) => d.toLocaleDateString('en-GB', { weekday: 'short', day: 'numeric', month: 'short' });
  const dateKey = (d) => d.toISOString().slice(0,10);

  const times = ['09:30', '10:30', '11:30', '13:30', '15:00'];

  const canNext = () => {
    if (step === 0) return data.programme;
    if (step === 1) return data.date && data.time;
    if (step === 2) return data.parentName && data.email && data.phone;
    return true;
  };

  const next = () => {
    if (step < 2) { setStep(step + 1); }
    else { setDone(true); }
  };

  const close = () => { onClose(); };

  return (
    <div className="modal-shade" onClick={close} role="dialog" aria-modal="true" aria-label="Book a tour">
      <div className="modal" onClick={e => e.stopPropagation()} style={{ position: 'relative' }}>
        <button className="modal-close" onClick={close} aria-label="Close"><Icon.X /></button>
        <aside className="modal-aside">
          <div>
            <div className="idea-rule" style={{ marginBottom: 16 }}><span/><span/><span/><span/></div>
            <h3 style={{ color: 'white', fontSize: 24 }}>Arrange a tour of IDEA ELC</h3>
            <p style={{ color: 'rgba(255,255,255,.75)', fontSize: 14, marginTop: 12 }}>
              The best way to feel our centre is to walk through it. Tours last about 45 minutes — meet a teacher, see classrooms, ask anything.
            </p>
          </div>
          <div style={{ display: 'grid', gap: 12, fontSize: 13, color: 'rgba(255,255,255,.7)' }}>
            <div style={{ display: 'flex', gap: 10 }}><Icon.Pin /> Victory Heights, DSC</div>
            <div style={{ display: 'flex', gap: 10 }}><Icon.Clock /> 45 min visit</div>
            <div style={{ display: 'flex', gap: 10 }}><Icon.Shield /> Safeguarding-compliant</div>
          </div>
        </aside>
        <div className="modal-body">
          {done ? (
            <div style={{ textAlign: 'center', padding: '24px 0' }}>
              <div style={{ width: 72, height: 72, margin: '0 auto 18px', borderRadius: '50%', background: '#E9F8E4', color: 'var(--c-green)', display: 'grid', placeItems: 'center' }}>
                <Icon.Check size={36} />
              </div>
              <h3>You're booked in — sort of.</h3>
              <p style={{ color: 'var(--ink-2)', maxWidth: 360, margin: '8px auto 0' }}>
                This is a design prototype, so nothing was sent. In production this would email <strong>admissions@ideaelc.ae</strong> and confirm to <strong>{data.email || 'you'}</strong>.
              </p>
              <div style={{ marginTop: 18, padding: 16, background: 'var(--cream)', borderRadius: 14, textAlign: 'left', fontSize: 14 }}>
                <div><strong>{data.parentName}</strong> · {ageBands.find(b => b.id === data.programme)?.label}</div>
                <div style={{ color: 'var(--ink-2)' }}>{data.date && new Date(data.date).toLocaleDateString('en-GB', { weekday: 'long', day: 'numeric', month: 'long' })} at {data.time}</div>
              </div>
              <div style={{ marginTop: 18, display: 'flex', gap: 10, justifyContent: 'center' }}>
                <a className="btn btn-wa" href="https://wa.me/971000000000?text=Hi%20IDEA%20ELC%2C%20I%27d%20like%20to%20confirm%20my%20tour" target="_blank" rel="noopener">
                  <Icon.Whatsapp size={16} /> Confirm on WhatsApp
                </a>
                <button className="btn btn-light" onClick={close}>Close</button>
              </div>
            </div>
          ) : (
            <>
              <div className="step-bar">
                {[0,1,2].map(i => <span key={i} className={i < step ? 'done' : i === step ? 'active' : ''} />)}
              </div>
              <div style={{ fontSize: 13, fontWeight: 700, color: 'var(--c-red)', letterSpacing: '0.1em', textTransform: 'uppercase' }}>Step {step + 1} of 3</div>
              {step === 0 && (
                <div>
                  <h3 style={{ marginTop: 6 }}>Tell us about your child</h3>
                  <p style={{ color: 'var(--ink-2)', fontSize: 14, margin: '6px 0 18px' }}>We'll match you with the right age group on the day.</p>
                  <div className="tile-radio">
                    {ageBands.map(b => (
                      <button key={b.id} className={data.programme === b.id ? 'selected' : ''} onClick={() => update('programme', b.id)}>
                        {b.label}<small>{b.sub}</small>
                      </button>
                    ))}
                  </div>
                  <div className="field" style={{ marginTop: 18 }}>
                    <label>Visit format</label>
                    <div className="tile-radio">
                      <button className={data.visitType === 'in-person' ? 'selected' : ''} onClick={() => update('visitType', 'in-person')}>
                        In-person tour<small>Walk through the centre</small>
                      </button>
                      <button className={data.visitType === 'virtual' ? 'selected' : ''} onClick={() => update('visitType', 'virtual')}>
                        Virtual call<small>Live video walk-through</small>
                      </button>
                    </div>
                  </div>
                </div>
              )}
              {step === 1 && (
                <div>
                  <h3 style={{ marginTop: 6 }}>Pick a day & time</h3>
                  <p style={{ color: 'var(--ink-2)', fontSize: 14, margin: '6px 0 18px' }}>Tours run mid-morning when classrooms are most active.</p>
                  <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(110px, 1fr))', gap: 8 }}>
                    {dates.map(d => (
                      <button
                        key={dateKey(d)}
                        onClick={() => update('date', dateKey(d))}
                        style={{
                          padding: '12px 8px',
                          borderRadius: 12,
                          border: '1.5px solid ' + (data.date === dateKey(d) ? 'var(--c-red)' : 'var(--line)'),
                          background: data.date === dateKey(d) ? '#FFF5F4' : 'white',
                          fontWeight: 600,
                          fontSize: 13,
                          textAlign: 'center',
                        }}
                      >
                        {fmtDate(d)}
                      </button>
                    ))}
                  </div>
                  <div style={{ marginTop: 18, fontWeight: 700, fontSize: 13, marginBottom: 8 }}>Times available</div>
                  <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
                    {times.map(t => (
                      <button
                        key={t}
                        onClick={() => update('time', t)}
                        style={{
                          padding: '10px 16px',
                          borderRadius: 999,
                          border: '1.5px solid ' + (data.time === t ? 'var(--c-red)' : 'var(--line)'),
                          background: data.time === t ? '#FFF5F4' : 'white',
                          fontWeight: 700,
                          fontSize: 13,
                        }}
                      >{t}</button>
                    ))}
                  </div>
                </div>
              )}
              {step === 2 && (
                <div>
                  <h3 style={{ marginTop: 6 }}>Your details</h3>
                  <p style={{ color: 'var(--ink-2)', fontSize: 14, margin: '6px 0 18px' }}>We'll send your confirmation here.</p>
                  <div className="field"><label>Parent / guardian name</label>
                    <input type="text" value={data.parentName} onChange={e => update('parentName', e.target.value)} placeholder="Your full name" />
                  </div>
                  <div className="field-row">
                    <div className="field"><label>Email</label>
                      <input type="email" value={data.email} onChange={e => update('email', e.target.value)} placeholder="you@example.com" />
                    </div>
                    <div className="field"><label>Phone</label>
                      <input type="tel" value={data.phone} onChange={e => update('phone', e.target.value)} placeholder="+971 …" />
                    </div>
                  </div>
                  <div className="field"><label>Anything we should know? <span style={{ color: 'var(--muted)', fontWeight: 500 }}>(optional)</span></label>
                    <textarea rows="3" value={data.notes} onChange={e => update('notes', e.target.value)} placeholder="Allergies, languages spoken at home, questions…" />
                  </div>
                </div>
              )}
              <div style={{ marginTop: 24, display: 'flex', justifyContent: 'space-between', gap: 8 }}>
                <button className="btn btn-light btn-sm" onClick={() => step === 0 ? close() : setStep(step - 1)}>
                  {step === 0 ? 'Cancel' : 'Back'}
                </button>
                <button
                  className="btn btn-primary"
                  disabled={!canNext()}
                  style={{ opacity: canNext() ? 1 : 0.45, pointerEvents: canNext() ? 'auto' : 'none' }}
                  onClick={next}
                >
                  {step === 2 ? 'Confirm tour request' : 'Continue'} <Icon.Arrow />
                </button>
              </div>
            </>
          )}
        </div>
      </div>
    </div>
  );
}
window.TourModal = TourModal;
