/* Multi-step charter quote modal */

const { useState: useStateC, useEffect: useEffectC, useMemo: useMemoC } = React;

const CHARTER_AIRCRAFT = [
  { id: "g650",     name: "Gulfstream G650",    cls: "Ultra-Long-Range", thumb: "media/fleet-gulfstream-g650-exterior.webp" },
  { id: "global7500", name: "Bombardier Global 7500", cls: "Ultra-Long-Range", thumb: "media/fleet-global-7500-managed.webp" },
  { id: "global6000", name: "Bombardier Global 6000", cls: "Long-Range",       thumb: "media/fleet-global-6000-exterior-1.webp" },
  { id: "g600",     name: "Gulfstream G600",     cls: "Long-Range",        thumb: "media/fleet-gulfstream-g600-exterior-1.webp" },
  { id: "legacy650",name: "Embraer Legacy 650",  cls: "Super-Midsize",     thumb: "media/fleet-legacy-650-empire-livery.webp" },
  { id: "bbj",      name: "Boeing Business Jet", cls: "Airliner Class",    thumb: "media/fleet-boeing-business-jet-bbj.webp" },
  { id: "any",      name: "Operator's Choice",   cls: "We'll recommend",   thumb: "media/managed-jet-on-ramp.webp" },
];

const ROUTE_SUGGESTIONS = [
  ["DXB → LHR", "Dubai → London"],
  ["DXB → MLE", "Dubai → Maldives"],
  ["DXB → CDG", "Dubai → Paris"],
  ["DXB → LCA", "Dubai → Larnaca"],
  ["BOM → DXB", "Mumbai → Dubai"],
  ["DXB → JFK", "Dubai → New York"],
];

