/* global React */
// FirstSteps — page components: Home, ProgramDetail, Apply, ThankYou

const { useState, useMemo, useEffect, useRef, forwardRef, useImperativeHandle } = React;

// Canonical English position values — what we send in the payload regardless of UI language.
// The localized labels (window.I18N[lang].form.positions) render at the same indices.
const POSITION_VALUES = ["Goalkeeper", "Defender", "Midfielder", "Forward", "Other"];

// ----- International phone field (intl-tel-input wrapper) -----
const PhoneInput = forwardRef(function PhoneInput({ lang, onValid }, ref) {
  const inputRef = useRef(null);
  const itiRef = useRef(null);

  useEffect(() => {
    if (!inputRef.current || !window.intlTelInput) return;
    // Default country by interface language. EN/ES → Spain, RU → Russia.
    const initial = lang === "ru" ? "ru" : "es";
    itiRef.current = window.intlTelInput(inputRef.current, {
      initialCountry: initial,
      preferredCountries: ["es", "ru", "gb", "us", "de", "fr", "it", "pt", "kz", "ua"],
      separateDialCode: false,
      autoPlaceholder: "polite",
      formatOnDisplay: true,
      utilsScript: "https://cdn.jsdelivr.net/npm/intl-tel-input@18.2.1/build/js/utils.js",
    });
    return () => {
      try { itiRef.current && itiRef.current.destroy(); } catch (e) {}
      itiRef.current = null;
    };
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  // Update default country when interface language changes — only if user hasn't typed yet.
  useEffect(() => {
    if (!itiRef.current || !inputRef.current) return;
    if (inputRef.current.value && inputRef.current.value.trim() !== "") return;
    itiRef.current.setCountry(lang === "ru" ? "ru" : "es");
  }, [lang]);

  useImperativeHandle(ref, () => ({
    getNumber: () => {
      if (itiRef.current) {
        const n = itiRef.current.getNumber();
        if (n) return n;
      }
      return inputRef.current ? inputRef.current.value : "";
    },
    isValid: () => {
      if (!itiRef.current || !inputRef.current) return false;
      const raw = inputRef.current.value || "";
      if (raw.trim() === "") return false;
      try { return !!itiRef.current.isValidNumber(); }
      catch (e) { return raw.replace(/\D/g, "").length >= 7; }
    },
    getRaw: () => inputRef.current ? inputRef.current.value : "",
  }), []);

  return (
    <input
      ref={inputRef}
      type="tel"
      autoComplete="tel"
      onChange={() => onValid && onValid()}
    />
  );
});

// ---------- HOME ----------
// Carousel pool: 4 featured programs (per brief)
const FEATURED_IDS = ["full-year-tenerife", "trial", "community", "analysis"];

// "Our cases" — short MP4 clips that play inline in the carousel between the
// Programs and Partners sections. Files live in /assets/cases.
const CASE_VIDEOS = [
  { src: "assets/cases/Sultan_full_year.mp4",    title: "Sultan · Full-year program" },
  { src: "assets/cases/Ismaila_trials.mp4",      title: "Ismaila · Trials" },
  { src: "assets/cases/Constantinos_trials.mp4", title: "Constantinos · Trials" },
  { src: "assets/cases/Lucas_trials.mp4",        title: "Lucas · Trials" },
  { src: "assets/cases/Efthimis_trials.mp4",     title: "Efthimis · Trials" },
];

// Program-detail overview videos: only shown on the full-year program page,
// directly after the Requirements block. Mix of training footage, parent
// testimony and a coach's perspective.
const FULL_YEAR_OVERVIEW_VIDEOS = [
  { src: "assets/overview/training-overview.mp4", title: "Inside training" },
  { src: "assets/overview/parent-comment.mp4",    title: "Parent perspective" },
  { src: "assets/overview/aris-aristidou.mp4",    title: "Mr Aris Aristidou — head coach" },
  { src: "assets/cases/Ismaila_trials.mp4",       title: "Ismaila · On the pitch" },
  { src: "assets/cases/Sultan_full_year.mp4",     title: "Sultan · Full-year program" },
];

function scrollToId(id, offset = 80) {
  const el = document.getElementById(id);
  if (el) window.scrollTo({ top: el.offsetTop - offset, behavior: "smooth" });
}

function ProgramCarousel({ lang, navigate, programs }) {
  const t = window.I18N[lang];
  const det = t.detail;
  const [index, setIndex] = useState(0);
  const total = programs.length;

  const go = (delta) => setIndex((i) => (i + delta + total) % total);
  const prev = () => go(-1);
  const next = () => go(+1);

  // Auto-advance — runs continuously regardless of hover/focus so the reveal
  // animation comes from carousel scroll, not from mouse interactions.
  useEffect(() => {
    const id = setInterval(() => setIndex((i) => (i + 1) % total), 5500);
    return () => clearInterval(id);
  }, [total]);

  useEffect(() => {
    const onKey = (e) => {
      if (e.key === "ArrowLeft") prev();
      if (e.key === "ArrowRight") next();
    };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, []);

  const prevI = (index - 1 + total) % total;
  const nextI = (index + 1) % total;
  const prevP = programs[prevI];
  const curP  = programs[index];
  const nextP = programs[nextI];

  const SlideCard = ({ p, i, active }) => {
    const bg = (window.PROGRAM_IMAGES && window.PROGRAM_IMAGES[p.id]) || null;
    return (
      <div
        className={"carousel-slide" + (active ? " is-active" : " is-side")}
        onClick={() => {
          if (active) navigate({ name: "program", id: p.id });
          else setIndex(i);
        }}
        role="button"
        tabIndex={0}
        onKeyDown={(e) => {
          if (e.key === "Enter") {
            if (active) navigate({ name: "program", id: p.id });
            else setIndex(i);
          }
        }}
        aria-label={p.title[lang]}
      >
        <div
          className={"slide-card" + (bg ? " has-image" : "")}
          style={bg ? { backgroundImage: "url(" + bg + ")" } : null}
        >
          {bg && <div className="slide-card-overlay" aria-hidden="true" />}
          <div className="slide-card-content">
            <h3 className="slide-title">{p.title[lang]}</h3>
            <p className="slide-desc">{p.short[lang]}</p>
            <div className="slide-cta">
              <button
                className="btn btn-primary btn-large"
                onClick={(e) => { e.stopPropagation(); scrollToId("programs"); }}
              >
                {t.cta.learn} <Arrow size={14} />
              </button>
            </div>
          </div>
        </div>
      </div>
    );
  };

  return (
    <section className="carousel-section">
      <div className="carousel-frame">
        <button className="car-nav prev" onClick={prev} aria-label="Previous program">
          <ArrowLeft size={20} />
        </button>
        <button className="car-nav next" onClick={next} aria-label="Next program">
          <Arrow size={20} />
        </button>

        <div className="carousel-track">
          <SlideCard p={prevP} i={prevI} active={false} />
          <SlideCard key={index} p={curP} i={index} active={true} />
          <SlideCard p={nextP} i={nextI} active={false} />
        </div>

        <div className="car-dots" role="tablist">
          {programs.map((p, i) => (
            <button
              key={p.id}
              className={"car-dot" + (i === index ? " active" : "")}
              onClick={() => setIndex(i)}
              aria-label={p.title[lang]}
              aria-selected={i === index}
            />
          ))}
        </div>
      </div>
    </section>
  );
}

function HomePage({ lang, navigate }) {
  const t = window.I18N[lang];
  const featured = FEATURED_IDS.map((id) => window.PROGRAMS.find((p) => p.id === id)).filter(Boolean);
  return (
    <main className="fade-in">
      <section className="hero hero-with-bg">
        <div className="hero-bg" aria-hidden="true"></div>
        <div className="container">
          <div className="eyebrow">{t.hero.eyebrow}</div>
          <h1 className="slogan">
            <span className="row1">{t.hero.slogan_1}</span>{" "}
            <span className="row2 accent">{t.hero.slogan_2}</span>
          </h1>
        </div>
      </section>

      <ProgramCarousel lang={lang} navigate={navigate} programs={featured} />

      <section className="section" id="programs">
        <div className="container">
          <div className="section-head">
            <div className="left">
              <div className="eyebrow dark">{t.programs.eyebrow}</div>
              <h2 className="h2">{t.programs.title}</h2>
              <p className="desc">{t.programs.desc}</p>
            </div>
          </div>
          <div className="programs-grid">
            {window.PROGRAMS.map((p, i) => (
              <ProgramCard key={p.id} program={p} idx={i} lang={lang} navigate={navigate} />
            ))}
          </div>
        </div>
      </section>

      <section className="section cases-section" id="cases">
        <div className="container">
          <div className="section-head">
            <div className="left">
              <div className="eyebrow dark">{t.cases.eyebrow}</div>
              <h2 className="h2">{t.cases.title}</h2>
              <p className="desc">{t.cases.desc}</p>
            </div>
          </div>
          <VideoCarousel
            videos={CASE_VIDEOS}
            labels={{ sound: t.cases.sound, expand: t.cases.expand, close: t.cases.close }}
          />
        </div>
      </section>

      <section className="partners" id="partners">
        <div className="container">
          <div className="partners-head">
            <div className="title">{t.partners.title}</div>
            <div className="meta">{t.partners.meta}</div>
          </div>
          <div className="partners-grid">
            {window.PARTNERS.map((p) => (
              <div className="partner-card" key={p.name}>
                <div className="partner-logo">
                  <img src={p.logo} alt={p.name} loading="lazy" />
                </div>
                <div className="partner-name">{p.name}</div>
                <div className="partner-loc">{p.loc}</div>
              </div>
            ))}
          </div>
        </div>
      </section>

      <section className="section tight how-section how-with-bg" id="how">
        <div className="how-bg" aria-hidden="true"></div>
        <div className="container">
          <div className="section-head">
            <div className="left">
              <div className="eyebrow dark">{t.how.eyebrow}</div>
              <h2 className="h2">{t.how.title}</h2>
            </div>
          </div>
          <div className="how-grid">
            {t.how.steps.map((s, i) => (
              <div className="step" key={i}>
                <div className="num">0{i + 1}</div>
                <div className="title">{s.t}</div>
                <div className="body">{s.b}</div>
              </div>
            ))}
          </div>
        </div>
      </section>

      <section className="section" id="about" style={{ background: "var(--bg-soft)" }}>
        <div className="container">
          <div className="about-grid">
            <div>
              <div className="eyebrow dark">{t.about.eyebrow}</div>
              <h2 className="h2" style={{ marginTop: 14 }}>{t.about.title}</h2>
              <p className="lead" style={{ marginTop: 24, color: "var(--muted)", maxWidth: 560 }}>{t.about.body}</p>
            </div>
            <div className="about-pillars">
              {t.about.pillars.map((p, i) => (
                <div className="pillar" key={i}>
                  <div className="pillar-k">{p.k}</div>
                  <div className="pillar-v">{p.v}</div>
                </div>
              ))}
            </div>
          </div>
        </div>
      </section>

      <section className="section tight" id="collab" style={{ background: "var(--navy-800)", color: "#fff" }}>
        <div className="container">
          <div className="collab-row">
            <div>
              <div className="eyebrow" style={{ color: "var(--yellow)" }}>{t.collab.eyebrow}</div>
              <h2 className="h2" style={{ marginTop: 14, color: "#fff" }}>{t.collab.title}</h2>
              <p style={{ marginTop: 24, color: "rgba(255,255,255,0.78)", maxWidth: 640, fontSize: 17, lineHeight: 1.6 }}>{t.collab.body}</p>
            </div>
            <button className="btn btn-primary btn-large" onClick={() => navigate({ name: "collaboration" })}>
              {t.cta.talkToUs} <Arrow size={14} />
            </button>
          </div>
        </div>
      </section>

      <section className="section" id="history">
        <div className="container">
          <div className="section-head">
            <div className="left">
              <div className="eyebrow dark">{t.history.eyebrow}</div>
              <h2 className="h2">{t.history.title}</h2>
            </div>
          </div>
          <div className="history-grid">
            {t.history.items.map((h, i) => (
              <div className="hist" key={i}>
                <div className="hist-year">{h.y}</div>
                <div className="hist-title">{h.t}</div>
                <div className="hist-body">{h.b}</div>
              </div>
            ))}
          </div>
        </div>
      </section>

      <span id="contact"></span>
    </main>
  );
}

// ---------- PROGRAM DETAIL ----------
function TrialAgePicker({ lang, program, navigate }) {
  const t = window.I18N[lang].detail;
  const heroImg = (window.PROGRAM_IMAGES && window.PROGRAM_IMAGES[program.id]) || null;
  return (
    <main className="fade-in">
      <section className={"detail-hero" + (heroImg ? " has-image" : "")} style={heroImg ? { backgroundImage: "linear-gradient(180deg, rgba(10,31,68,0.78) 0%, rgba(10,31,68,0.92) 100%), url(" + heroImg + ")" } : null}>
        <div className="container">
          <div className="crumb" onClick={() => navigate({ name: "home" })}>
            ← {t.back}
          </div>
          <div className="tag">{t.tag}</div>
          <h1 className="h1">{program.title[lang]}</h1>
          <p className="sub">{program.short[lang]}</p>
        </div>
      </section>

      <section className="picker">
        <div className="container">
          <div className="picker-head">
            <div className="eyebrow dark">{t.pickerTitle}</div>
            <p className="picker-sub">{t.pickerSub}</p>
          </div>
          <div className="picker-grid">
            {program.tracks.map((tr) => (
              <button
                className="picker-card"
                key={tr.id}
                onClick={() => navigate({ name: "program", id: program.id, track: tr.id })}
              >
                <div className="picker-age">{tr.ageBand[lang]}</div>
                <div className="picker-title">{tr.title[lang]}</div>
                <div className="picker-club">{typeof tr.club === "string" ? tr.club : tr.club[lang]}</div>
                <div className="picker-arrow"><Arrow size={20} /></div>
              </button>
            ))}
          </div>
        </div>
      </section>
    </main>
  );
}

function TrackDetail({ lang, program, track, navigate }) {
  const t = window.I18N[lang].detail;
  const lblClub = typeof track.club === "string" ? track.club : track.club[lang];
  const heroImg = (window.PROGRAM_IMAGES && window.PROGRAM_IMAGES[program.id]) || null;
  return (
    <main className="fade-in">
      <section className={"detail-hero" + (heroImg ? " has-image" : "")} style={heroImg ? { backgroundImage: "linear-gradient(180deg, rgba(10,31,68,0.78) 0%, rgba(10,31,68,0.92) 100%), url(" + heroImg + ")" } : null}>
        <div className="container">
          <div className="crumb" onClick={() => navigate({ name: "program", id: program.id })}>
            ← {t.backToPicker}
          </div>
          <div className="tag">{track.ageBand[lang]} · {lblClub}</div>
          <h1 className="h1">{track.title[lang]}</h1>
          <p className="sub">{track.sub[lang]}</p>
        </div>
      </section>

      <div className="container">
        <div className="detail-body">
          <div>
            <div className="detail-section">
              <h3>{t.overview}</h3>
              {track.overview[lang].map((p, i) => <p key={i}>{p}</p>)}
            </div>
            <div className="detail-section">
              <h3>{t.audience}</h3>
              <ul>
                {track.audience[lang].map((item, i) => <li key={i}>{item}</li>)}
              </ul>
            </div>
            <div className="detail-section">
              <h3>{t.requirements}</h3>
              <ul>
                {track.requirements[lang].map((item, i) => <li key={i}>{item}</li>)}
              </ul>
            </div>
          </div>

          <aside>
            <div className="apply-panel">
              <div className="label">{t.applyTitle}</div>
              <div className="price">{track.title[lang]}</div>
              <div style={{ fontSize: 14, color: "var(--muted)", marginTop: 10 }}>{t.applySub}</div>

              <div className="facts">
                <div className="fact"><span className="k">{t.duration}</span><span className="v">{track.duration[lang]}</span></div>
                <div className="fact"><span className="k">{t.age}</span><span className="v">{track.ageBand[lang]}</span></div>
                <div className="fact"><span className="k">{t.location}</span><span className="v">{track.location[lang]}</span></div>
                <div className="fact"><span className="k">{t.price}</span><span className="v">{track.priceFrom[lang]}</span></div>
              </div>

              <button
                className="btn btn-primary btn-large"
                onClick={() => navigate({ name: "apply", id: program.id, track: track.id })}
              >
                {window.I18N[lang].cta.apply} <Arrow size={14} />
              </button>
            </div>
          </aside>
        </div>
      </div>
    </main>
  );
}

function ProgramDetail({ lang, programId, trackId, navigate }) {
  const t = window.I18N[lang].detail;
  const program = window.PROGRAMS.find((p) => p.id === programId);
  useEffect(() => { window.scrollTo(0, 0); }, [programId, trackId]);

  if (!program) {
    return <main className="container" style={{ padding: 96 }}>Not found.</main>;
  }

  // Trial-style program with tracks → show age picker, then specific track
  if (program.tracks) {
    if (trackId) {
      const track = program.tracks.find((x) => x.id === trackId);
      if (!track) return <main className="container" style={{ padding: 96 }}>Track not found.</main>;
      return <TrackDetail lang={lang} program={program} track={track} navigate={navigate} />;
    }
    return <TrialAgePicker lang={lang} program={program} navigate={navigate} />;
  }

  // Standard program detail
  const heroImg = (window.PROGRAM_IMAGES && window.PROGRAM_IMAGES[program.id]) || null;
  return (
    <main className="fade-in">
      <section className={"detail-hero" + (heroImg ? " has-image" : "")} style={heroImg ? { backgroundImage: "linear-gradient(180deg, rgba(10,31,68,0.78) 0%, rgba(10,31,68,0.92) 100%), url(" + heroImg + ")" } : null}>
        <div className="container">
          <div className="crumb" onClick={() => navigate({ name: "home" })}>
            ← {t.back}
          </div>
          <div className="tag">{t.tag}</div>
          <h1 className="h1">{program.title[lang]}</h1>
          <p className="sub">{program.short[lang]}</p>
        </div>
      </section>

      <div className="container">
        <div className="detail-body">
          <div>
            <div className="detail-section">
              <h3>{t.overview}</h3>
              {program.overview[lang].map((p, i) => <p key={i}>{p}</p>)}
            </div>
            <div className="detail-section">
              <h3>{t.audience}</h3>
              <ul>
                {program.audience[lang].map((item, i) => <li key={i}>{item}</li>)}
              </ul>
            </div>
            <div className="detail-section">
              <h3>{t.requirements}</h3>
              <ul>
                {program.requirements[lang].map((item, i) => <li key={i}>{item}</li>)}
              </ul>
            </div>
          </div>

          <aside>
            <div className="apply-panel">
              <div className="label">{t.applyTitle}</div>
              <div className="price">{program.title[lang]}</div>
              <div style={{ fontSize: 14, color: "var(--muted)", marginTop: 10 }}>{t.applySub}</div>

              <div className="facts">
                <div className="fact"><span className="k">{t.duration}</span><span className="v">{program.duration[lang]}</span></div>
                <div className="fact"><span className="k">{t.age}</span><span className="v">{program.age[lang]}</span></div>
                <div className="fact"><span className="k">{t.location}</span><span className="v">{program.location[lang]}</span></div>
                <div className="fact"><span className="k">{t.format}</span><span className="v">{program.format[lang]}</span></div>
              </div>

              <button
                className="btn btn-primary btn-large"
                onClick={() => navigate({ name: "apply", id: program.id })}
              >
                {window.I18N[lang].cta.apply} <Arrow size={14} />
              </button>
            </div>
          </aside>
        </div>
      </div>

      {program.id === "full-year-tenerife" && (
        <section className="section program-overview-videos" style={{ background: "var(--bg-soft)" }}>
          <div className="container">
            <div className="section-head">
              <div className="left">
                <div className="eyebrow dark">{window.I18N[lang].cases.eyebrow}</div>
                <h2 className="h2">{t.programOverview}</h2>
              </div>
            </div>
            <VideoCarousel
              videos={FULL_YEAR_OVERVIEW_VIDEOS}
              labels={{
                sound:  window.I18N[lang].cases.sound,
                expand: window.I18N[lang].cases.expand,
                close:  window.I18N[lang].cases.close,
              }}
            />
          </div>
        </section>
      )}
    </main>
  );
}

// ---------- APPLY FORM ----------
// Single form at #/apply/form. Receives its program/track context (and
// optionally a "collab" form-type) from sessionStorage via fsReadApplyContext.
function ApplyPage({ lang, navigate }) {
  // Read context once on mount. We don't react to changes — the form is
  // entered fresh whenever the user navigates here.
  const ctx = useMemo(() => {
    const c = (typeof window.fsReadApplyContext === "function") ? window.fsReadApplyContext() : null;
    return c || {};
  }, []);
  const formType = ctx.type === "collab" ? "collab" : "player";
  const programId = ctx.programId || null;
  const trackId   = ctx.trackId   || null;

  const t = window.I18N[lang].form;
  // Collaboration form-specific strings (different title/sub/legal copy).
  const ct = window.I18N[lang].collabForm || null;
  const program = programId ? window.PROGRAMS.find((p) => p.id === programId) : null;
  const track = trackId && program && program.tracks
    ? program.tracks.find((x) => x.id === trackId)
    : null;
  const [values, setValues] = useState({
    first: "", last: "", email: "", age: "",
    club: "", position: "", video: "",
    videoLater: false, // when true, the video field is locked and validation is skipped
    website: "", // honeypot — must remain empty
  });
  const [errors, setErrors] = useState({});
  const [submitting, setSubmitting] = useState(false);
  const [submitError, setSubmitError] = useState(false);
  const [collabSubmitted, setCollabSubmitted] = useState(false);
  const phoneRef = useRef(null);

  // Capture UTM parameters once on mount so they survive in-app navigation.
  const utm = useMemo(() => {
    const keys = ["utm_source", "utm_campaign", "utm_medium", "utm_content", "utm_term"];
    const out = {};
    try {
      const sp = new URLSearchParams(window.location.search);
      keys.forEach((k) => { out[k] = sp.get(k) || ""; });
    } catch (err) {
      keys.forEach((k) => { out[k] = ""; });
    }
    return out;
  }, []);

  useEffect(() => { window.scrollTo(0, 0); }, []);

  // Player form requires a program. Collaboration form does not.
  if (formType === "player" && !program) {
    // No context (e.g. user opened #/apply/form directly with empty storage).
    // Send them back home to pick a program.
    return (
      <main className="container" style={{ padding: 96, textAlign: "center" }}>
        <p style={{ marginBottom: 16 }}>{(t && t.errors && t.errors.noProgram) || "Please choose a program first."}</p>
        <button className="btn btn-primary" onClick={() => navigate({ name: "home" })}>
          {window.I18N[lang].nav && window.I18N[lang].nav.programs ? window.I18N[lang].nav.programs : "Programs"}
        </button>
      </main>
    );
  }

  const set = (k) => (e) => setValues({ ...values, [k]: e.target.value });

  const validate = () => {
    const e = {};
    const errs = formType === "collab" ? (ct && ct.errors) || t.errors : t.errors;
    if (!values.first.trim()) e.first = errs.first;
    if (!values.last.trim()) e.last = errs.last;
    if (!phoneRef.current || !phoneRef.current.isValid()) e.phone = errs.phone;
    if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(values.email)) e.email = errs.email;
    // Player-only fields.
    if (formType === "player") {
      const a = parseInt(values.age, 10);
      if (!a || a < 4 || a > 25) e.age = t.errors.age;
      // Video link is required UNLESS the applicant checked "I'll send later".
      if (!values.videoLater) {
        if (!values.video.trim()) e.video = t.errors.video;
        else if (!/^https:\/\/\S+\.\S+/i.test(values.video.trim())) e.videoFormat = t.errors.videoFormat;
      }
    }
    return e;
  };

  const submit = async (e) => {
    e.preventDefault();
    if (submitting) return;

    // Honeypot: if a bot filled this hidden field, silently ignore.
    if (values.website && values.website.trim() !== "") {
      return;
    }

    const errs = validate();
    setErrors(errs);
    if (Object.keys(errs).length > 0) {
      const firstErrField = document.querySelector(".field.error input, .field.error select");
      if (firstErrField) firstErrField.focus();
      return;
    }

    setSubmitError(false);
    setSubmitting(true);

    const programTitle = formType === "collab"
      ? "Collaboration"
      : (track
          ? (track.title && track.title.en) || (program.title && program.title.en) || program.id
          : (program.title && program.title.en) || program.id);

    const phoneE164 = phoneRef.current ? phoneRef.current.getNumber() : "";

    const payload = {
      first_name:   values.first.trim(),
      last_name:    values.last.trim(),
      phone:        phoneE164,
      email:        values.email.trim(),
      age:          formType === "collab" ? "" : parseInt(values.age, 10),
      current_club: formType === "collab" ? "" : values.club.trim(),
      position:     formType === "collab" ? "" : values.position,
      video_link:   formType === "collab"
        ? ""
        : (values.videoLater ? "Will send later" : values.video.trim()),
      program:      programTitle,
      language:     (lang || "en").toUpperCase(),
      utm_source:   utm.utm_source   || "",
      utm_campaign: utm.utm_campaign || "",
      utm_medium:   utm.utm_medium   || "",
      utm_content:  utm.utm_content  || "",
      utm_term:     utm.utm_term     || "",
      landing_url:  (typeof window !== "undefined" && window.location) ? window.location.href : "",
      website:      "", // honeypot — always empty on real submits
    };

    const endpoint = "https://f1rststeps.com/amo.php";

    const controller = new AbortController();
    const timer = setTimeout(() => controller.abort(), 10000);

    try {
      const res = await fetch(endpoint, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(payload),
        signal: controller.signal,
      });
      clearTimeout(timer);
      if (res.status === 200) {
        // Meta Pixel — fire the Lead event once on successful submit.
        // The base pixel is already initialised in the site head, so we
        // only call the event here and guard for environments where the
        // pixel hasn't loaded (e.g. blocked by an ad-blocker).
        if (typeof fbq !== "undefined") {
          try { fbq("track", "Lead"); } catch (e) {}
        }
        if (formType === "collab") {
          // Collaboration leads get an inline confirmation rather than the
          // full thank-you page, matching the previous modal behaviour.
          setCollabSubmitted(true);
          return;
        }
        const ref = "FS-" + Math.random().toString(36).slice(2, 8).toUpperCase();
        navigate({ name: "thanks", id: program.id, ref });
        return;
      }
      setSubmitError(true);
    } catch (err) {
      clearTimeout(timer);
      setSubmitError(true);
    } finally {
      setSubmitting(false);
    }
  };

  // Inline thank-you when a collaboration enquiry submits successfully.
  // (For player applications we still navigate to the full /thanks page.)
  if (formType === "collab" && collabSubmitted && ct) {
    return (
      <main className="fade-in form-wrap">
        <div className="container">
          <div className="form-card collab-thanks" style={{ textAlign: "center" }}>
            <div className="mark"><Check size={36} /></div>
            <h2 className="h2" style={{ marginTop: 18 }}>{ct.thanksTitle}</h2>
            <p style={{ marginTop: 12 }}>{ct.thanksBody}</p>
            <button
              className="btn btn-primary btn-large"
              onClick={() => navigate({ name: "collaboration" })}
              style={{ marginTop: 28 }}
            >
              {ct.cancel}
            </button>
          </div>
        </div>
      </main>
    );
  }

  // Pick the right header copy + cancel destination based on form type.
  const isCollab = formType === "collab";
  const headTitle    = isCollab && ct ? ct.title : t.title;
  const headHeadline = isCollab && ct
    ? ct.title
    : (track ? track.title[lang] : (program ? program.title[lang] : ""));
  const headSub      = isCollab && ct
    ? ct.sub
    : (track ? (track.ageBand[lang] + " · " + (typeof track.club === "string" ? track.club : track.club[lang])) : t.sub);
  const cancelTarget = isCollab
    ? { name: "collaboration" }
    : (track ? { name: "program", id: program.id, track: track.id } : { name: "program", id: program.id });
  const cancelLabel  = isCollab && ct ? ct.cancel : t.cancel;
  const legalText    = isCollab && ct ? ct.legal : t.legal;
  const submitLabel  = isCollab && ct ? ct.submit : t.submit;
  const firstLabel   = isCollab && ct ? ct.first : t.first;
  const lastLabel    = isCollab && ct ? ct.last  : t.last;
  const phoneLabel   = isCollab && ct ? ct.phone : t.phone;
  const emailLabel   = isCollab && ct ? ct.email : t.email;

  return (
    <main className="fade-in form-wrap">
      <div className="container">
        <div className="form-card">
          <div className="form-head">
            <div>
              <div className="for">{isCollab ? (window.I18N[lang].collabPage && window.I18N[lang].collabPage.eyebrow) || headTitle : headTitle}</div>
              <h2 className="h3" style={{ marginTop: 4 }}>{headHeadline}</h2>
              <div style={{ fontSize: 14, color: "var(--muted)", marginTop: 10 }}>
                {headSub}
              </div>
            </div>
            <button className="btn btn-link" onClick={() => navigate(cancelTarget)}>
              <ArrowLeft size={12} /> {cancelLabel}
            </button>
          </div>

          <form onSubmit={submit} noValidate className={isCollab ? "collab-form" : undefined}>
            {/* Honeypot — hidden from real users. Bots that auto-fill every field will trip this. */}
            <div style={{ display: "none" }} aria-hidden="true">
              <label>
                Website
                <input
                  type="text"
                  name="website"
                  tabIndex={-1}
                  autoComplete="off"
                  value={values.website}
                  onChange={set("website")}
                />
              </label>
            </div>

            <div className="form-grid">
              <Field label={firstLabel} required error={errors.first}>
                <input type="text" value={values.first} onChange={set("first")} autoComplete="given-name" />
              </Field>
              <Field label={lastLabel} required error={errors.last}>
                <input type="text" value={values.last} onChange={set("last")} autoComplete="family-name" />
              </Field>
              <Field label={phoneLabel} required error={errors.phone}>
                <PhoneInput ref={phoneRef} lang={lang} />
              </Field>
              <Field label={emailLabel} required error={errors.email}>
                <input type="email" value={values.email} onChange={set("email")} placeholder="name@example.com" autoComplete="email" />
              </Field>
              {!isCollab && (
                <React.Fragment>
                  <Field label={t.age} required error={errors.age}>
                    <input type="number" min="4" max="25" value={values.age} onChange={set("age")} />
                  </Field>
                  <Field label={t.currentClub}>
                    <input type="text" value={values.club} onChange={set("club")} placeholder={lang === "ru" ? "Например: ФК Локомотив" : (lang === "es" ? "Ej. CD Tenerife" : "e.g. CD Tenerife")} />
                  </Field>
                  <Field label={t.position}>
                    <select value={values.position} onChange={set("position")}>
                      <option value="">—</option>
                      {POSITION_VALUES.map((val, i) => (
                        <option key={val} value={val}>{(t.positions && t.positions[i]) || val}</option>
                      ))}
                    </select>
                  </Field>
                  <Field label={t.videoLink} required error={errors.video || errors.videoFormat} hint={t.videoHint}>
                    <input
                      type="url"
                      value={values.video}
                      onChange={set("video")}
                      placeholder="https://veo.co/... | hudl.com/... | youtube.com/..."
                      disabled={values.videoLater}
                      aria-disabled={values.videoLater}
                    />
                    <label className="check-row">
                      <input
                        type="checkbox"
                        checked={values.videoLater}
                        onChange={(e) => {
                          const checked = e.target.checked;
                          setValues((v) => ({ ...v, videoLater: checked }));
                          // Clear any pending video errors as soon as the user opts to send later.
                          if (checked) {
                            setErrors((er) => {
                              const next = { ...er };
                              delete next.video;
                              delete next.videoFormat;
                              return next;
                            });
                          }
                        }}
                      />
                      <span>{t.videoLater}</span>
                    </label>
                  </Field>
                </React.Fragment>
              )}
            </div>

            <div className="form-actions">
              <div className="legal">{legalText}</div>
              <button
                type="submit"
                className="btn btn-primary btn-large"
                disabled={submitting}
                aria-busy={submitting}
              >
                {submitting ? (
                  <React.Fragment>
                    <span className="spinner" aria-hidden="true" />
                    {lang === "ru" ? "Отправляем…" : (lang === "es" ? "Enviando…" : "Sending…")}
                  </React.Fragment>
                ) : (
                  <React.Fragment>
                    {submitLabel} <Arrow size={14} />
                  </React.Fragment>
                )}
              </button>
            </div>

            {submitError && (
              <div className="form-error-banner" role="alert">
                <div className="form-error-banner__msg">
                  {lang === "ru"
                    ? "Не удалось отправить заявку. Напишите нам в WhatsApp"
                    : (lang === "es"
                        ? "No se pudo enviar la solicitud. Escríbenos por WhatsApp"
                        : "We couldn't submit your application. Message us on WhatsApp")}
                </div>
                <a
                  className="btn btn-primary"
                  href="https://wa.me/+34610827731"
                  target="_blank"
                  rel="noopener noreferrer"
                >
                  WhatsApp <Arrow size={12} />
                </a>
              </div>
            )}
          </form>
        </div>
      </div>
    </main>
  );
}

// ---------- THANK YOU ----------
function ThankYouPage({ lang, refCode, navigate }) {
  const t = window.I18N[lang].thanks;
  useEffect(() => { window.scrollTo(0, 0); }, []);
  return (
    <section className="thanks fade-in">
      <div className="thanks-inner">
        <div className="mark"><Check size={40} /></div>
        <h1 className="h1">{t.title}</h1>
        <p>{t.body}</p>
        <div className="cta-row">
          <button className="btn btn-primary btn-large" onClick={() => navigate({ name: "home" })}>
            {t.back}
          </button>
          <button className="btn btn-outline-light btn-large" onClick={() => {
            navigate({ name: "home" });
            setTimeout(() => {
              const el = document.getElementById("programs");
              if (el) window.scrollTo({ top: el.offsetTop - 60, behavior: "smooth" });
            }, 60);
          }}>
            {t.moreInfo}
          </button>
        </div>
        {refCode && <div className="ref">{t.ref}: {refCode}</div>}
      </div>
    </section>
  );
}

Object.assign(window, { HomePage, ProgramDetail, ApplyPage, ThankYouPage });
