/* global React, FLEET */
const { useState, useMemo } = React;

/* ============================================================
   BOOKING — multi-step quote with live recommendation
   ============================================================ */
function BookingFlow() {
  const [step, setStep] = useState(0);
  const [data, setData] = useState({
    from: 'PRG', fromName: 'Prague',
    to: 'LCY', toName: 'London City',
    distance: 1050,
    date: '2026-05-12', time: '09:00',
    pax: 4,
    aircraft: null,
    catering: 'standard',
    extras: [],
  });

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

  // recommend aircraft based on pax + distance
  const recommended = useMemo(() => {
    const candidates = window.FLEET.filter(a => {
      const rangeKm = parseInt(a.range.replace(/[,\s]/g, ''));
      return a.seats >= data.pax && rangeKm >= data.distance * 1.15;
    });
    return candidates.sort((a, b) => a.seats - b.seats).slice(0, 3);
  }, [data.pax, data.distance]);

  // estimated price (rough — for prototype only)
  const priceEst = useMemo(() => {
    const a = data.aircraft || recommended[0];
    if (!a) return 0;
    const ratePerKm = { 'learjet-75': 9, 'gulfstream-g200': 11, 'gulfstream-g280': 13, 'challenger-605': 15, 'global-6000': 22 };
    const base = (ratePerKm[a.id] || 12) * data.distance * 2;
    const cateringExtra = { standard: 0, premium: 1200, signature: 3500 }[data.catering] || 0;
    return Math.round((base + cateringExtra) / 100) * 100;
  }, [data.aircraft, data.catering, data.distance, recommended]);

  const steps = ['Route', 'Passengers', 'Aircraft', 'Details', 'Quote'];

  const next = () => setStep(s => Math.min(s + 1, steps.length - 1));
  const prev = () => setStep(s => Math.max(s - 1, 0));

  return (
    <section id="book" style={{ padding: '140px 0', borderBottom: '1px solid var(--line)' }}>
      <div className="container-wide">
        <div className="section-head">
          <div>
            <div className="eyebrow" style={{ marginBottom: 16 }}>04 — Instant quote</div>
            <h2 className="section-title">Plan your<br/>flight in five steps.</h2>
          </div>
          <p className="section-sub">
            Tell us where, when and how many — we'll suggest the right aircraft and a live price band.
            A real dispatcher confirms within four working hours.
          </p>
        </div>

        <div style={{
          display: 'grid', gridTemplateColumns: '1.4fr 1fr', gap: 0,
          border: '1px solid var(--line)',
          background: 'var(--bg-elevated)',
        }}>
          {/* LEFT — form */}
          <div style={{ padding: 48, borderRight: '1px solid var(--line)' }}>
            {/* Step bar */}
            <div style={{ display: 'flex', gap: 4, marginBottom: 40 }}>
              {steps.map((s, i) => (
                <div key={s} style={{ flex: 1 }}>
                  <div style={{
                    height: 2,
                    background: i <= step ? 'var(--accent)' : 'var(--line)',
                    transition: 'background var(--t-base)',
                  }}/>
                  <div className="mono" style={{
                    fontSize: 10, textTransform: 'uppercase', letterSpacing: '0.1em',
                    marginTop: 8,
                    color: i === step ? 'var(--text)' : 'var(--text-subtle)',
                  }}>
                    0{i + 1} {s}
                  </div>
                </div>
              ))}
            </div>

            {/* Step content */}
            <div style={{ minHeight: 360 }}>
              {step === 0 && (
                <div>
                  <h3 className="display" style={{ fontSize: 36, fontWeight: 500, letterSpacing: '-0.03em', marginBottom: 24 }}>Where to?</h3>
                  <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16, marginBottom: 24 }}>
                    <Field label="From (ICAO/IATA)" value={data.from} onChange={v => update('from', v.toUpperCase())} mono/>
                    <Field label="To (ICAO/IATA)" value={data.to} onChange={v => update('to', v.toUpperCase())} mono/>
                    <Field label="Departure date" value={data.date} type="date" onChange={v => update('date', v)}/>
                    <Field label="Time (UTC)" value={data.time} type="time" onChange={v => update('time', v)}/>
                  </div>
                  <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
                    {[
                      ['PRG → LCY', 1050, 'PRG', 'Prague', 'LCY', 'London City'],
                      ['PRG → DXB', 4350, 'PRG', 'Prague', 'DXB', 'Dubai'],
                      ['PRG → CDG', 880, 'PRG', 'Prague', 'CDG', 'Paris CDG'],
                      ['PRG → LJU', 480, 'PRG', 'Prague', 'LJU', 'Ljubljana'],
                    ].map(p => (
                      <button key={p[0]} onClick={() => setData(d => ({ ...d, from: p[2], fromName: p[3], to: p[4], toName: p[5], distance: p[1] }))}
                        className="mono"
                        style={{
                          fontSize: 11, padding: '8px 12px',
                          border: '1px solid var(--line-strong)',
                          letterSpacing: '0.04em',
                        }}>
                        {p[0]} · {p[1]} km
                      </button>
                    ))}
                  </div>
                </div>
              )}

              {step === 1 && (
                <div>
                  <h3 className="display" style={{ fontSize: 36, fontWeight: 500, letterSpacing: '-0.03em', marginBottom: 24 }}>How many?</h3>
                  <div style={{ marginBottom: 32 }}>
                    <div className="mono" style={{ fontSize: 11, color: 'var(--text-subtle)', textTransform: 'uppercase', letterSpacing: '0.12em', marginBottom: 12 }}>Passengers</div>
                    <div style={{ display: 'flex', gap: 8 }}>
                      {[2, 4, 6, 8, 10, 12].map(n => (
                        <button key={n} onClick={() => update('pax', n)}
                          style={{
                            width: 56, height: 56,
                            border: '1px solid ' + (data.pax === n ? 'var(--text)' : 'var(--line-strong)'),
                            background: data.pax === n ? 'var(--text)' : 'transparent',
                            color: data.pax === n ? 'var(--bg)' : 'var(--text)',
                            fontSize: 18, fontWeight: 500,
                            transition: 'all var(--t-fast)',
                          }}>
                          {n}
                        </button>
                      ))}
                    </div>
                  </div>
                  <div style={{
                    padding: 20, background: 'var(--bg-inset)',
                    border: '1px solid var(--line)',
                    fontSize: 13, color: 'var(--text-muted)', lineHeight: 1.6,
                  }}>
                    With <strong style={{ color: 'var(--text)' }}>{data.pax}</strong> passengers and a leg of <strong style={{ color: 'var(--text)' }}>{data.distance} km</strong>,
                    we have <strong style={{ color: 'var(--accent)' }}>{recommended.length}</strong> aircraft that fit.
                  </div>
                </div>
              )}

              {step === 2 && (
                <div>
                  <h3 className="display" style={{ fontSize: 36, fontWeight: 500, letterSpacing: '-0.03em', marginBottom: 24 }}>Pick your aircraft</h3>
                  <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
                    {recommended.length === 0 && (
                      <div style={{ padding: 20, background: 'var(--bg-inset)', fontSize: 13, color: 'var(--text-muted)' }}>
                        No aircraft in the fleet match these requirements. Adjust passenger count or contact dispatch.
                      </div>
                    )}
                    {recommended.map((a, i) => {
                      const sel = (data.aircraft?.id || recommended[0]?.id) === a.id;
                      return (
                        <button key={a.id} onClick={() => update('aircraft', a)}
                          style={{
                            padding: 20,
                            border: '1px solid ' + (sel ? 'var(--accent)' : 'var(--line-strong)'),
                            background: sel ? 'color-mix(in oklch, var(--accent) 6%, var(--bg))' : 'transparent',
                            display: 'flex', justifyContent: 'space-between', alignItems: 'center',
                            textAlign: 'left',
                            transition: 'all var(--t-fast)',
                          }}>
                          <div>
                            <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 4 }}>
                              {i === 0 && <span className="mono" style={{ fontSize: 9, padding: '3px 6px', background: 'var(--accent)', color: '#fff', letterSpacing: '0.1em' }}>RECOMMENDED</span>}
                              <span className="mono" style={{ fontSize: 11, color: 'var(--text-subtle)' }}>{a.mfr.toUpperCase()}</span>
                            </div>
                            <div className="display" style={{ fontSize: 22, fontWeight: 500, letterSpacing: '-0.02em' }}>
                              {a.model} <span className="mono" style={{ fontSize: 13, color: 'var(--text-muted)', fontWeight: 400 }}>· {a.reg}</span>
                            </div>
                            <div className="mono" style={{ fontSize: 11, color: 'var(--text-muted)', marginTop: 4 }}>
                              {a.seats} pax · {a.range} · {a.speed}
                            </div>
                          </div>
                          <svg width="14" height="14" viewBox="0 0 14 14" style={{ color: sel ? 'var(--accent)' : 'var(--line-strong)' }}>
                            <circle cx="7" cy="7" r="6" fill="none" stroke="currentColor" strokeWidth="1.4"/>
                            {sel && <circle cx="7" cy="7" r="3" fill="currentColor"/>}
                          </svg>
                        </button>
                      );
                    })}
                  </div>
                </div>
              )}

              {step === 3 && (
                <div>
                  <h3 className="display" style={{ fontSize: 36, fontWeight: 500, letterSpacing: '-0.03em', marginBottom: 24 }}>Onboard preferences</h3>
                  <div className="mono" style={{ fontSize: 11, color: 'var(--text-subtle)', textTransform: 'uppercase', letterSpacing: '0.12em', marginBottom: 12 }}>Catering</div>
                  <div style={{ display: 'flex', flexDirection: 'column', gap: 8, marginBottom: 24 }}>
                    {[
                      { id: 'standard', t: 'Standard', d: 'Sandwiches, fresh fruit, soft drinks', p: 'Included' },
                      { id: 'premium', t: 'Premium', d: 'Three-course menu by Prague chef, full bar', p: '+ €1,200' },
                      { id: 'signature', t: 'Signature', d: 'Bespoke menu — sourced and prepped to your spec', p: '+ €3,500' },
                    ].map(c => {
                      const sel = data.catering === c.id;
                      return (
                        <button key={c.id} onClick={() => update('catering', c.id)}
                          style={{
                            padding: '16px 20px',
                            border: '1px solid ' + (sel ? 'var(--accent)' : 'var(--line-strong)'),
                            background: sel ? 'color-mix(in oklch, var(--accent) 6%, var(--bg))' : 'transparent',
                            display: 'flex', justifyContent: 'space-between', alignItems: 'center',
                            textAlign: 'left',
                          }}>
                          <div>
                            <div style={{ fontSize: 14, fontWeight: 500 }}>{c.t}</div>
                            <div style={{ fontSize: 12, color: 'var(--text-muted)', marginTop: 2 }}>{c.d}</div>
                          </div>
                          <div className="mono" style={{ fontSize: 12, color: sel ? 'var(--accent)' : 'var(--text-muted)' }}>{c.p}</div>
                        </button>
                      );
                    })}
                  </div>
                  <div className="mono" style={{ fontSize: 11, color: 'var(--text-subtle)', textTransform: 'uppercase', letterSpacing: '0.12em', marginBottom: 12 }}>Extras</div>
                  <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
                    {['VIP Lounge', 'Ground transfer', 'Pet onboard', 'Cargo hold'].map(x => {
                      const sel = data.extras.includes(x);
                      return (
                        <button key={x} onClick={() => update('extras', sel ? data.extras.filter(e => e !== x) : [...data.extras, x])}
                          style={{
                            padding: '10px 14px', fontSize: 12,
                            border: '1px solid ' + (sel ? 'var(--text)' : 'var(--line-strong)'),
                            background: sel ? 'var(--text)' : 'transparent',
                            color: sel ? 'var(--bg)' : 'var(--text)',
                          }}>
                          {sel ? '✓ ' : '+ '}{x}
                        </button>
                      );
                    })}
                  </div>
                </div>
              )}

              {step === 4 && (
                <div>
                  <h3 className="display" style={{ fontSize: 36, fontWeight: 500, letterSpacing: '-0.03em', marginBottom: 8 }}>Your estimate</h3>
                  <p style={{ color: 'var(--text-muted)', fontSize: 14, marginBottom: 24 }}>
                    Indicative. A dispatcher confirms binding price within 4 working hours.
                  </p>
                  <div style={{
                    padding: 32, border: '1px solid var(--line)', background: 'var(--bg-inset)',
                    marginBottom: 24,
                  }}>
                    <div className="mono" style={{ fontSize: 11, color: 'var(--text-subtle)', textTransform: 'uppercase', letterSpacing: '0.12em', marginBottom: 8 }}>
                      Estimated price band
                    </div>
                    <div className="display" style={{ fontSize: 56, fontWeight: 500, letterSpacing: '-0.04em', lineHeight: 1 }}>
                      €{(priceEst * 0.92).toLocaleString('en-US', { maximumFractionDigits: 0 })}
                      <span style={{ fontSize: 28, color: 'var(--text-muted)', margin: '0 12px' }}>—</span>
                      €{(priceEst * 1.08).toLocaleString('en-US', { maximumFractionDigits: 0 })}
                    </div>
                    <div className="mono" style={{ fontSize: 11, color: 'var(--text-subtle)', marginTop: 12 }}>
                      Round trip · all taxes & fees · positioning included
                    </div>
                  </div>
                  <input type="email" placeholder="your@email.com"
                    style={{
                      width: '100%', padding: '16px 18px', fontSize: 14,
                      border: '1px solid var(--line-strong)', background: 'var(--bg)',
                      color: 'var(--text)', fontFamily: 'inherit', borderRadius: 0,
                      marginBottom: 12,
                    }}/>
                  <button className="btn btn-primary" style={{ width: '100%', justifyContent: 'center', padding: 16 }}>
                    Send to dispatch
                  </button>
                </div>
              )}
            </div>

            {/* Nav buttons */}
            <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 40, paddingTop: 24, borderTop: '1px solid var(--line)' }}>
              <button onClick={prev} disabled={step === 0} className="btn btn-ghost"
                style={{ opacity: step === 0 ? 0.3 : 1 }}>
                <svg width="12" height="12" viewBox="0 0 12 12"><path d="M10 6H2M6 2L2 6l4 4" stroke="currentColor" strokeWidth="1.5" fill="none"/></svg>
                Back
              </button>
              {step < steps.length - 1 && (
                <button onClick={next} className="btn btn-primary">
                  Continue
                  <svg width="12" height="12" viewBox="0 0 12 12"><path d="M2 6h8M6 2l4 4-4 4" stroke="currentColor" strokeWidth="1.5" fill="none"/></svg>
                </button>
              )}
            </div>
          </div>

          {/* RIGHT — live summary */}
          <div style={{ padding: 48, background: 'var(--bg-inset)' }}>
            <div className="eyebrow" style={{ marginBottom: 24 }}>Your quote · LIVE</div>

            {/* Route visual */}
            <div style={{ marginBottom: 32, padding: '24px 0', borderTop: '1px solid var(--line)', borderBottom: '1px solid var(--line)' }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 12 }}>
                <div>
                  <div className="mono" style={{ fontSize: 11, color: 'var(--text-subtle)' }}>FROM</div>
                  <div className="display" style={{ fontSize: 32, fontWeight: 500, letterSpacing: '-0.02em' }}>{data.from}</div>
                  <div style={{ fontSize: 12, color: 'var(--text-muted)' }}>{data.fromName}</div>
                </div>
                <div style={{ flex: 1, padding: '0 16px', position: 'relative' }}>
                  <div style={{ height: 1, background: 'var(--line-strong)', position: 'relative' }}>
                    <svg width="20" height="20" viewBox="0 0 20 20" style={{
                      position: 'absolute', left: '50%', top: '50%', transform: 'translate(-50%, -50%) rotate(90deg)',
                      background: 'var(--bg-inset)', padding: 2,
                    }}>
                      <path d="M10 2 L13 14 L10 12 L7 14 Z" fill="var(--accent)"/>
                    </svg>
                  </div>
                  <div className="mono" style={{ textAlign: 'center', fontSize: 10, color: 'var(--text-subtle)', marginTop: 8 }}>
                    {data.distance} KM
                  </div>
                </div>
                <div style={{ textAlign: 'right' }}>
                  <div className="mono" style={{ fontSize: 11, color: 'var(--text-subtle)' }}>TO</div>
                  <div className="display" style={{ fontSize: 32, fontWeight: 500, letterSpacing: '-0.02em' }}>{data.to}</div>
                  <div style={{ fontSize: 12, color: 'var(--text-muted)' }}>{data.toName}</div>
                </div>
              </div>
            </div>

            <SummaryRow l="Date" v={data.date}/>
            <SummaryRow l="Time" v={data.time + ' UTC'}/>
            <SummaryRow l="Passengers" v={`${data.pax} pax`}/>
            <SummaryRow l="Aircraft" v={(data.aircraft || recommended[0])?.model || '—'}/>
            <SummaryRow l="Catering" v={data.catering}/>
            <SummaryRow l="Extras" v={data.extras.length ? data.extras.join(', ') : 'None'}/>

            <div style={{ marginTop: 32, padding: 20, background: 'var(--bg)', border: '1px solid var(--line-strong)' }}>
              <div className="mono" style={{ fontSize: 10, color: 'var(--text-subtle)', textTransform: 'uppercase', letterSpacing: '0.12em', marginBottom: 8 }}>
                Estimated · indicative only
              </div>
              <div className="display" style={{ fontSize: 36, fontWeight: 500, letterSpacing: '-0.03em' }}>
                €{priceEst.toLocaleString('en-US', { maximumFractionDigits: 0 })}
              </div>
              <div className="mono" style={{ fontSize: 11, color: 'var(--text-muted)', marginTop: 6 }}>
                ± 8% · all-in · round trip
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

function Field({ label, value, onChange, type = 'text', mono }) {
  return (
    <label style={{ display: 'block' }}>
      <div className="mono" style={{ fontSize: 10, textTransform: 'uppercase', letterSpacing: '0.12em', color: 'var(--text-subtle)', marginBottom: 6 }}>{label}</div>
      <input type={type} value={value} onChange={e => onChange(e.target.value)}
        style={{
          width: '100%', padding: '12px 14px', fontSize: 14,
          fontFamily: mono ? 'var(--font-mono)' : 'inherit',
          border: '1px solid var(--line-strong)', background: 'var(--bg)',
          color: 'var(--text)', borderRadius: 0,
          letterSpacing: mono ? '0.05em' : 'normal',
        }}/>
    </label>
  );
}

function SummaryRow({ l, v }) {
  return (
    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '12px 0', borderBottom: '1px dashed var(--line)' }}>
      <span className="mono" style={{ fontSize: 11, color: 'var(--text-subtle)', textTransform: 'uppercase', letterSpacing: '0.1em' }}>{l}</span>
      <span style={{ fontSize: 13, fontWeight: 500, textTransform: 'capitalize' }}>{v}</span>
    </div>
  );
}

Object.assign(window, { BookingFlow });
