// Multi-step booking flow
function BookingModal({ open, onClose }) {
  const [step, setStep] = React.useState(0);
  const [data, setData] = React.useState({
    location: '', specialty: '', doctor: '', date: '', time: '',
    name: '', phone: '', notes: '',
  });

  React.useEffect(() => {
    if (!open) {
      // reset on close (after animation)
      const t = setTimeout(() => {
        setStep(0);
        setData({ location: '', specialty: '', doctor: '', date: '', time: '', name: '', phone: '', notes: '' });
      }, 300);
      return () => clearTimeout(t);
    }
  }, [open]);

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

  if (!open) return null;

  const steps = ['Location', 'Specialty', 'Doctor', 'When', 'Your details'];
  const totalSteps = steps.length;

  const set = (k, v) => setData(d => ({ ...d, [k]: v }));
  const next = () => setStep(s => Math.min(s + 1, totalSteps));
  const back = () => setStep(s => Math.max(s - 1, 0));

  const canAdvance = (() => {
    if (step === 0) return !!data.location;
    if (step === 1) return !!data.specialty;
    if (step === 2) return !!data.doctor;
    if (step === 3) return !!data.date && !!data.time;
    if (step === 4) return data.name.trim().length > 1 && data.phone.trim().length >= 7;
    return false;
  })();

  return (
    <div style={{
      position: 'fixed', inset: 0, zIndex: 100,
      background: 'rgba(26,21,48,0.55)',
      display: 'grid', placeItems: 'center', padding: 24,
      animation: 'fadein 250ms var(--ease)',
    }} onClick={onClose}>
      <div onClick={e => e.stopPropagation()} style={{
        background: 'var(--bg-1)', borderRadius: 'var(--radius-xl)',
        maxWidth: 600, width: '100%',
        boxShadow: 'var(--shadow-lg)',
        animation: 'rise 300ms var(--ease)',
        overflow: 'hidden',
        maxHeight: '90vh', display: 'flex', flexDirection: 'column',
      }}>
        {/* Header */}
        <div style={{ padding: '24px 32px 0', display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
          <div>
            <div className="overline" style={{ marginBottom: 6 }}>Book an Appointment</div>
            <div style={{ font: 'var(--t-body-sm)', color: 'var(--fg-2)' }}>
              {step < totalSteps ? `Step ${step + 1} of ${totalSteps} · ${steps[step]}` : 'Confirmation'}
            </div>
          </div>
          <button onClick={onClose} aria-label="Close" style={{ background: 'transparent', border: 'none', padding: 8, cursor: 'pointer', color: 'var(--ink-700)', borderRadius: 9999 }}>
            <CloseIcon/>
          </button>
        </div>

        {/* Progress */}
        {step < totalSteps && (
          <div style={{ padding: '20px 32px 0', display: 'flex', gap: 6 }}>
            {steps.map((_, i) => (
              <div key={i} style={{ flex: 1, height: 3, borderRadius: 999,
                background: i <= step ? 'var(--violet-700)' : 'var(--hairline-cool)',
                transition: 'background var(--dur) var(--ease)' }}/>
            ))}
          </div>
        )}

        {/* Body */}
        <div style={{ padding: '24px 32px', overflowY: 'auto', flex: 1 }}>
          {step === 0 && <StepLocation data={data} set={set}/>}
          {step === 1 && <StepSpecialty data={data} set={set}/>}
          {step === 2 && <StepDoctor data={data} set={set}/>}
          {step === 3 && <StepWhen data={data} set={set}/>}
          {step === 4 && <StepDetails data={data} set={set}/>}
          {step === totalSteps && <StepConfirm data={data}/>}
        </div>

        {/* Footer */}
        {step < totalSteps && (
          <div style={{ padding: '16px 32px 24px', display: 'flex', gap: 12, justifyContent: 'space-between', borderTop: '1px solid var(--hairline-cool)' }}>
            <Button variant="ghost" onClick={step === 0 ? onClose : back}>
              {step === 0 ? 'Cancel' : '← Back'}
            </Button>
            <Button onClick={next} variant={canAdvance ? 'primary' : 'secondary'} >
              {step === totalSteps - 1 ? 'Submit Request' : 'Continue →'}
            </Button>
          </div>
        )}
        {step === totalSteps && (
          <div style={{ padding: '16px 32px 24px', display: 'flex', justifyContent: 'flex-end', borderTop: '1px solid var(--hairline-cool)' }}>
            <Button onClick={onClose}>Close</Button>
          </div>
        )}
      </div>
      <style>{`
        @keyframes fadein { from { opacity: 0; } to { opacity: 1; } }
        @keyframes rise { from { opacity: 0; transform: translateY(12px); } to { opacity: 1; transform: translateY(0); } }
      `}</style>
    </div>
  );
}

function ChoiceCard({ active, onClick, title, sub, icon }) {
  const [hover, setHover] = React.useState(false);
  return (
    <button onClick={onClick}
      onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)}
      style={{
        textAlign: 'left', cursor: 'pointer',
        background: active ? 'rgba(74,45,111,0.05)' : 'white',
        border: '1.5px solid ' + (active ? 'var(--violet-700)' : (hover ? 'var(--hairline-cool)' : 'var(--hairline)')),
        borderRadius: 'var(--radius-md)',
        padding: '14px 16px',
        display: 'flex', alignItems: 'center', gap: 14,
        transition: 'border-color var(--dur) var(--ease), background var(--dur) var(--ease)',
        width: '100%',
        fontFamily: 'var(--font-body)',
      }}>
      {icon && <div style={{ flex: '0 0 auto' }}>{icon}</div>}
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ font: 'var(--t-body)', fontWeight: 600, color: 'var(--ink-900)' }}>{title}</div>
        {sub && <div style={{ font: 'var(--t-body-sm)', color: 'var(--fg-2)', marginTop: 2 }}>{sub}</div>}
      </div>
      <div style={{
        width: 18, height: 18, borderRadius: '50%',
        border: `1.5px solid ${active ? 'var(--violet-700)' : 'var(--hairline)'}`,
        background: active ? 'var(--violet-700)' : 'transparent',
        display: 'grid', placeItems: 'center', flex: '0 0 auto',
      }}>
        {active && <div style={{ width: 6, height: 6, borderRadius: '50%', background: 'white' }}/>}
      </div>
    </button>
  );
}

