// ============================================================
// JET LUXE — Quote modal (multi-step) + main app
// ============================================================

const { useState: useState_, useEffect: useEffect_, useMemo: useMemo_, Fragment: Fragment_ } = React;

// ============================================================
// QUOTE MODAL
// ============================================================
function QuoteModal({ t, locale, open, onClose, initialService }) {
  const Q = t.quote;
  const STEPS = 5;
  const [step, setStep] = useState_(1);
  const [data, setData] = useState_({
    service: initialService || 'charter',
    trip: 0,
    from: '',
    to: '',
    depart: '',
    ret: '',
    pax: '4',
    notes: '',
    name: '',
    email: '',
    phone: '',
    prefer: 0
  });

  useEffect_(() => {
    if (open) {
      setStep(1);
      setData(d => ({ ...d, service: initialService || d.service }));
      document.body.style.overflow = 'hidden';
    } else {
      document.body.style.overflow = '';
    }
  }, [open, initialService]);

  if (!open) return null;

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

  const next = () => setStep(s => Math.min(STEPS, s + 1));
  const back = () => setStep(s => Math.max(1, s - 1));

  const canAdvance = () => {
    if (step === 1) return !!data.service;
    if (step === 2) return data.from.trim() && data.to.trim();
    if (step === 3) return data.depart.trim() && data.pax;
    if (step === 4) return data.name.trim() && data.email.trim();
    return true;
  };

  // build WhatsApp deep-link from current state
  const waText = useMemo_(() => {
    const lines = [
      locale === 'ar' ? 'مرحباً Jet Luxe، أودّ الاستفسار عن:' : 'Hi Jet Luxe, I’d like to enquire about:',
      `· ${Q.step1.options.find(o => o.id === data.service)?.name || data.service}`,
      `· ${Q.step2.from}: ${data.from || '—'}`,
      `· ${Q.step2.to}: ${data.to || '—'}`,
      `· ${Q.step3.depart}: ${data.depart || '—'}`,
      `· ${Q.step3.pax}: ${data.pax || '—'}`,
      data.notes ? `· ${Q.step3.notes}: ${data.notes}` : null
    ].filter(Boolean);
    return encodeURIComponent(lines.join('\n'));
  }, [data, locale, Q]);
  const waUrl = `https://wa.me/+17724448268?text=${waText}`;

  const reference = useMemo_(() => 'JL-' + Math.random().toString(36).slice(2, 8).toUpperCase(), [open]);

  // ---- Step contents ----
  const Step1 = () => (
    <Fragment_>
      <div className="modal-step-num">{locale === 'ar' ? 'الخطوة ١ من ٥' : 'Step 01 / 05'}</div>
      <h3 className="modal-h">{Q.step1.h}</h3>
      <p className="modal-sub">{Q.step1.sub}</p>
      <div className="option-grid">
        {Q.step1.options.map(o => (
          <button
            key={o.id}
            className={`option-card ${data.service === o.id ? 'selected' : ''}`}
            onClick={() => update('service', o.id)}
            type="button"
          >
            <h4>{o.name}</h4>
            <p>{o.desc}</p>
          </button>
        ))}
      </div>
    </Fragment_>
  );

  const Step2 = () => (
    <Fragment_>
      <div className="modal-step-num">{locale === 'ar' ? 'الخطوة ٢ من ٥' : 'Step 02 / 05'}</div>
      <h3 className="modal-h">{Q.step2.h}</h3>
      <p className="modal-sub">{Q.step2.sub}</p>
      <div className="field">
        <label>{locale === 'ar' ? 'نوع الرحلة' : 'Trip type'}</label>
        <div style={{ display: 'flex', gap: 8, marginTop: 4 }}>
          {Q.step2.trip.map((tt, i) => (
            <button
              key={i}
              type="button"
              onClick={() => update('trip', i)}
              className={`option-card ${data.trip === i ? 'selected' : ''}`}
              style={{ padding: '12px 16px', flex: 1, textAlign: 'center' }}
            >
              <h4 style={{ fontSize: 14, margin: 0 }}>{tt}</h4>
            </button>
          ))}
        </div>
      </div>
      <div className="field-row">
        <div className="field">
          <label>{Q.step2.from}</label>
          <input type="text" value={data.from} placeholder={Q.step2.fromPh} onChange={e => update('from', e.target.value)} />
        </div>
        <div className="field">
          <label>{Q.step2.to}</label>
          <input type="text" value={data.to} placeholder={Q.step2.toPh} onChange={e => update('to', e.target.value)} />
        </div>
      </div>
    </Fragment_>
  );

  const Step3 = () => (
    <Fragment_>
      <div className="modal-step-num">{locale === 'ar' ? 'الخطوة ٣ من ٥' : 'Step 03 / 05'}</div>
      <h3 className="modal-h">{Q.step3.h}</h3>
      <p className="modal-sub">{Q.step3.sub}</p>
      <div className="field-row">
        <div className="field">
          <label>{Q.step3.depart}</label>
          <input type="date" value={data.depart} onChange={e => update('depart', e.target.value)} />
        </div>
        <div className="field">
          <label>{Q.step3.ret}</label>
          <input type="date" value={data.ret} onChange={e => update('ret', e.target.value)} />
        </div>
      </div>
      <div className="field-row">
        <div className="field">
          <label>{Q.step3.pax}</label>
          <input type="number" min="1" max="14" value={data.pax} onChange={e => update('pax', e.target.value)} />
        </div>
        <div></div>
      </div>
      <div className="field">
        <label>{Q.step3.notes}</label>
        <textarea rows={2} value={data.notes} placeholder={Q.step3.notesPh}
          onChange={e => update('notes', e.target.value)}
          style={{ resize: 'none' }}
        />
      </div>
    </Fragment_>
  );

  const Step4 = () => (
    <Fragment_>
      <div className="modal-step-num">{locale === 'ar' ? 'الخطوة ٤ من ٥' : 'Step 04 / 05'}</div>
      <h3 className="modal-h">{Q.step4.h}</h3>
      <p className="modal-sub">{Q.step4.sub}</p>
      <div className="field">
        <label>{Q.step4.name}</label>
        <input type="text" value={data.name} onChange={e => update('name', e.target.value)} />
      </div>
      <div className="field-row">
        <div className="field">
          <label>{Q.step4.email}</label>
          <input type="email" value={data.email} onChange={e => update('email', e.target.value)} />
        </div>
        <div className="field">
          <label>{Q.step4.phone}</label>
          <input type="tel" value={data.phone} onChange={e => update('phone', e.target.value)} />
        </div>
      </div>
      <div className="field">
        <label>{Q.step4.prefer}</label>
        <div style={{ display: 'flex', gap: 8, marginTop: 4 }}>
          {Q.step4.prefers.map((p, i) => (
            <button
              key={i}
              type="button"
              onClick={() => update('prefer', i)}
              className={`option-card ${data.prefer === i ? 'selected' : ''}`}
              style={{ padding: '12px 16px', flex: 1, textAlign: 'center' }}
            >
              <h4 style={{ fontSize: 14, margin: 0 }}>{p}</h4>
            </button>
          ))}
        </div>
      </div>
    </Fragment_>
  );

  const Step5 = () => (
    <div className="confirm">
      <div className="check">✓</div>
      <h3 className="modal-h" style={{ textAlign: 'center' }}>{Q.step5.h}</h3>
      <p className="modal-sub" style={{ textAlign: 'center' }}>{Q.step5.sub}</p>
      <div className="ref">{Q.step5.refLbl} · {reference}</div>
      <div className="confirm-actions">
        <a className="btn btn-primary" href={waUrl} target="_blank" rel="noopener">
          {Q.step5.wa} <span className="arr"></span>
        </a>
        <button className="btn btn-ghost" onClick={onClose}>
          {Q.step5.close}
        </button>
      </div>
    </div>
  );

  const stepBody = step === 1 ? <Step1 /> : step === 2 ? <Step2 /> : step === 3 ? <Step3 /> : step === 4 ? <Step4 /> : <Step5 />;

  return (
    <div className="modal-backdrop" onClick={onClose}>
      <div className="modal" onClick={e => e.stopPropagation()} role="dialog" aria-modal="true">
        <button className="modal-close" onClick={onClose} aria-label="Close">×</button>
        <div className="modal-progress">
          {Array.from({ length: STEPS }).map((_, i) => {
            const n = i + 1;
            const cls = n < step ? 'done' : n === step ? 'active' : '';
            return <span key={i} className={`step ${cls}`}></span>;
          })}
        </div>
        <div className="modal-body">
          {stepBody}
          {step < 5 && (
            <div className="modal-footer">
              <button className="btn btn-ghost btn-small" onClick={back} disabled={step === 1}
                style={{ opacity: step === 1 ? 0.3 : 1 }}>
                ← {Q.back}
              </button>
              <span className="step-count">{String(step).padStart(2, '0')} / 0{STEPS}</span>
              <button className="btn btn-primary btn-small"
                onClick={next}
                disabled={!canAdvance()}
                style={{ opacity: canAdvance() ? 1 : 0.3 }}>
                {step === 4 ? Q.send : Q.next} <span className="arr"></span>
              </button>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

// ============================================================
// TWEAKS
// ============================================================
function JLTweaks({ tweaks, setTweak }) {
  return (
    <TweaksPanel title="Tweaks">
      <TweakSection title="Theme">
        <TweakRadio label="Mode" value={tweaks.theme} onChange={v => setTweak('theme', v)}
          options={[{ value: 'light', label: 'Light' }, { value: 'dark', label: 'Dark' }]} />
        <TweakSelect label="Accent" value={tweaks.accent} onChange={v => setTweak('accent', v)}
          options={[
            { value: 'petrol',    label: 'Petrol blue · champagne' },
            { value: 'midnight',  label: 'Midnight · champagne' },
            { value: 'champagne', label: 'Champagne only' },
            { value: 'ocean',     label: 'Ocean · gold' }
          ]} />
      </TweakSection>
      <TweakSection title="Hero">
        <TweakRadio label="Treatment" value={tweaks.hero} onChange={v => setTweak('hero', v)}
          options={[
            { value: 'photo', label: 'Photo' },
            { value: 'split', label: 'Split' },
            { value: 'type',  label: 'Type-led' }
          ]} />
      </TweakSection>
      <TweakSection title="Rhythm">
        <TweakRadio label="Density" value={tweaks.density} onChange={v => setTweak('density', v)}
          options={[
            { value: 'editorial', label: 'Editorial' },
            { value: 'spacious',  label: 'Spacious' },
            { value: 'cinematic', label: 'Cinematic' }
          ]} />
      </TweakSection>
      <TweakSection title="Locale">
        <TweakRadio label="Language" value={tweaks.locale} onChange={v => setTweak('locale', v)}
          options={[{ value: 'en', label: 'English' }, { value: 'ar', label: 'العربية' }]} />
      </TweakSection>
    </TweaksPanel>
  );
}

// ============================================================
// APP
// ============================================================
const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "theme": "light",
  "accent": "petrol",
  "hero": "photo",
  "density": "spacious",
  "locale": "en"
}/*EDITMODE-END*/;

function App() {
  const [tweaks, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const locale = tweaks.locale;
  const setLocale = (v) => setTweak('locale', v);

  const t = useMemo_(() => {
    const base = window.JL_CONTENT[locale];
    return { ...base, locale };
  }, [locale]);

  const [quoteOpen, setQuoteOpen] = useState_(false);
  const [initialService, setInitialService] = useState_('charter');
  const openQuote = (svc) => {
    setInitialService(svc || 'charter');
    setQuoteOpen(true);
  };
  const closeQuote = () => setQuoteOpen(false);

  // apply data attributes on <html>
  useEffect_(() => {
    document.documentElement.setAttribute('data-theme', tweaks.theme);
    document.documentElement.setAttribute('data-accent', tweaks.accent);
    document.documentElement.setAttribute('data-density', tweaks.density);
    document.documentElement.setAttribute('dir', t.dir);
    document.documentElement.setAttribute('lang', locale);
  }, [tweaks, locale, t]);

  return (
    <Fragment_>
      <Nav t={t} locale={locale} setLocale={setLocale} onQuote={openQuote} />
      <Hero t={t} hero={tweaks.hero} onQuote={openQuote} />
      <TrustStrip t={t} />
      <Services t={t} onQuote={openQuote} />
      <Marquee locale={locale} />
      <Fleet t={t} onQuote={openQuote} />
      <Invictus t={t} onQuote={openQuote} />
      <FlightCare t={t} />
      <Presence t={t} />
      <About t={t} />
      <Contact t={t} onQuote={openQuote} />
      <Footer t={t} />
      <WhatsAppFab />
      <QuoteModal t={t} locale={locale} open={quoteOpen} onClose={closeQuote} initialService={initialService} />
      <JLTweaks tweaks={tweaks} setTweak={setTweak} />
    </Fragment_>
  );
}

ReactDOM.createRoot(document.getElementById('app')).render(<App />);
