/* global React */
/* Multi-step booking form */
const DB = window.BVH_DATA;
const { useState: useStateB, useEffect: useEffectB } = React;

function BookPage({ setRoute, location, setLocation, prefillService }) {
  const [step, setStep] = useStateB(0);
  const [form, setForm] = useStateB({
    urgency: '',
    petType: '',
    petName: '',
    petAge: '',
    sex: '',
    location: location,
    service: prefillService || '',
    preferredDate: '',
    preferredTime: '',
    ownerName: '',
    phone: '',
    email: '',
    notes: '',
    contactMethod: 'whatsapp',
  });
  const [errors, setErrors] = useStateB({});

  useEffectB(() => { setForm(f => ({...f, location})); }, [location]);

  const update = (k, v) => { setForm(f => ({...f, [k]: v})); setErrors(e => ({...e, [k]: null})); };

  const steps = [
    { id: 0, label: 'About your pet' },
    { id: 1, label: 'Reason for visit' },
    { id: 2, label: 'Time & place' },
    { id: 3, label: 'Your contact' },
    { id: 4, label: 'Confirm' },
  ];

  function validateStep(s) {
    const e = {};
    if (s === 0) {
      if (!form.petType) e.petType = 'Pick a species';
      if (!form.petName) e.petName = 'Pet name needed';
    }
    if (s === 1) {
      if (!form.urgency) e.urgency = 'Tell us how urgent';
      if (!form.service) e.service = 'Pick a reason';
    }
    if (s === 2) {
      if (!form.location) e.location = 'Pick a location';
      if (!form.preferredDate) e.preferredDate = 'Pick a preferred day';
    }
    if (s === 3) {
      if (!form.ownerName) e.ownerName = 'Your name';
      if (!form.phone || form.phone.length < 7) e.phone = 'Mobile number needed';
      if (form.email && !/.+@.+\..+/.test(form.email)) e.email = 'Invalid email';
    }
    setErrors(e);
    return Object.keys(e).length === 0;
  }

  function next() {
    if (validateStep(step)) setStep(s => Math.min(steps.length-1, s+1));
  }
  function back() { setStep(s => Math.max(0, s-1)); }

  if (form.urgency === 'now' && step <= 1) {
    return (
      <div className="page-enter">
        <section className="section" style={{background:'var(--emergency)', color:'#fff'}}>
          <div className="wrap">
            <div style={{maxWidth:780}}>
              <div className="eyebrow" style={{color:'rgba(255,255,255,.7)'}}><span className="num" style={{color:'#fff'}}>!</span>EMERGENCY — DO NOT FILL A FORM</div>
              <h1 className="display" style={{fontSize:'clamp(48px, 6vw, 80px)', margin:'18px 0 24px', color:'#fff'}}>
                Please call — <em style={{color:'#FCE4DD'}}>now.</em>
              </h1>
              <p style={{fontSize:18, lineHeight:1.5, color:'rgba(255,255,255,.85)', maxWidth:'48ch', marginBottom:32}}>
                If this is an emergency, do not wait for a form confirmation. Pick up the phone — we'll triage on the call and prepare the team while you drive.
              </p>
              <div style={{display:'flex', gap:12, flexWrap:'wrap'}}>
                <a className="btn btn-lg" style={{background:'#fff', color:'var(--emergency)'}} href={`tel:${DB.hospital.phoneMain.replace(/\s/g,'')}`}>
                  Call {DB.hospital.phoneMain}
                </a>
                <a className="btn btn-lg btn-whatsapp" href={DB.hospital.waLink}>
                  WhatsApp {DB.hospital.whatsapp}
                </a>
                <button className="btn btn-lg btn-ghost" style={{borderColor:'rgba(255,255,255,.4)', color:'#fff'}} onClick={() => update('urgency','')}>
                  Back to booking →
                </button>
              </div>
            </div>
          </div>
        </section>
      </div>
    );
  }

  // success
  if (step === 5) {
    const svc = DB.services.find(s => s.id === form.service);
    const loc = DB.locations.find(l => l.id === form.location);
    return (
      <div className="page-enter">
        <section className="section">
          <div className="wrap" style={{maxWidth:820}}>
            <div style={{textAlign:'center', padding:'40px 0'}}>
              <div style={{width:64, height:64, borderRadius:100, background:'var(--success)', color:'#fff', display:'inline-grid', placeItems:'center', fontSize:30, marginBottom:24}}>✓</div>
              <div className="eyebrow"><span className="num">06</span>REQUEST RECEIVED</div>
              <h1 className="display" style={{fontSize:'clamp(48px, 6vw, 80px)', margin:'18px 0 24px'}}>
                Thank you, <em>{form.ownerName.split(' ')[0] || 'friend'}.</em>
              </h1>
              <p className="lede" style={{margin:'0 auto'}}>
                We've received the request for <strong style={{color:'var(--ink)'}}>{form.petName}</strong>. A team member from {loc?.short} will WhatsApp you within an hour during opening hours to confirm a time.
              </p>
            </div>

            <div style={{background:'var(--paper)', border:'1px solid var(--line-strong)', padding:32, borderRadius:6}}>
              <div className="creds" style={{marginBottom:18}}>BOOKING — DRAFT REF. BVH-{Math.random().toString(36).slice(2,8).toUpperCase()}</div>
              <div style={{display:'grid', gridTemplateColumns:'1fr 1fr', gap:16}}>
                <Row k="Pet" v={`${form.petName} (${form.petType}${form.petAge?', '+form.petAge:''})`} />
                <Row k="Service" v={svc?.name || '—'} />
                <Row k="Location" v={loc?.name || '—'} />
                <Row k="Preferred date" v={form.preferredDate} />
                <Row k="Preferred time" v={form.preferredTime || 'Any'} />
                <Row k="Confirm by" v={form.contactMethod === 'whatsapp' ? 'WhatsApp' : form.contactMethod === 'phone' ? 'Phone call' : 'Email'} />
              </div>
            </div>

            <div style={{textAlign:'center', marginTop:32, display:'flex', gap:10, justifyContent:'center'}}>
              <button className="btn btn-primary" onClick={() => setRoute("home")}>Back to homepage →</button>
              <a className="btn btn-ghost" href={DB.hospital.waLink}>Open WhatsApp now</a>
            </div>
          </div>
        </section>
      </div>
    );
  }

  return (
    <div className="page-enter">
      <section className="section" style={{paddingBottom:0}}>
        <div className="wrap" style={{maxWidth:980}}>
          <div className="section-head" style={{marginBottom:32}}>
            <div>
              <div className="eyebrow"><span className="num">06</span>BOOK AN APPOINTMENT</div>
              <h1 className="display" style={{fontSize:'clamp(44px, 5.5vw, 72px)'}}>Tell us a little<br/>about your <em>patient.</em></h1>
            </div>
            <div>
              <p className="lede">
                Five short steps. We'll confirm by WhatsApp within an hour during opening hours. If anything is urgent, please call <a href={`tel:${DB.hospital.phoneMain.replace(/\s/g,'')}`} style={{textDecoration:'underline'}}>{DB.hospital.phoneMain}</a> — don't wait for a form confirmation.
              </p>
            </div>
          </div>

          <div className="steps">
            {steps.map(s => (
              <div key={s.id} className={`step ${step===s.id?'active':step>s.id?'done':''}`}>
                <span className="num">{String(s.id+1).padStart(2,'0')}</span>{s.label}
              </div>
            ))}
          </div>
        </div>
      </section>

      <section className="section" style={{paddingTop:32}}>
        <div className="wrap" style={{maxWidth:780}}>

          {step === 0 && (
            <div>
              <div className="eyebrow" style={{marginBottom:12}}>STEP 01 — ABOUT YOUR PET</div>
              <h3 style={{fontFamily:'var(--font-display)', fontSize:32, fontWeight:500, margin:'0 0 24px'}}>Who are we seeing?</h3>

              <div className="field" style={{marginBottom:20}}>
                <label>SPECIES</label>
                <div className="chips">
                  {['Dog','Cat','Rabbit','Bird','Exotic'].map(t => (
                    <button key={t} className={`chip ${form.petType===t?'active':''}`} onClick={() => update('petType', t)}>{t}</button>
                  ))}
                </div>
                {errors.petType && <span className="err">{errors.petType}</span>}
              </div>

              <div className="form-grid">
                <div className={`field ${errors.petName?'error':''}`}>
                  <label>PET NAME</label>
                  <input value={form.petName} onChange={e => update('petName', e.target.value)} placeholder="e.g. Biscuit" />
                  {errors.petName && <span className="err">{errors.petName}</span>}
                </div>
                <div className="field">
                  <label>AGE (OPTIONAL)</label>
                  <input value={form.petAge} onChange={e => update('petAge', e.target.value)} placeholder="e.g. 4 years, 6 months" />
                </div>
                <div className="field">
                  <label>SEX (OPTIONAL)</label>
                  <div className="chips">
                    {['Male','Male neutered','Female','Female spayed','Unsure'].map(t => (
                      <button key={t} className={`chip ${form.sex===t?'active':''}`} onClick={() => update('sex', t)}>{t}</button>
                    ))}
                  </div>
                </div>
              </div>
            </div>
          )}

          {step === 1 && (
            <div>
              <div className="eyebrow" style={{marginBottom:12}}>STEP 02 — REASON FOR VISIT</div>
              <h3 style={{fontFamily:'var(--font-display)', fontSize:32, fontWeight:500, margin:'0 0 24px'}}>How urgent is this?</h3>

              <div className="field" style={{marginBottom:24}}>
                <label>URGENCY</label>
                <div style={{display:'grid', gridTemplateColumns:'1fr 1fr 1fr', gap:10}}>
                  {[
                    { k:'now',     t:'Right now', d:'Emergency — accident, sudden illness', em:true },
                    { k:'this-week', t:'This week', d:'Worrying but not urgent — soonest available' },
                    { k:'routine',  t:'Routine', d:'Check-up, vaccines, dental — any convenient slot' },
                  ].map(u => (
                    <button
                      key={u.k}
                      onClick={() => update('urgency', u.k)}
                      style={{
                        textAlign:'left',
                        padding:'18px 20px',
                        border:'1px solid '+(form.urgency===u.k?(u.em?'var(--emergency)':'var(--vet)'):'var(--line-strong)'),
                        background: form.urgency===u.k?(u.em?'rgba(200,71,47,.06)':'rgba(30,42,120,.04)'):'var(--paper)',
                        borderRadius:6,
                        cursor:'pointer',
                      }}
                    >
                      <div style={{display:'flex', alignItems:'center', gap:8, marginBottom:4}}>
                        {u.em && <span className="dot dot-pulse" style={{color:'var(--emergency)'}}></span>}
                        <span style={{fontWeight:500, fontSize:16, color: u.em?'var(--emergency)':'var(--ink)'}}>{u.t}</span>
                      </div>
                      <div style={{fontSize:12, color:'var(--slate)'}}>{u.d}</div>
                    </button>
                  ))}
                </div>
                {errors.urgency && <span className="err">{errors.urgency}</span>}
              </div>

              <div className={`field ${errors.service?'error':''}`}>
                <label>REASON</label>
                <div className="chips">
                  {DB.services.map(s => (
                    <button key={s.id} className={`chip ${form.service===s.id?'active':''}`} onClick={() => update('service', s.id)}>{s.name}</button>
                  ))}
                </div>
                {errors.service && <span className="err">{errors.service}</span>}
              </div>

              <div className="field" style={{marginTop:20}}>
                <label>ANYTHING WE SHOULD KNOW (OPTIONAL)</label>
                <textarea rows={4} value={form.notes} onChange={e => update('notes', e.target.value)} placeholder="Symptoms, when they started, current medications, anxieties at the vet…" />
              </div>
            </div>
          )}

          {step === 2 && (
            <div>
              <div className="eyebrow" style={{marginBottom:12}}>STEP 03 — TIME & PLACE</div>
              <h3 style={{fontFamily:'var(--font-display)', fontSize:32, fontWeight:500, margin:'0 0 24px'}}>When and where?</h3>

              <div className="field" style={{marginBottom:20}}>
                <label>LOCATION</label>
                <div style={{display:'grid', gridTemplateColumns:'1fr 1fr', gap:10}}>
                  {DB.locations.map(l => (
                    <button
                      key={l.id}
                      onClick={() => { update('location', l.id); setLocation(l.id); }}
                      style={{
                        textAlign:'left',
                        padding:'16px 18px',
                        border:'1px solid '+(form.location===l.id?'var(--vet)':'var(--line-strong)'),
                        background: form.location===l.id?'rgba(30,42,120,.04)':'var(--paper)',
                        borderRadius:6,
                        cursor:'pointer',
                      }}
                    >
                      <div className="creds" style={{color: form.location===l.id?'var(--vet)':'var(--slate)', marginBottom:6}}>{l.isFlagship?'FLAGSHIP HOSPITAL':'NEIGHBOURHOOD CLINIC'}</div>
                      <div style={{fontFamily:'var(--font-display)', fontSize:20, fontWeight:500, marginBottom:4}}>{l.name}</div>
                      <div style={{fontSize:12, color:'var(--slate)'}}>{l.addressLine1}<br/>{l.hoursLine}</div>
                    </button>
                  ))}
                </div>
              </div>

              <div className="form-grid">
                <div className={`field ${errors.preferredDate?'error':''}`}>
                  <label>PREFERRED DATE</label>
                  <input type="date" value={form.preferredDate} onChange={e => update('preferredDate', e.target.value)} />
                  {errors.preferredDate && <span className="err">{errors.preferredDate}</span>}
                </div>
                <div className="field">
                  <label>TIME OF DAY</label>
                  <div className="chips">
                    {['Morning','Afternoon','Evening','Any'].map(t => (
                      <button key={t} className={`chip ${form.preferredTime===t?'active':''}`} onClick={() => update('preferredTime', t)}>{t}</button>
                    ))}
                  </div>
                </div>
              </div>
            </div>
          )}

          {step === 3 && (
            <div>
              <div className="eyebrow" style={{marginBottom:12}}>STEP 04 — YOUR CONTACT</div>
              <h3 style={{fontFamily:'var(--font-display)', fontSize:32, fontWeight:500, margin:'0 0 24px'}}>How can we reach you?</h3>

              <div className="form-grid">
                <div className={`field ${errors.ownerName?'error':''}`}>
                  <label>YOUR NAME</label>
                  <input value={form.ownerName} onChange={e => update('ownerName', e.target.value)} />
                  {errors.ownerName && <span className="err">{errors.ownerName}</span>}
                </div>
                <div className={`field ${errors.phone?'error':''}`}>
                  <label>MOBILE NUMBER</label>
                  <input value={form.phone} onChange={e => update('phone', e.target.value)} placeholder="+971 …" />
                  {errors.phone && <span className="err">{errors.phone}</span>}
                </div>
                <div className={`field ${errors.email?'error':''}`} style={{gridColumn:'span 2'}}>
                  <label>EMAIL (OPTIONAL)</label>
                  <input value={form.email} onChange={e => update('email', e.target.value)} type="email" />
                  {errors.email && <span className="err">{errors.email}</span>}
                </div>
              </div>

              <div className="field" style={{marginTop:20}}>
                <label>CONFIRM MY BOOKING BY</label>
                <div className="chips">
                  {[{k:'whatsapp',t:'WhatsApp'},{k:'phone',t:'Phone call'},{k:'email',t:'Email'}].map(c => (
                    <button key={c.k} className={`chip ${form.contactMethod===c.k?'active':''}`} onClick={() => update('contactMethod', c.k)}>{c.t}</button>
                  ))}
                </div>
              </div>
            </div>
          )}

          {step === 4 && (
            <BookingReview form={form} />
          )}

          <div style={{display:'flex', justifyContent:'space-between', marginTop:48, paddingTop:24, borderTop:'1px solid var(--line)'}}>
            <button className="btn btn-ghost" onClick={back} disabled={step===0} style={{opacity: step===0?.4:1}}>
              ← Back
            </button>
            <div style={{display:'flex', gap:10}}>
              {step === 4 ? (
                <button className="btn btn-primary btn-lg" onClick={() => setStep(5)}>
                  Confirm booking →
                </button>
              ) : (
                <button className="btn btn-primary" onClick={next}>
                  Continue →
                </button>
              )}
            </div>
          </div>
        </div>
      </section>
    </div>
  );
}