function StepLocation({ data, set }) {
  return (
    <div>
      <h3 style={{ font: 'var(--t-h2)', color: 'var(--violet-700)', margin: '0 0 6px' }}>Which clinic?</h3>
      <p style={{ font: 'var(--t-body-sm)', color: 'var(--fg-2)', margin: '0 0 20px' }}>Choose the location closest to you.</p>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
        {LOCATIONS.map(l => (
          <ChoiceCard key={l.id}
            active={data.location === l.name}
            onClick={() => set('location', l.name)}
            title={l.name}
            sub={`${l.sub} · ${(l.addrLines || [l.addr]).join(', ')}`}
            icon={<div style={{ width: 36, height: 36, borderRadius: 10, background: 'var(--bg-soft)', display: 'grid', placeItems: 'center', color: 'var(--lavender-600)' }}><PinIcon size={16}/></div>}
          />
        ))}
      </div>
    </div>
  );
}

function StepSpecialty({ data, set }) {
  return (
    <div>
      <h3 style={{ font: 'var(--t-h2)', color: 'var(--violet-700)', margin: '0 0 6px' }}>What kind of consultation?</h3>
      <p style={{ font: 'var(--t-body-sm)', color: 'var(--fg-2)', margin: '0 0 20px' }}>Pick the specialty most relevant to your concern.</p>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 10 }} className="bk-grid-2">
        {SPECIALTIES.map(s => (
          <ChoiceCard key={s.id}
            active={data.specialty === s.name}
            onClick={() => set('specialty', s.name)}
            title={s.name}
            sub={s.tagline}
            icon={<div style={{ width: 36, height: 36, borderRadius: 10, background: s.family === 'teal' ? 'rgba(5,124,139,0.10)' : 'rgba(254,106,46,0.10)', display: 'grid', placeItems: 'center' }}><ConditionIcon name={s.conditions[0]} family={s.family} size={20}/></div>}
          />
        ))}
      </div>
      <style>{`@media (max-width: 540px){ .bk-grid-2 { grid-template-columns: 1fr !important; } }`}</style>
    </div>
  );
}

