// Inquiry / booking flow — multi-step form

const { useState: useStateI, useEffect: useEffectI } = React;
const FORMSPREE_ENDPOINT = 'https://formspree.io/f/xvkpldwo';

function Inquiry() {
  const [step, setStep] = useStateI(0);
  const [sending, setSending] = useStateI(false);
  const [sendError, setSendError] = useStateI(false);
  const [data, setData] = useStateI({
    interests: [], when: 'flexible', month: 'september', year: '2026', days: 9,
    travelers: 2, kids: 0, style: 'mid', budget: 7000,
    name: '', email: '', country: '', phone: '', notes: '',
    pace: 'balanced', accommodation: ['tented'], inspirations: []
  });
  const set = (k, v) => setData(d => ({ ...d, [k]: v }));
  const toggle = (k, v) => setData(d => ({ ...d, [k]: d[k].includes(v) ? d[k].filter(x => x !== v) : [...d[k], v] }));

  const steps = ['Dream', 'When', 'Who', 'Style', 'You'];
  const titles = [
    "What's calling you to Tanzania?",
    "When can you travel?",
    "Who's coming?",
    "How do you like to travel?",
    "Where should we send the draft?"
  ];

  useEffectI(() => { window.scrollTo({ top: 0, behavior: 'smooth' }); }, [step]);

  return (
    <main style={{ minHeight: '100vh', display: 'grid', gridTemplateColumns: '1fr 1fr' }}>
      <aside style={{
        background: 'var(--moss)', color: 'var(--bone)',
        padding: '80px 80px 60px',
        display: 'flex', flexDirection: 'column', justifyContent: 'space-between',
        position: 'sticky', top: 76, height: 'calc(100vh - 76px)'
      }} className="inquiry-aside">
        <div>
          <div className="eyebrow dark"><span className="dot"/>Plan your trip · Step {step+1} of {steps.length}</div>
          <h1 className="h-1" style={{ marginTop: 18, color: 'var(--bone)', fontSize: 'clamp(36px, 4vw, 60px)' }}>
            {titles[step]}
          </h1>
          <p style={{ marginTop: 20, color: 'rgba(244,239,230,0.75)', maxWidth: 420, fontSize: 16 }}>
            {step === 0 && "Pick the things that pull you — we'll build the trip around them."}
            {step === 1 && "Approximate is fine. We'll suggest the best windows for what you want to see."}
            {step === 2 && "Group composition shapes pacing, vehicles, and which camps we recommend."}
            {step === 3 && "Pacing, accommodation, and budget — be honest, we work with all three."}
            {step === 4 && "We'll respond within 24 hours with a draft itinerary. No charge, no template."}
          </p>
        </div>

        <div>
          <div style={{ display: 'flex', gap: 12, marginBottom: 24 }}>
            {steps.map((s, i) => (
              <div key={s} style={{ flex: 1 }}>
                <div style={{ height: 2, background: i <= step ? 'var(--sun)' : 'rgba(244,239,230,0.2)', transition: 'background 0.3s' }}/>
                <div className="mono" style={{
                  fontSize: 10, letterSpacing: '0.14em', textTransform: 'uppercase',
                  marginTop: 8, color: i <= step ? 'rgba(244,239,230,0.85)' : 'rgba(244,239,230,0.4)'
                }}>{String(i+1).padStart(2,'0')} {s}</div>
              </div>
            ))}
          </div>
          <p className="mono" style={{ fontSize: 11, color: 'rgba(244,239,230,0.5)', letterSpacing: '0.12em', textTransform: 'uppercase' }}>
            Free planning · No obligation · Reply &lt; 24h
          </p>
        </div>
      </aside>

      <section style={{ padding: '80px 80px 80px' }} className="inquiry-form">
        {step === 0 && <Step1 data={data} toggle={toggle} set={set}/>}
        {step === 1 && <Step2 data={data} set={set}/>}
        {step === 2 && <Step3 data={data} set={set}/>}
        {step === 3 && <Step4 data={data} set={set} toggle={toggle}/>}
        {step === 4 && <Step5 data={data} set={set}/>}

        {step < 4 ? (
          <div style={{ display: 'flex', gap: 12, marginTop: 48, paddingTop: 32, borderTop: '1px solid var(--line)' }}>
            {step > 0 && <button onClick={() => setStep(step-1)} className="btn btn-ghost">
              <Ico.Arrow style={{ transform: 'rotate(180deg)' }}/> Back
            </button>}
            <button onClick={() => setStep(step+1)} className="btn btn-primary" style={{ marginLeft: 'auto' }}>
              Continue <Ico.Arrow/>
            </button>
          </div>
        ) : (
          <div style={{ display: 'flex', gap: 12, marginTop: 48, paddingTop: 32, borderTop: '1px solid var(--line)' }}>
            <button onClick={() => setStep(step-1)} className="btn btn-ghost">
              <Ico.Arrow style={{ transform: 'rotate(180deg)' }}/> Back
            </button>
            <button disabled={sending} onClick={() => {
              setSending(true);
              setSendError(false);
              fetch(FORMSPREE_ENDPOINT, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
                body: JSON.stringify(data)
              })
                .then(res => { if (!res.ok) throw new Error('fail'); setStep(5); })
                .catch(() => setSendError(true))
                .finally(() => setSending(false));
            }} className="btn btn-sun" style={{ marginLeft: 'auto' }}>
              {sending ? 'Sending…' : 'Send inquiry'} <Ico.Arrow/>
            </button>
          </div>
        )}

        {sendError && <p style={{ color: 'var(--clay)', marginTop: 12, fontSize: 13 }}>Something went wrong sending your inquiry — please try again.</p>}

        {step === 5 && <Confirmation data={data}/>}
      </section>

      <style>{`
        @media (max-width: 980px) {
          main { grid-template-columns: 1fr !important; }
          .inquiry-aside { position: static !important; height: auto !important; padding: 60px 32px !important; }
          .inquiry-form { padding: 48px 32px !important; }
        }
      `}</style>
    </main>
  );
}

