/* global React */
(function(){
const { useState, useEffect } = React;

/* ───── QUOTE MODAL ───── */
function QuoteModal({ i, seed, onClose }){
  const [step, setStep] = useState(1);
  const [form, setForm] = useState({
    intent: seed.service || 'Private jet charter',
    terminal: seed.terminal || '',
    from: '', to: '', date: '', pax: 2,
    name: '', email: '', phone: '',
    notes: '',
  });
  const upd = (k,v)=> setForm(f=>({...f, [k]:v}));

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

  const submit = (e)=>{
    e.preventDefault();
    setStep(4);
  };

  const waLink = `https://wa.me/97142124000?text=${encodeURIComponent(
    `Hi Jetex, I'd like a quote.\nIntent: ${form.intent}\nFrom: ${form.from} → ${form.to}\nDate: ${form.date}\nPax: ${form.pax}\nName: ${form.name}`
  )}`;

  return (
    <div className="modal" role="dialog" aria-modal="true" onClick={(e)=>{ if(e.target.classList.contains('modal')) onClose(); }}>
      <div className="modal__card">
        <header className="modal__head">
          <div>
            <div className="modal__eyebrow mono"><span className="dot"/> CONCIERGE DESK</div>
            <div className="modal__title">{i.quote}</div>
          </div>
          <button className="modal__close" onClick={onClose} aria-label="Close">×</button>
        </header>

        <div className="modal__steps mono">
          {['Intent','Route','Contact'].map((s,k)=>(
            <div key={k} className={`mstep ${step===k+1?'is-current':''} ${step>k+1?'is-done':''}`}>
              <span>0{k+1}</span> {s}
            </div>
          ))}
        </div>

        <form onSubmit={submit} className="modal__body">
          {step===1 && (
            <>
              <Field label="Service">
                <div className="chips">
                  {['Private jet charter','Contact an FBO','Trip planning','Fuel','Aircraft sales','Concierge'].map(opt=>(
                    <button type="button" key={opt} className={`chip ${form.intent===opt?'is-active':''}`} onClick={()=>upd('intent',opt)}>{opt}</button>
                  ))}
                </div>
              </Field>
              {(form.intent==='Contact an FBO' || form.intent==='Fuel' || form.intent==='Trip planning') && (
                <Field label="Terminal / station (optional)">
                  <input value={form.terminal} onChange={e=>upd('terminal',e.target.value)} placeholder="e.g. Dubai South (DWC)" />
                </Field>
              )}
              <div className="modal__nav">
                <button type="button" className="btn btn--solid" onClick={()=>setStep(2)}>Continue <window.JetexUI1.Arrow/></button>
              </div>
            </>
          )}

          {step===2 && (
            <>
              <div className="row2">
                <Field label="From"><input value={form.from} onChange={e=>upd('from',e.target.value)} placeholder="DXB · Dubai" /></Field>
                <Field label="To"><input value={form.to} onChange={e=>upd('to',e.target.value)} placeholder="LBG · Paris Le Bourget" /></Field>
              </div>
              <div className="row2">
                <Field label="Date"><input type="date" value={form.date} onChange={e=>upd('date',e.target.value)} /></Field>
                <Field label="Passengers">
                  <div className="stepper">
                    <button type="button" onClick={()=>upd('pax', Math.max(1, form.pax-1))}>−</button>
                    <span className="mono">{form.pax}</span>
                    <button type="button" onClick={()=>upd('pax', form.pax+1)}>+</button>
                  </div>
                </Field>
              </div>
              <Field label="Notes (optional)">
                <textarea rows="3" value={form.notes} onChange={e=>upd('notes',e.target.value)} placeholder="Aircraft preference, return leg, dietary, ground transport…" />
              </Field>
              <div className="modal__nav">
                <button type="button" className="btn btn--ghost btn--dark" onClick={()=>setStep(1)}>Back</button>
                <button type="button" className="btn btn--solid" onClick={()=>setStep(3)}>Continue <window.JetexUI1.Arrow/></button>
              </div>
            </>
          )}

          {step===3 && (
            <>
              <Field label="Full name"><input required value={form.name} onChange={e=>upd('name',e.target.value)} /></Field>
              <div className="row2">
                <Field label="Email"><input required type="email" value={form.email} onChange={e=>upd('email',e.target.value)} /></Field>
                <Field label="Phone"><input value={form.phone} onChange={e=>upd('phone',e.target.value)} placeholder="+971…" /></Field>
              </div>
              <div className="modal__note mono">
                Bespoke quote only. Reviewed by a concierge — typically within one hour.
              </div>
              <div className="modal__nav">
                <button type="button" className="btn btn--ghost btn--dark" onClick={()=>setStep(2)}>Back</button>
                <a className="btn btn--ghost btn--dark" href={waLink} target="_blank" rel="noopener">Send via WhatsApp</a>
                <button type="submit" className="btn btn--solid">Submit enquiry <window.JetexUI1.Arrow/></button>
              </div>
            </>
          )}

          {step===4 && (
            <div className="done">
              <div className="done__tick" aria-hidden="true">
                <svg viewBox="0 0 24 24" width="36" height="36" fill="none"><path d="M4 12l5 5L20 6" stroke="currentColor" strokeWidth="2" strokeLinecap="square"/></svg>
              </div>
              <div className="done__title">Enquiry received.</div>
              <p className="done__copy">A Jetex concierge will reply to <strong>{form.email || 'your address'}</strong> within the hour. For anything urgent — <a href="tel:+97142124000">+971 4 212 4000</a>, 24/7.</p>
              <div className="modal__nav modal__nav--center">
                <button type="button" className="btn btn--solid" onClick={onClose}>Close</button>
              </div>
            </div>
          )}
        </form>
      </div>
    </div>
  );
}

function Field({label, children}){
  return (
    <label className="field">
      <div className="field__l mono">{label}</div>
      {children}
    </label>
  );
}

/* ───── TWEAKS PANEL ───── */
function TweaksPanel({ t, setTweak, onClose }){
  return (
    <div className="tweaks">
      <div className="tweaks__head">
        <div>Tweaks</div>
        <button onClick={onClose} aria-label="Close">×</button>
      </div>
      <div className="tweaks__body">
        <TwkSection label="Theme">
          <TwkRadio value={t.theme} options={[['noir','Noir'],['paper','Paper']]} onChange={(v)=>setTweak('theme',v)} />
        </TwkSection>
        <TwkSection label="Display font">
          <TwkRadio value={t.displayFont} options={[['Fraunces','Fraunces'],['Cormorant','Cormorant'],['Manrope','Manrope']]} onChange={(v)=>setTweak('displayFont',v)} />
        </TwkSection>
        <TwkSection label="Accent">
          <div className="twk-swatches">
            {['#FF6900','#E84A1B','#C2410C','#0A6CFF','#2E7D5B'].map(c=>(
              <button key={c} className={`twk-sw ${t.accent===c?'is-active':''}`} style={{background:c}} onClick={()=>setTweak('accent',c)} aria-label={c}/>
            ))}
          </div>
        </TwkSection>
        <TwkSection label="Concierge desk (hero panel)">
          <TwkToggle value={t.showTechnicals} onChange={(v)=>setTweak('showTechnicals',v)} />
        </TwkSection>
        <TwkSection label="Language">
          <TwkRadio value={t.lang} options={[['en','EN'],['ar','AR'],['ru','RU'],['zh','ZH']]} onChange={(v)=>setTweak('lang',v)} />
        </TwkSection>
      </div>
    </div>
  );
}

function TwkSection({label, children}){
  return (
    <div className="twk-section">
      <div className="twk-label mono">{label}</div>
      {children}
    </div>
  );
}

function TwkRadio({ value, options, onChange }){
  return (
    <div className="twk-radio">
      {options.map(([k,l])=>(
        <button key={k} className={`twk-radio__btn ${value===k?'is-active':''}`} onClick={()=>onChange(k)}>{l}</button>
      ))}
    </div>
  );
}

function TwkToggle({ value, onChange }){
  return (
    <button className={`twk-toggle ${value?'is-on':''}`} onClick={()=>onChange(!value)} aria-pressed={!!value}>
      <span/>
    </button>
  );
}

window.JetexUI4 = { QuoteModal, TweaksPanel };
})();