function StepDoctor({ data, set }) {
  // Filter doctors by specialty + chosen clinic.
  const list = DOCTORS.filter(d => {
    if (!d.locations.includes(data.location)) return false;
    if (data.specialty === 'Sleep Medicine') return d.specialty === 'Neurology';
    if (data.specialty === 'De-Addiction') return d.specialty === 'Psychiatry';
    return d.specialty === data.specialty;
  });
  return (
    <div>
      <h3 style={{ font: 'var(--t-h2)', color: 'var(--violet-700)', margin: '0 0 6px' }}>Pick a doctor</h3>
      <p style={{ font: 'var(--t-body-sm)', color: 'var(--fg-2)', margin: '0 0 20px' }}>Available at {data.location} for {data.specialty}.</p>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
        {list.length === 0 && (
          <div style={{ padding: 24, background: 'var(--bg-soft)', borderRadius: 12, color: 'var(--fg-2)', font: 'var(--t-body-sm)' }}>
            No matching specialist at this location. Please go back and pick another clinic.
          </div>
        )}
        <ChoiceCard active={data.doctor === 'Any'} onClick={() => set('doctor', 'Any')} title="Any available specialist"
          sub="Let our team assign the best fit."
          icon={<div style={{ width: 36, height: 36, borderRadius: 10, background: 'var(--bg-soft)', display: 'grid', placeItems: 'center', color: 'var(--lavender-600)', fontWeight: 700 }}>—</div>}/>
        {list.map(d => (
          <ChoiceCard key={d.id}
            active={data.doctor === d.name}
            onClick={() => set('doctor', d.name)}
            title={d.name}
            sub={`${d.role} · ${d.degrees}`}
            icon={<div style={{ width: 36, height: 36, borderRadius: '50%', background: d.g, flex: '0 0 auto', overflow: 'hidden', position: 'relative' }}>
              {d.photo && <img src={d.photo} alt="" style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', objectFit: 'cover' }}/>}
            </div>}
          />
        ))}
      </div>
    </div>
  );
}

function StepWhen({ data, set }) {
  // Generate next 7 days
  const days = Array.from({ length: 7 }).map((_, i) => {
    const d = new Date();
    d.setDate(d.getDate() + i + 1);
    const wd = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'][d.getDay()];
    const dom = d.getDate();
    const mo = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'][d.getMonth()];
    const closed = d.getDay() === 0; // Sunday
    return { key: `${dom}-${mo}`, wd, dom, mo, closed };
  });
  const slots = ['10:00 am', '11:30 am', '12:30 pm', '4:00 pm', '5:30 pm', '6:30 pm'];
  return (
    <div>
      <h3 style={{ font: 'var(--t-h2)', color: 'var(--violet-700)', margin: '0 0 6px' }}>When works for you?</h3>
      <p style={{ font: 'var(--t-body-sm)', color: 'var(--fg-2)', margin: '0 0 20px' }}>Times shown are tentative — our team will confirm the exact slot.</p>

      <div style={{ font: 11, fontWeight: 600, letterSpacing: '0.1em', textTransform: 'uppercase', color: 'var(--ink-700)', marginBottom: 10 }}>Date</div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(7, 1fr)', gap: 6, marginBottom: 22 }} className="bk-days">
        {days.map(d => {
          const active = data.date === d.key;
          return (
            <button key={d.key} disabled={d.closed} onClick={() => set('date', d.key)} style={{
              cursor: d.closed ? 'not-allowed' : 'pointer',
              background: active ? 'var(--violet-700)' : 'white',
              color: active ? 'white' : (d.closed ? 'var(--ink-300)' : 'var(--ink-900)'),
              border: `1px solid ${active ? 'var(--violet-700)' : 'var(--hairline)'}`,
              borderRadius: 12, padding: '10px 6px',
              fontFamily: 'var(--font-body)', textAlign: 'center',
              opacity: d.closed ? 0.5 : 1,
            }}>
              <div style={{ font: 'var(--t-caption)', opacity: 0.8 }}>{d.wd}</div>
              <div style={{ font: '600 18px/1.1 var(--font-body)', fontFeatureSettings: '"tnum"' }}>{d.dom}</div>
              <div style={{ font: 10, opacity: 0.7 }}>{d.mo}</div>
            </button>
          );
        })}
      </div>

      <div style={{ font: 11, fontWeight: 600, letterSpacing: '0.1em', textTransform: 'uppercase', color: 'var(--ink-700)', marginBottom: 10 }}>Time</div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 8 }} className="bk-times">
        {slots.map(s => {
          const active = data.time === s;
          return (
            <button key={s} onClick={() => set('time', s)} style={{
              cursor: 'pointer',
              background: active ? 'var(--violet-700)' : 'white',
              color: active ? 'white' : 'var(--ink-900)',
              border: `1px solid ${active ? 'var(--violet-700)' : 'var(--hairline)'}`,
              borderRadius: 9999, padding: '10px 6px',
              fontFamily: 'var(--font-body)', font: '500 14px/1 var(--font-body)', fontFeatureSettings: '"tnum"',
            }}>{s}</button>
          );
        })}
      </div>
      <style>{`
        @media (max-width: 540px) { .bk-days { grid-template-columns: repeat(4, 1fr) !important; } .bk-times { grid-template-columns: repeat(2, 1fr) !important; } }
      `}</style>
    </div>
  );
}