function Step1({ data, toggle }) {
  const opts = [
    { k: 'migration', t: 'The Great Migration', d: 'Two million wildebeest, river crossings, calving plains.', tone: 'sun', img: 'https://safari.janelsafaris.com/wp-content/uploads/2025/10/23.jpg' },
    { k: 'big5', t: 'The Big Five', d: 'Lion, leopard, elephant, buffalo, rhino — all in one trip.', tone: 'clay', img: 'https://safari.janelsafaris.com/wp-content/uploads/2025/09/DSC_2974-Edit.jpg' },
    { k: 'kilimanjaro', t: 'Kilimanjaro', d: '5,895m. Eight days from rainforest to glacier.', tone: 'ink', img: 'https://safari.janelsafaris.com/wp-content/uploads/2025/10/yoad-shejtman-S8IflvEHBFk-unsplash-scaled.jpg' },
    { k: 'beach', t: 'Beach time', d: 'Zanzibar, Pemba, Mafia. Decompress after the bush.', tone: 'ocean', img: 'https://safari.janelsafaris.com/wp-content/uploads/2025/09/humphrey-m-e6dRLBx6Kg8-unsplash-scaled.jpg' },
    { k: 'culture', t: 'Cultural depth', d: 'Maasai, Hadzabe, Datoga. Real visits, not performances.', tone: 'moss', img: 'https://safari.janelsafaris.com/wp-content/uploads/2025/09/matthew-stephenson-ztJxQYP2bKs-unsplash-scaled.jpg' },
    { k: 'photo', t: 'Photography', d: 'Specialist vehicles, hides, and bean bags. Pro guides.', tone: 'sand', img: 'https://safari.janelsafaris.com/wp-content/uploads/2025/09/janel-scaled.jpg' },
    { k: 'family', t: 'Family-friendly', d: 'Trip designed around kids without dumbing down.', tone: 'sun', img: 'https://safari.janelsafaris.com/wp-content/uploads/2026/03/Rhino-Lodge-15-700px.jpg' },
    { k: 'honeymoon', t: 'Honeymoon', d: 'Privacy, romance, and sunsets you remember.', tone: 'clay', img: 'https://safari.janelsafaris.com/wp-content/uploads/2025/09/ultimate-safaris-namibia-fxx-SJSsiqk-unsplash-scaled.jpg' },
  ];
  return (
    <div>
      <div className="label">Multi-select · Pick anything that resonates</div>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12, marginTop: 16 }}>
        {opts.map(o => {
          const sel = data.interests.includes(o.k);
          return (
            <button key={o.k} onClick={() => toggle('interests', o.k)} style={{
              padding: 0, textAlign: 'left',
              border: '1px solid ' + (sel ? 'var(--ink)' : 'var(--line)'),
              borderRadius: 'var(--radius-md)',
              background: sel ? 'var(--ink)' : 'transparent',
              color: sel ? 'var(--bone)' : 'var(--ink)',
              transition: 'all 0.2s', overflow: 'hidden'
            }}>
              <div style={{ height: 100, overflow: 'hidden' }}>
                <img src={o.img} alt={o.t} style={{ width: '100%', height: '100%', objectFit: 'cover', display: 'block' }}/>
              </div>
              <div style={{ padding: 16 }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
                  <h3 style={{ fontFamily: 'var(--serif)', fontSize: 22, fontWeight: 500, margin: 0 }}>{o.t}</h3>
                  <span style={{
                    width: 22, height: 22, borderRadius: '50%',
                    border: '1px solid currentColor',
                    display: 'flex', alignItems: 'center', justifyContent: 'center',
                    background: sel ? 'var(--sun)' : 'transparent', color: sel ? 'var(--ink)' : 'currentColor',
                    flexShrink: 0
                  }}>{sel && <Ico.Check style={{ width: 12, height: 12 }}/>}</span>
                </div>
                <p style={{ fontSize: 13, marginTop: 6, opacity: 0.75 }}>{o.d}</p>
              </div>
            </button>
          );
        })}
      </div>
    </div>
  );
}

