// Multi-step Pre-arrival request form
const { useState: useStateF, useMemo: useMemoF } = React;

function PreArrivalForm({ t }) {
  const [step, setStep] = useStateF(0);
  const [data, setData] = useStateF({
    facility: "",
    tail: "",
    aircraftType: "",
    regCountry: "",
    eta: "",
    etd: "",
    pax: "",
    crew: "",
    services: [],
    notes: "",
    name: "",
    org: "",
    email: "",
    phone: "",
    contactPref: t.prearrival.contactOptions[2],
  });
  const [errors, setErrors] = useStateF({});
  const [submitted, setSubmitted] = useStateF(false);

  const update = (k, v) => {
    setData(d => ({ ...d, [k]: v }));
    if (errors[k]) setErrors(e => ({ ...e, [k]: null }));
  };
  const toggleService = (s) => {
    setData(d => ({
      ...d,
      services: d.services.includes(s) ? d.services.filter(x => x !== s) : [...d.services, s]
    }));
  };

  const validateStep = (s) => {
    const e = {};
    if (s === 0 && !data.facility) e.facility = true;
    if (s === 1) {
      if (!data.tail) e.tail = true;
      if (!data.aircraftType) e.aircraftType = true;
    }
    if (s === 2) {
      if (!data.eta) e.eta = true;
    }
    if (s === 4) {
      if (!data.name) e.name = true;
      if (!data.email) e.email = true;
    }
    setErrors(e);
    return Object.keys(e).length === 0;
  };

  const next = () => {
    if (!validateStep(step)) return;
    if (step < 4) setStep(s => s + 1);
    else handleSubmit();
  };
  const back = () => setStep(s => Math.max(0, s - 1));

  const handleSubmit = () => {
    if (!validateStep(4)) return;
    setSubmitted(true);
  };

  const goStep = (i) => {
    if (i <= step || submitted) {
      setStep(i);
    }
  };

  if (submitted) {
    return (
      <div className="form-card">
        <div className="form-success">
          <div className="form-success-mark">✓</div>
          <div className="eyebrow" style={{ color: "var(--ok)" }}>REQ-{Math.floor(Math.random() * 90000 + 10000)} · CRM SYNCED</div>
          <h3>{t.prearrival.successTitle}</h3>
          <p style={{ color: "var(--muted)", fontSize: 16, lineHeight: 1.4, maxWidth: "48ch", margin: 0 }}>{t.prearrival.successLede}</p>

          <dl className="form-success-summary">
            <dt>Facility</dt><dd>{data.facility}</dd>
            <dt>Tail</dt><dd className="mono" style={{ fontFamily: "var(--font-mono)" }}>{data.tail}</dd>
            <dt>Type</dt><dd>{data.aircraftType}</dd>
            <dt>ETA · ETD</dt><dd className="mono" style={{ fontFamily: "var(--font-mono)" }}>{data.eta} → {data.etd || "—"}</dd>
            <dt>PAX · Crew</dt><dd>{data.pax || "—"} · {data.crew || "—"}</dd>
            <dt>Services</dt><dd>{data.services.join(", ") || "—"}</dd>
            <dt>Contact</dt><dd>{data.name}, {data.org || "—"}<br/><span style={{color:"var(--muted)", fontSize: 12}}>{data.email} · {data.phone || "—"}</span></dd>
          </dl>

          <div style={{ marginTop: 24, paddingTop: 24, borderTop: "1px solid var(--border-soft)", width: "100%" }}>
            <span className="mono" style={{ color: "var(--muted)" }}>{t.prearrival.successContact}</span>
            <div style={{ display: "flex", gap: 16, marginTop: 12, flexWrap: "wrap" }}>
              <a className="btn btn-ghost btn-sm" href="tel:+97142073411">DXB FBO — +971 4 207 3411</a>
              <a className="btn btn-ghost btn-sm" href="tel:+971561743146">DWC FBO — +971 56 174 3146</a>
            </div>
          </div>
          <button
            className="btn btn-primary"
            style={{ marginTop: 16 }}
            onClick={() => { setSubmitted(false); setStep(0); setData(d => ({...d, tail: "", aircraftType: "", eta: "", etd: ""})); }}
          >
            {t.prearrival.successAnother} <span className="btn-arrow">{t.nav.ctaArrow}</span>
          </button>
        </div>
      </div>
    );
  }

  return (
    <div className="form-card">
      {/* Stepper */}
      <div className="form-stepper" role="tablist">
        {t.prearrival.steps.map((s, i) => (
          <button
            key={i}
            role="tab"
            aria-selected={step === i}
            className={"form-step " + (step === i ? "active " : "") + (i < step ? "done" : "")}
            onClick={() => goStep(i)}
          >
            <span className="form-step-num">0{i+1}</span>
            <span className="form-step-title">{s}</span>
          </button>
        ))}
      </div>

      {/* Body */}
      <div className="form-body">
        {step === 0 && (
          <div>
            <div className="form-section-eyebrow">{t.prearrival.steps[0]}</div>
            <h3 className="form-section-title">{t.prearrival.facilityLabel}</h3>
            <p className="subhead" style={{ fontSize: 14, marginBottom: 24 }}>{t.prearrival.facilityHelp}</p>
            <div className="chip-group">
              {[
                { v: "Dubai International — DXB", code: "OMDB" },
                { v: "Dubai World Central — DWC", code: "OMDW" },
              ].map((f, i) => (
                <button
                  key={i}
                  className={"chip-btn " + (data.facility === f.v ? "selected" : "")}
                  onClick={() => update("facility", f.v)}
                  style={{ padding: "16px 20px", fontSize: 16 }}
                >
                  {f.v} <span className="chip-code">{f.code}</span>
                </button>
              ))}
            </div>
            {errors.facility && <div className="field-error-msg" style={{ marginTop: 12 }}>{t.prearrival.requiredMsg}</div>}
          </div>
        )}

        {step === 1 && (
          <div>
            <div className="form-section-eyebrow">{t.prearrival.steps[1]}</div>
            <h3 className="form-section-title">{t.prearrival.typeLabel}</h3>
            <div className="form-grid">
              <div className={"field " + (errors.tail ? "field-error" : "")}>
                <label>{t.prearrival.tailLabel} *</label>
                <input
                  type="text"
                  className="mono-input"
                  placeholder={t.prearrival.tailPlaceholder}
                  value={data.tail}
                  onChange={e => update("tail", e.target.value.toUpperCase())}
                />
                {errors.tail && <span className="field-error-msg">{t.prearrival.requiredMsg}</span>}
              </div>
              <div className={"field " + (errors.aircraftType ? "field-error" : "")}>
                <label>{t.prearrival.typeLabel} *</label>
                <input
                  type="text"
                  placeholder={t.prearrival.typePlaceholder}
                  value={data.aircraftType}
                  onChange={e => update("aircraftType", e.target.value)}
                />
                {errors.aircraftType && <span className="field-error-msg">{t.prearrival.requiredMsg}</span>}
              </div>
              <div className="field col-2">
                <label>{t.prearrival.regLabel}</label>
                <input
                  type="text"
                  placeholder={t.prearrival.regPlaceholder}
                  value={data.regCountry}
                  onChange={e => update("regCountry", e.target.value)}
                />
              </div>
            </div>
          </div>
        )}

        {step === 2 && (
          <div>
            <div className="form-section-eyebrow">{t.prearrival.steps[2]}</div>
            <h3 className="form-section-title">{t.prearrival.eta} / {t.prearrival.etd}</h3>
            <div className="form-grid">
              <div className={"field " + (errors.eta ? "field-error" : "")}>
                <label>{t.prearrival.eta} *</label>
                <input
                  type="datetime-local"
                  className="mono-input"
                  value={data.eta}
                  onChange={e => update("eta", e.target.value)}
                />
                {errors.eta && <span className="field-error-msg">{t.prearrival.requiredMsg}</span>}
              </div>
              <div className="field">
                <label>{t.prearrival.etd}</label>
                <input
                  type="datetime-local"
                  className="mono-input"
                  value={data.etd}
                  onChange={e => update("etd", e.target.value)}
                />
              </div>
              <div className="field">
                <label>{t.prearrival.paxLabel}</label>
                <input
                  type="number"
                  min="0"
                  placeholder="0"
                  value={data.pax}
                  onChange={e => update("pax", e.target.value)}
                />
              </div>
              <div className="field">
                <label>{t.prearrival.crewLabel}</label>
                <input
                  type="number"
                  min="0"
                  placeholder="0"
                  value={data.crew}
                  onChange={e => update("crew", e.target.value)}
                />
              </div>
            </div>
          </div>
        )}

        {step === 3 && (
          <div>
            <div className="form-section-eyebrow">{t.prearrival.steps[3]}</div>
            <h3 className="form-section-title">{t.prearrival.servicesLabel}</h3>
            <div className="chip-group" style={{ marginBottom: 24 }}>
              {t.prearrival.services.map((s, i) => (
                <button
                  key={i}
                  className={"chip-btn " + (data.services.includes(s) ? "selected" : "")}
                  onClick={() => toggleService(s)}
                >
                  {s}
                </button>
              ))}
            </div>
            <div className="field">
              <label>{t.prearrival.notesLabel}</label>
              <textarea
                rows="4"
                placeholder={t.prearrival.notesPlaceholder}
                value={data.notes}
                onChange={e => update("notes", e.target.value)}
                style={{ resize: "vertical", borderBottom: "1px solid var(--border)", padding: "10px 0" }}
              />
            </div>
          </div>
        )}

        {step === 4 && (
          <div>
            <div className="form-section-eyebrow">{t.prearrival.steps[4]}</div>
            <h3 className="form-section-title">{t.prearrival.nameLabel}</h3>
            <div className="form-grid">
              <div className={"field " + (errors.name ? "field-error" : "")}>
                <label>{t.prearrival.nameLabel} *</label>
                <input
                  type="text"
                  value={data.name}
                  onChange={e => update("name", e.target.value)}
                />
                {errors.name && <span className="field-error-msg">{t.prearrival.requiredMsg}</span>}
              </div>
              <div className="field">
                <label>{t.prearrival.orgLabel}</label>
                <input
                  type="text"
                  value={data.org}
                  onChange={e => update("org", e.target.value)}
                />
              </div>
              <div className={"field " + (errors.email ? "field-error" : "")}>
                <label>{t.prearrival.emailLabel} *</label>
                <input
                  type="email"
                  value={data.email}
                  onChange={e => update("email", e.target.value)}
                />
                {errors.email && <span className="field-error-msg">{t.prearrival.requiredMsg}</span>}
              </div>
              <div className="field">
                <label>{t.prearrival.phoneLabel}</label>
                <input
                  type="tel"
                  className="mono-input"
                  value={data.phone}
                  onChange={e => update("phone", e.target.value)}
                />
              </div>
              <div className="field col-2">
                <label>{t.prearrival.contactPref}</label>
                <div className="chip-group" style={{ marginTop: 6 }}>
                  {t.prearrival.contactOptions.map((o, i) => (
                    <button
                      key={i}
                      className={"chip-btn " + (data.contactPref === o ? "selected" : "")}
                      onClick={() => update("contactPref", o)}
                    >
                      {o}
                    </button>
                  ))}
                </div>
              </div>
            </div>
          </div>
        )}

        <div className="form-footer">
          <span className="form-footer-meta">
            {t.prearrival.stepsMeta} {step + 1} {t.prearrival.of} 5
          </span>
          <div style={{ display: "flex", gap: 8 }}>
            {step > 0 && (
              <button className="btn btn-ghost btn-sm" onClick={back}>
                ← {t.prearrival.back}
              </button>
            )}
            <button className="btn btn-primary btn-sm" onClick={next}>
              {step < 4 ? t.prearrival.next : t.prearrival.submit}
              <span className="btn-arrow">{t.nav.ctaArrow}</span>
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}

function PreArrivalSection({ t }) {
  return (
    <section className="prearrival section shell" id="pre-arrival">
      <div className="container">
        <div className="prearrival-inner">
          <div className="prearrival-intro">
            <div className="eyebrow">{t.prearrival.eyebrow}</div>
            <h2>{t.prearrival.title}</h2>
            <p>{t.prearrival.sub}</p>
            <div className="prearrival-checklist">
              {t.prearrival.checklist.map((c, i) => (
                <div key={i} className="prearrival-check">{c}</div>
              ))}
            </div>
          </div>
          <PreArrivalForm t={t} />
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { PreArrivalForm, PreArrivalSection });