function StepDetails({ data, set }) {
  const inputStyle = {
    font: 'var(--t-body)', padding: '12px 14px',
    border: '1px solid var(--hairline)', borderRadius: 'var(--radius-md)',
    background: 'white', color: 'var(--ink-900)', outline: 'none',
    width: '100%', boxSizing: 'border-box', fontFamily: 'var(--font-body)',
  };
  return (
    <div>
      <h3 style={{ font: 'var(--t-h2)', color: 'var(--violet-700)', margin: '0 0 6px' }}>Your details</h3>
      <p style={{ font: 'var(--t-body-sm)', color: 'var(--fg-2)', margin: '0 0 20px' }}>So we know who to call.</p>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
        <Field label="Patient name">
          <input value={data.name} onChange={e => set('name', e.target.value)} required placeholder="Full name" style={inputStyle}/>
        </Field>
        <Field label="Mobile">
          <input value={data.phone} onChange={e => set('phone', e.target.value)} required placeholder="+91 ·· ····· ····" style={inputStyle}/>
        </Field>
        <Field label="Notes (optional)">
          <textarea value={data.notes} onChange={e => set('notes', e.target.value)} rows={3}
            placeholder="A few words about your concern" style={{...inputStyle, resize: 'vertical'}}/>
        </Field>
      </div>

      {/* Summary */}
      <div style={{
        marginTop: 22, background: 'var(--bg-soft)', borderRadius: 'var(--radius-md)', padding: 18,
        border: '1px solid var(--hairline-cool)',
      }}>
        <div className="overline" style={{ marginBottom: 10 }}>Booking summary</div>
        <SummaryRow label="Clinic" v={data.location}/>
        <SummaryRow label="Specialty" v={data.specialty}/>
        <SummaryRow label="Doctor" v={data.doctor}/>
        <SummaryRow label="When" v={`${data.date.replace('-', ' ')} · ${data.time}`}/>
      </div>
    </div>
  );
}

function SummaryRow({ label, v }) {
  return (
    <div style={{ display: 'flex', justifyContent: 'space-between', padding: '6px 0', font: 'var(--t-body-sm)' }}>
      <span style={{ color: 'var(--fg-2)' }}>{label}</span>
      <span style={{ color: 'var(--ink-900)', fontWeight: 500 }}>{v || '—'}</span>
    </div>
  );
}

function StepConfirm({ data }) {
  return (
    <div style={{ textAlign: 'center', padding: '32px 0 24px' }}>
      <div style={{ width: 64, height: 64, borderRadius: '50%', background: 'rgba(254,106,46,0.10)', display: 'inline-grid', placeItems: 'center', marginBottom: 20 }}>
        <img src="assets/icons/checkmark.svg" style={{ width: 36, height: 36 }} alt=""/>
      </div>
      <h3 style={{ font: 'var(--t-h2)', color: 'var(--violet-700)', margin: '0 0 10px' }}>Request received</h3>
      <p style={{ font: 'var(--t-body)', color: 'var(--fg-2)', margin: '0 0 24px', maxWidth: 380, marginInline: 'auto' }}>
        Our team will call <strong style={{ color: 'var(--ink-900)' }}>{data.phone || 'you'}</strong> within one working day to confirm your appointment at {data.location}.
      </p>
      <div style={{ background: 'var(--bg-soft)', borderRadius: 'var(--radius-md)', padding: 18, textAlign: 'left', maxWidth: 420, margin: '0 auto' }}>
        <SummaryRow label="Clinic" v={data.location}/>
        <SummaryRow label="Specialty" v={data.specialty}/>
        <SummaryRow label="Doctor" v={data.doctor}/>
        <SummaryRow label="When" v={`${data.date.replace('-', ' ')} · ${data.time}`}/>
        <SummaryRow label="Patient" v={data.name}/>
      </div>
    </div>
  );
}

function Field({ label, children }) {
  return (
    <label style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
      <span style={{ font: 11, fontFamily: 'var(--font-body)', fontWeight: 600, letterSpacing: '0.1em', textTransform: 'uppercase', color: 'var(--ink-700)' }}>{label}</span>
      {children}
    </label>
  );
}

window.BookingModal = BookingModal;