function Step2({ data, set }) {
  const months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
  const years = ['2026','2027'];
  const monthGuide = {
    'Jan': 'Calving season · Ndutu', 'Feb': 'Calving peak · Ndutu', 'Mar': 'Green & quiet',
    'Apr': 'Long rains · low season', 'May': 'Green season finishes', 'Jun': 'Dry begins · excellent',
    'Jul': 'Migration in central/north', 'Aug': 'River crossings begin', 'Sep': 'Crossings peak ★',
    'Oct': 'Crossings continue', 'Nov': 'Short rains · transition', 'Dec': 'Migration south · festive'
  };
  return (
    <div>
      <div style={{ display: 'flex', gap: 8, marginBottom: 24 }}>
        {[['flexible','I have flexibility'],['set','My dates are set']].map(([k,l]) => (
          <button key={k} onClick={() => set('when', k)} style={{
            flex: 1, padding: '14px',
            border: '1px solid ' + (data.when === k ? 'var(--ink)' : 'var(--line)'),
            background: data.when === k ? 'var(--ink)' : 'transparent',
            color: data.when === k ? 'var(--bone)' : 'var(--ink)',
            borderRadius: 'var(--radius-md)', fontSize: 14, fontWeight: 500
          }}>{l}</button>
        ))}
      </div>
      <div className="label">Target month</div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(6, 1fr)', gap: 8, marginTop: 12 }}>
        {months.map((m, i) => (
          <button key={m} onClick={() => set('month', m.toLowerCase())} style={{
            padding: '14px 0', borderRadius: 6, fontSize: 13, fontFamily: 'var(--mono)',
            textTransform: 'uppercase', letterSpacing: '0.08em',
            background: data.month === m.toLowerCase() ? 'var(--moss)' : 'transparent',
            color: data.month === m.toLowerCase() ? 'var(--bone)' : 'var(--ink)',
            border: '1px solid ' + (data.month === m.toLowerCase() ? 'var(--moss)' : 'var(--line)')
          }}>{m}</button>
        ))}
      </div>
      <div style={{
        marginTop: 16, padding: 16, background: 'var(--bone-deep)', borderRadius: 'var(--radius-md)',
        display: 'flex', alignItems: 'center', gap: 12
      }}>
        <Ico.Compass style={{ color: 'var(--sun)' }}/>
        <div style={{ fontSize: 14 }}>
          <strong style={{ fontFamily: 'var(--serif)', fontSize: 18 }}>{months.find(m => m.toLowerCase() === data.month)}</strong>
          <span style={{ marginLeft: 12, color: 'var(--muted)' }}>{monthGuide[months.find(m => m.toLowerCase() === data.month)]}</span>
        </div>
      </div>

      <div style={{ marginTop: 32 }}>
        <div className="label">Year</div>
        <div style={{ display: 'flex', gap: 8, marginTop: 12 }}>
          {years.map(y => (
            <button key={y} onClick={() => set('year', y)} style={{
              padding: '12px 24px', borderRadius: 6, fontFamily: 'var(--serif)', fontSize: 22,
              background: data.year === y ? 'var(--ink)' : 'transparent',
              color: data.year === y ? 'var(--bone)' : 'var(--ink)',
              border: '1px solid ' + (data.year === y ? 'var(--ink)' : 'var(--line)')
            }}>{y}</button>
          ))}
        </div>
      </div>

      <div style={{ marginTop: 32 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
          <span className="label">Trip length</span>
          <span style={{ fontFamily: 'var(--serif)', fontSize: 22 }}>{data.days} days</span>
        </div>
        <input type="range" min="3" max="21" value={data.days} onChange={e => set('days', +e.target.value)} style={{ width: '100%', marginTop: 8, accentColor: 'var(--moss)' }}/>
        <div style={{ display: 'flex', justifyContent: 'space-between', fontFamily: 'var(--mono)', fontSize: 11, color: 'var(--muted)' }}>
          <span>3</span><span>12</span><span>21</span>
        </div>
      </div>
    </div>
  );
}

function Step3({ data, set }) {
  return (
    <div>
      <div className="label">Adults (16+)</div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 16, marginTop: 12 }}>
        <button onClick={() => set('travelers', Math.max(1, data.travelers-1))} style={{
          width: 44, height: 44, borderRadius: '50%', border: '1px solid var(--line)'
        }}><Ico.Minus/></button>
        <span style={{ fontFamily: 'var(--serif)', fontSize: 48, minWidth: 60, textAlign: 'center' }}>{data.travelers}</span>
        <button onClick={() => set('travelers', Math.min(12, data.travelers+1))} style={{
          width: 44, height: 44, borderRadius: '50%', border: '1px solid var(--line)'
        }}><Ico.Plus/></button>
      </div>

      <div className="label" style={{ marginTop: 32 }}>Children (under 16)</div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 16, marginTop: 12 }}>
        <button onClick={() => set('kids', Math.max(0, data.kids-1))} style={{
          width: 44, height: 44, borderRadius: '50%', border: '1px solid var(--line)'
        }}><Ico.Minus/></button>
        <span style={{ fontFamily: 'var(--serif)', fontSize: 48, minWidth: 60, textAlign: 'center' }}>{data.kids}</span>
        <button onClick={() => set('kids', Math.min(8, data.kids+1))} style={{
          width: 44, height: 44, borderRadius: '50%', border: '1px solid var(--line)'
        }}><Ico.Plus/></button>
      </div>

      <div style={{ marginTop: 40, padding: 24, background: 'var(--bone-deep)', borderRadius: 'var(--radius-md)' }}>
        <div className="mono" style={{ fontSize: 11, color: 'var(--moss)', letterSpacing: '0.14em', textTransform: 'uppercase', marginBottom: 8 }}>
          🛻 Vehicle suggestion
        </div>
        <p style={{ margin: 0, fontSize: 14, color: 'var(--ink-soft)' }}>
          {data.travelers + data.kids <= 4 ? 'One Toyota Land Cruiser fits comfortably. Each guest gets a window — guaranteed.' :
           data.travelers + data.kids <= 7 ? 'One Land Cruiser, but we recommend two for guaranteed window seats.' :
           'Two Land Cruisers travelling in convoy with two guides.'}
        </p>
      </div>
    </div>
  );
}