function CharterFlow({ open, onClose }) {
  const [step, setStep] = useStateC(0);
  const [data, setData] = useStateC({
    from: "DXB", to: "",
    tripType: "one-way",
    date: "", returnDate: "",
    pax: 6,
    aircraft: "",
    name: "", company: "", email: "", phone: "",
    notes: "",
  });
  const [submitted, setSubmitted] = useStateC(false);

  useEffectC(() => {
    if (!open) {
      // reset when closed
      setStep(0); setSubmitted(false);
      setData(d => ({ ...d }));
    }
  }, [open]);

  useEffectC(() => {
    const onKey = (e) => { if (e.key === "Escape" && open) onClose(); };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [open, onClose]);

  if (!open) return null;

  const steps = ["Route", "Date", "Aircraft", "Details", "Confirm"];

  const canNext = (() => {
    if (step === 0) return data.from.trim().length > 1 && data.to.trim().length > 1;
    if (step === 1) return data.date.length > 0 && (data.tripType !== "round-trip" || data.returnDate.length > 0);
    if (step === 2) return data.aircraft.length > 0;
    if (step === 3) return data.name.trim() && data.email.trim() && data.phone.trim();
    return true;
  })();

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

  const handleSubmit = () => {
    setSubmitted(true);
  };

  const ac = CHARTER_AIRCRAFT.find(a => a.id === data.aircraft);

  return (
    <div className="cq-backdrop" onClick={(e) => { if (e.target.classList.contains("cq-backdrop")) onClose(); }}>
      <div className="cq-panel" role="dialog" aria-modal="true" aria-labelledby="cq-title">
        <div className="cq-head">
          <div className="title" id="cq-title">Request a Charter Quote · CRM-routed</div>
          <button className="cq-close" onClick={onClose}>Close ✕</button>
        </div>

        {!submitted && (
          <div className="cq-progress" aria-label="Progress">
            {steps.map((label, i) => (
              <div key={label} className={"step" + (i < step ? " is-done" : "") + (i === step ? " is-active" : "")}>
                <span className="dot" />
                <span>0{i + 1} · {label}</span>
              </div>
            ))}
          </div>
        )}

        <div className="cq-body">
          {submitted ? (
            <SuccessPanel data={data} ac={ac} onClose={onClose} />
          ) : (
            <>
              {step === 0 && <StepRoute data={data} update={update} />}
              {step === 1 && <StepDate data={data} update={update} />}
              {step === 2 && <StepAircraft data={data} update={update} />}
              {step === 3 && <StepDetails data={data} update={update} />}
              {step === 4 && <StepConfirm data={data} ac={ac} />}
            </>
          )}
        </div>

        {!submitted && (
          <div className="cq-foot">
            <button className="back" onClick={() => step === 0 ? onClose() : setStep(step - 1)}>
              {step === 0 ? "← Cancel" : "← Back"}
            </button>
            <span className="ix">Step 0{step + 1} of 0{steps.length}</span>
            {step < steps.length - 1 ? (
              <button className="next btn" onClick={() => setStep(step + 1)} disabled={!canNext}>
                Continue <span className="arrow">→</span>
              </button>
            ) : (
              <button className="next btn" onClick={handleSubmit}>
                Send Enquiry <span className="arrow">→</span>
              </button>
            )}
          </div>
        )}
      </div>
    </div>
  );
}

function StepRoute({ data, update }) {
  return (
    <>
      <span className="eyebrow on-light step-eyebrow">01 · ROUTE</span>
      <h3 className="step-title">Where to, <em>and from where?</em></h3>
      <p className="step-sub">Use IATA codes or city names. We'll resolve the FBO at quote.</p>

      <div className="cq-route">
        <div className="cq-field" style={{ margin: 0 }}>
          <label htmlFor="cq-from">Departure</label>
          <input id="cq-from" type="text" value={data.from} onChange={(e) => update("from", e.target.value)} placeholder="DXB · Dubai" />
        </div>
        <button
          className="cq-route-swap"
          type="button"
          aria-label="Swap"
          onClick={() => { update("from", data.to); update("to", data.from); }}
        >
          ⇄
        </button>
        <div className="cq-field" style={{ margin: 0 }}>
          <label htmlFor="cq-to">Arrival</label>
          <input id="cq-to" type="text" value={data.to} onChange={(e) => update("to", e.target.value)} placeholder="MLE · Maldives" />
        </div>
      </div>

      <div className="cq-suggestions">
        {ROUTE_SUGGESTIONS.map((r, i) => {
          const [code, label] = r;
          const [f, t] = code.split(" → ");
          const isActive = data.from === f && data.to === t;
          return (
            <button
              key={i}
              type="button"
              className={"pill" + (isActive ? " is-active" : "")}
              onClick={() => { update("from", f); update("to", t); }}
              title={label}
            >
              {code}
            </button>
          );
        })}
      </div>
    </>
  );
}

function StepDate({ data, update }) {
  return (
    <>
      <span className="eyebrow on-light step-eyebrow">02 · TIMING</span>
      <h3 className="step-title">When are we <em>flying?</em></h3>
      <p className="step-sub">Add the return leg if needed. All times confirmed at quote.</p>

      <div className="cq-field">
        <label>Trip type</label>
        <div className="cq-suggestions" style={{ marginTop: 4 }}>
          {["one-way", "round-trip", "multi-leg"].map(t => (
            <button
              key={t}
              type="button"
              className={"pill" + (data.tripType === t ? " is-active" : "")}
              onClick={() => update("tripType", t)}
            >
              {t.replace("-", " ")}
            </button>
          ))}
        </div>
      </div>

      <div className="cq-row2">
        <div className="cq-field">
          <label htmlFor="cq-date">Departure date</label>
          <input id="cq-date" type="date" value={data.date} onChange={(e) => update("date", e.target.value)} />
        </div>
        {data.tripType === "round-trip" && (
          <div className="cq-field">
            <label htmlFor="cq-return">Return date</label>
            <input id="cq-return" type="date" value={data.returnDate} onChange={(e) => update("returnDate", e.target.value)} />
          </div>
        )}
      </div>

      <div className="cq-field">
        <label htmlFor="cq-pax">Passengers</label>
        <div style={{ display: "flex", alignItems: "center", gap: 16 }}>
          <input
            id="cq-pax"
            type="range"
            min="1" max="18" step="1"
            value={data.pax}
            onChange={(e) => update("pax", parseInt(e.target.value, 10))}
            style={{ flex: 1, accentColor: "var(--gold)" }}
          />
          <span style={{ fontFamily: "Instrument Serif, serif", fontSize: 32, minWidth: 60, textAlign: "right" }}>{data.pax}</span>
        </div>
      </div>
    </>
  );
}

function StepAircraft({ data, update }) {
  return (
    <>
      <span className="eyebrow on-light step-eyebrow">03 · AIRCRAFT</span>
      <h3 className="step-title">Preferred <em>aircraft.</em></h3>
      <p className="step-sub">If you're unsure, choose <em style={{ color: "var(--gold-deep)" }}>Operator's Choice</em> — we'll recommend based on range, passengers and ground times.</p>

      <div className="cq-aircraft-grid">
        {CHARTER_AIRCRAFT.map(a => (
          <button
            key={a.id}
            type="button"
            className={"cq-aircraft-card" + (data.aircraft === a.id ? " is-active" : "")}
            onClick={() => update("aircraft", a.id)}
          >
            <div className="thumb" style={{ backgroundImage: `url(${a.thumb})` }} />
            <div className="meta">
              <div className="ac-name">{a.name}</div>
              <div className="ac-class">{a.cls}</div>
            </div>
          </button>
        ))}
      </div>
    </>
  );
}

function StepDetails({ data, update }) {
  return (
    <>
      <span className="eyebrow on-light step-eyebrow">04 · CONTACT</span>
      <h3 className="step-title">A direct line to <em>you.</em></h3>
      <p className="step-sub">A member of the Dubai operations desk will respond personally.</p>

      <div className="cq-row2">
        <div className="cq-field">
          <label htmlFor="cq-name">Full name</label>
          <input id="cq-name" type="text" value={data.name} onChange={(e) => update("name", e.target.value)} placeholder="" />
        </div>
        <div className="cq-field">
          <label htmlFor="cq-company">Company / Office</label>
          <input id="cq-company" type="text" value={data.company} onChange={(e) => update("company", e.target.value)} placeholder="Optional" />
        </div>
      </div>

      <div className="cq-row2">
        <div className="cq-field">
          <label htmlFor="cq-email">Email</label>
          <input id="cq-email" type="email" value={data.email} onChange={(e) => update("email", e.target.value)} />
        </div>
        <div className="cq-field">
          <label htmlFor="cq-phone">Phone (incl. country code)</label>
          <input id="cq-phone" type="tel" value={data.phone} onChange={(e) => update("phone", e.target.value)} placeholder="+971 …" />
        </div>
      </div>

      <div className="cq-field">
        <label htmlFor="cq-notes">Notes (optional)</label>
        <textarea id="cq-notes" value={data.notes} onChange={(e) => update("notes", e.target.value)} placeholder="Catering preferences, pets, ground transport, special requirements…" />
      </div>
    </>
  );
}

function StepConfirm({ data, ac }) {
  return (
    <>
      <span className="eyebrow on-light step-eyebrow">05 · CONFIRM</span>
      <h3 className="step-title">Review and <em>send.</em></h3>
      <p className="step-sub">No price will be quoted here — a member of our team will respond with a bespoke quote.</p>

      <div className="cq-summary">
        <div className="sum-row"><span className="k">Route</span><span className="v is-serif">{data.from} → {data.to}</span></div>
        <div className="sum-row"><span className="k">Trip</span><span className="v">{data.tripType}</span></div>
        <div className="sum-row"><span className="k">Date</span><span className="v">{data.date || "—"}{data.tripType === "round-trip" && data.returnDate ? ` → ${data.returnDate}` : ""}</span></div>
        <div className="sum-row"><span className="k">PAX</span><span className="v">{data.pax}</span></div>
        <div className="sum-row"><span className="k">Aircraft</span><span className="v is-serif">{ac ? ac.name : "—"}</span></div>
        <div className="sum-row"><span className="k">Contact</span><span className="v">{data.name} · {data.email} · {data.phone}</span></div>
        {data.company && <div className="sum-row"><span className="k">Company</span><span className="v">{data.company}</span></div>}
        {data.notes && <div className="sum-row"><span className="k">Notes</span><span className="v" style={{ fontWeight: 400, color: "var(--ink-2)" }}>{data.notes}</span></div>}
      </div>

      <div className="caps" style={{ color: "var(--muted-2)", fontSize: 10.5 }}>
        Submitting routes to Empire's Dubai CRM via Avinode / Formspree pipeline (prototype: no send).
      </div>
    </>
  );
}

function SuccessPanel({ data, ac, onClose }) {
  return (
    <div className="cq-success">
      <div className="check">✓</div>
      <h3 className="h-section">Enquiry <em>received.</em></h3>
      <p className="lede" style={{ marginTop: 12, maxWidth: "44ch", marginLeft: "auto", marginRight: "auto" }}>
        Reference <span className="mono" style={{ color: "var(--gold-deep)" }}>EAG-{Math.random().toString(36).substring(2, 8).toUpperCase()}</span> has been routed to charter@empire.aero. A member of the Dubai team will respond personally.
      </p>
      <div style={{ marginTop: 32, display: "flex", justifyContent: "center", gap: 12 }}>
        <button className="btn btn-ghost-light" onClick={onClose}>Close</button>
        <a className="btn btn-gold" href="tel:+971565091116">
          Or call now → <span className="mono" style={{ marginLeft: 8, fontSize: 11 }}>+971 56 509 1116</span>
        </a>
      </div>
    </div>
  );
}

Object.assign(window, { CharterFlow });