function Row({ k, v }) {
  return (
    <div style={{padding:'10px 0', borderBottom:'1px dashed var(--line)'}}>
      <div className="creds" style={{marginBottom:4}}>{k.toUpperCase()}</div>
      <div style={{fontSize:15}}>{v}</div>
    </div>
  );
}

function BookingReview({ form }) {
  const svc = DB.services.find(s => s.id === form.service);
  const loc = DB.locations.find(l => l.id === form.location);
  return (
    <div>
      <div className="eyebrow" style={{marginBottom:12}}>STEP 05 — REVIEW</div>
      <h3 style={{fontFamily:'var(--font-display)', fontSize:32, fontWeight:500, margin:'0 0 24px'}}>Does this look right?</h3>

      <div style={{background:'var(--paper)', border:'1px solid var(--line-strong)', padding:'8px 24px', borderRadius:6}}>
        <Row k="Pet"             v={`${form.petName || '—'} · ${form.petType || '—'}${form.petAge?', '+form.petAge:''}${form.sex?', '+form.sex:''}`} />
        <Row k="Urgency"         v={form.urgency === 'now' ? '⚠ Right now' : form.urgency === 'this-week' ? 'This week' : 'Routine'} />
        <Row k="Reason"          v={svc?.name || '—'} />
        <Row k="Location"        v={loc?.name || '—'} />
        <Row k="Preferred date"  v={form.preferredDate || '—'} />
        <Row k="Preferred time"  v={form.preferredTime || 'Any'} />
        <Row k="Your name"       v={form.ownerName || '—'} />
        <Row k="Phone"           v={form.phone || '—'} />
        <Row k="Email"           v={form.email || '—'} />
        <Row k="Confirm by"      v={form.contactMethod === 'whatsapp' ? 'WhatsApp' : form.contactMethod === 'phone' ? 'Phone call' : 'Email'} />
        {form.notes && <Row k="Notes" v={form.notes} />}
      </div>

      <div style={{marginTop:20, padding:'14px 18px', background:'var(--sky)', borderRadius:6, fontSize:13, color:'var(--slate)', display:'flex', gap:10}}>
        <span style={{color:'var(--vet)'}}>✓</span>
        <span>By submitting, you agree we can contact you about this appointment. No prices are charged at booking — we'll share a per-case estimate before any treatment begins.</span>
      </div>
    </div>
  );
}

Object.assign(window, { BookPage });