function Step4({ data, set, toggle }) {
  return (
    <div>
      <div className="label">Pace</div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3,1fr)', gap: 8, marginTop: 12 }}>
        {[
          ['relaxed','Relaxed','Long mornings, slow drives'],
          ['balanced','Balanced','Mix of activity and rest'],
          ['intense','Intense','Maximum game-driving'],
        ].map(([k,t,d]) => (
          <button key={k} onClick={() => set('pace', k)} style={{
            padding: 16, borderRadius: 'var(--radius-md)', textAlign: 'left',
            border: '1px solid ' + (data.pace === k ? 'var(--ink)' : 'var(--line)'),
            background: data.pace === k ? 'var(--ink)' : 'transparent',
            color: data.pace === k ? 'var(--bone)' : 'var(--ink)'
          }}>
            <div style={{ fontFamily: 'var(--serif)', fontSize: 20, fontWeight: 500 }}>{t}</div>
            <div style={{ fontSize: 12, opacity: 0.7, marginTop: 4 }}>{d}</div>
          </button>
        ))}
      </div>

      <div className="label" style={{ marginTop: 32 }}>Accommodation style (multi)</div>
      <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', marginTop: 12 }}>
        {['Tented','Lodge','Mobile camp','Treehouse','Boutique hotel'].map(a => {
          const sel = data.accommodation.includes(a.toLowerCase().replace(' ','-'));
          const k = a.toLowerCase().replace(' ','-');
          return (
            <button key={k} onClick={() => toggle('accommodation', k)} className="chip" style={{
              cursor: 'pointer', padding: '8px 14px', fontSize: 12,
              background: sel ? 'var(--moss)' : 'transparent',
              color: sel ? 'var(--bone)' : 'var(--ink)',
              borderColor: sel ? 'var(--moss)' : 'var(--line)'
            }}>{a}</button>
          );
        })}
      </div>

      <div className="label" style={{ marginTop: 32 }}>Style of trip</div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3,1fr)', gap: 8, marginTop: 12 }}>
        {[
          ['mid','Mid-luxury','$3–6k pp'],
          ['lux','Luxury','$6–12k pp'],
          ['ultra','Ultra-luxury','$12k+ pp'],
        ].map(([k,t,p]) => (
          <button key={k} onClick={() => set('style', k)} style={{
            padding: 16, borderRadius: 'var(--radius-md)', textAlign: 'left',
            border: '1px solid ' + (data.style === k ? 'var(--ink)' : 'var(--line)'),
            background: data.style === k ? 'var(--ink)' : 'transparent',
            color: data.style === k ? 'var(--bone)' : 'var(--ink)'
          }}>
            <div style={{ fontFamily: 'var(--serif)', fontSize: 20, fontWeight: 500 }}>{t}</div>
            <div style={{ fontSize: 12, opacity: 0.7, marginTop: 4 }}>{p}</div>
          </button>
        ))}
      </div>

      <div style={{ marginTop: 32 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
          <span className="label">Approximate budget per person</span>
          <span style={{ fontFamily: 'var(--serif)', fontSize: 22 }}>${data.budget.toLocaleString()}</span>
        </div>
        <input type="range" min="2000" max="20000" step="500" value={data.budget} onChange={e => set('budget', +e.target.value)} style={{ width: '100%', marginTop: 8, accentColor: 'var(--moss)' }}/>
        <div style={{ display: 'flex', justifyContent: 'space-between', fontFamily: 'var(--mono)', fontSize: 11, color: 'var(--muted)' }}>
          <span>$2k</span><span>$10k</span><span>$20k+</span>
        </div>
      </div>
    </div>
  );
}

function Step5({ data, set }) {
  return (
    <div>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
        <div>
          <label className="label">Full name</label>
          <input className="input" value={data.name} onChange={e => set('name', e.target.value)} placeholder="Hannah Reiss"/>
        </div>
        <div>
          <label className="label">Email</label>
          <input className="input" value={data.email} onChange={e => set('email', e.target.value)} placeholder="hannah@example.com" type="email"/>
        </div>
        <div>
          <label className="label">Country</label>
          <select className="select" value={data.country} onChange={e => set('country', e.target.value)}>
            <option value="">Select…</option>
            {['United Kingdom','United States','Canada','Germany','France','Australia','Japan','India','Other'].map(c => <option key={c}>{c}</option>)}
          </select>
        </div>
        <div>
          <label className="label">WhatsApp / Phone (optional)</label>
          <input className="input" value={data.phone} onChange={e => set('phone', e.target.value)} placeholder="+44 …"/>
        </div>
      </div>
      <div style={{ marginTop: 24 }}>
        <label className="label">Anything we should know? (optional)</label>
        <textarea className="textarea" rows={4} value={data.notes} onChange={e => set('notes', e.target.value)}
          placeholder="Mobility considerations, dietary needs, dream sightings, special occasions…"/>
      </div>
      <div style={{
        marginTop: 32, padding: 24, background: 'var(--bone-deep)', borderRadius: 'var(--radius-md)',
        display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 24
      }}>
        <Summary label="Interests" v={data.interests.length ? data.interests.length + ' selected' : '—'}/>
        <Summary label="When" v={`${data.month} ${data.year}`}/>
        <Summary label="Length" v={`${data.days} days`}/>
        <Summary label="Travelers" v={`${data.travelers} adults${data.kids ? `, ${data.kids} kids` : ''}`}/>
        <Summary label="Style" v={data.style + '-luxury'}/>
        <Summary label="Budget" v={`~$${data.budget.toLocaleString()} pp`}/>
      </div>
    </div>
  );
}

function Summary({ label, v }) {
  return (
    <div>
      <div className="label">{label}</div>
      <div style={{ fontFamily: 'var(--serif)', fontSize: 18, marginTop: 4, textTransform: 'capitalize' }}>{v}</div>
    </div>
  );
}

function Confirmation({ data }) {
  return (
    <div style={{
      position: 'fixed', inset: 0, background: 'rgba(26,24,20,0.92)', backdropFilter: 'blur(20px)',
      zIndex: 200, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 24
    }}>
      <div style={{ background: 'var(--bone)', borderRadius: 'var(--radius-lg)', maxWidth: 560, padding: 56, textAlign: 'center' }}>
        <div style={{
          width: 64, height: 64, borderRadius: '50%', background: 'var(--moss)', color: 'var(--bone)',
          margin: '0 auto', display: 'flex', alignItems: 'center', justifyContent: 'center'
        }}>
          <Ico.Check style={{ width: 28, height: 28 }}/>
        </div>
        <h2 className="h-2" style={{ marginTop: 24 }}>
          <em style={{ fontStyle: 'italic' }}>Asante sana,</em> {data.name || 'traveler'}.
        </h2>
        <p style={{ marginTop: 16, color: 'var(--ink-soft)' }}>
          Your inquiry is in our hands. A Tanzanian planner will read every word and reply within 24 hours — usually with a draft itinerary attached.
        </p>
        <div style={{ marginTop: 32, padding: 20, background: 'var(--bone-deep)', borderRadius: 'var(--radius-md)', textAlign: 'left' }}>
          <div className="mono" style={{ fontSize: 11, color: 'var(--muted)', letterSpacing: '0.14em', textTransform: 'uppercase', marginBottom: 6 }}>Reference</div>
          <div style={{ fontFamily: 'var(--mono)', fontSize: 18 }}>JS-2026-{Math.floor(Math.random()*9000+1000)}</div>
        </div>
        <div style={{ display: 'flex', gap: 8, marginTop: 32, justifyContent: 'center' }}>
          <a href="janelsafaris.com" className="btn btn-ghost">Back to home</a>
          <a href="#" className="btn btn-primary"><Ico.Wa style={{ width: 14, height: 14 }}/> WhatsApp now</a>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { Inquiry });