const { useState, useEffect, useRef } = React;
const { PROJECTS, TESTIMONIALS, PROCESS, T, CONTACT } = window.FF_DATA;

// ─────────────────────── HELPERS ───────────────────────
const localized = (val, lang) => {
  if (val == null) return "";
  if (typeof val === "string") return val;
  if (Array.isArray(val)) return val;
  return val[lang] ?? val.de ?? val.en ?? "";
};

const arClass = (a) => ({
  "2.39:1": "ar-2-39",
  "16:9": "ar-16-9",
  "4:5": "ar-4-5",
  "1:1": "ar-1-1",
  "9:16": "ar-9-16",
}[a] || "ar-16-9");

// ─────────────────────── SCROLL REVEAL ───────────────────────
function useReveal() {
  const ref = useRef(null);
  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const io = new IntersectionObserver((entries) => {
      entries.forEach((e) => {
        if (e.isIntersecting) {
          e.target.classList.add("is-in");
          io.unobserve(e.target);
        }
      });
    }, { threshold: 0.12, rootMargin: "0px 0px -10% 0px" });
    io.observe(el);
    return () => io.disconnect();
  }, []);
  return ref;
}

function Reveal({ children, as: As = "div", delay = 0, ...rest }) {
  const ref = useReveal();
  return (
    <As ref={ref} className={`ff-reveal ${rest.className || ""}`} style={{ ...rest.style, transitionDelay: `${delay}ms` }}>
      {children}
    </As>
  );
}

// ─────────────────────── MEDIA SLOT ───────────────────────
function useVimeoHighestQuality(iframeRef, vimeoId) {
  useEffect(() => {
    if (!vimeoId || !iframeRef.current) return;

    let player;
    let cancelled = false;

    const applyHighestQuality = () => {
      if (cancelled || !player) return;
      player.getQualities().then(qualities => {
        if (cancelled) return;
        const best = qualities
          .filter(q => q.id !== 'auto')
          .sort((a, b) => (parseInt(b.id) || 0) - (parseInt(a.id) || 0))[0];
        if (best) player.setQuality(best.id).catch(() => {});
      }).catch(() => {});
    };

    const init = () => {
      if (cancelled || !window.Vimeo || !iframeRef.current) return;
      player = new window.Vimeo.Player(iframeRef.current);
      player.ready().then(applyHighestQuality).catch(() => {});
      player.on('playing', applyHighestQuality);
    };

    if (window.Vimeo) {
      init();
    } else {
      const s = document.querySelector('script[src*="player.vimeo.com"]');
      if (s) s.addEventListener('load', init, { once: true });
    }

    return () => {
      cancelled = true;
      if (player) player.off('playing');
    };
  }, [vimeoId]);
}

function MediaSlot({ aspect = "16:9", caption, slate, withPlay = true, tag, idx, vimeoId, imgSrc, imgAlt = "" }) {
  const iframeRef = useRef(null);
  const containerRef = useRef(null);
  const [iframeReady, setIframeReady] = useState(false);
  useVimeoHighestQuality(iframeRef, iframeReady ? vimeoId : null);

  useEffect(() => {
    if (!vimeoId || !containerRef.current) return;
    const io = new IntersectionObserver(
      (entries) => { if (entries[0].isIntersecting) { setIframeReady(true); io.disconnect(); } },
      { rootMargin: "400px" }
    );
    io.observe(containerRef.current);
    return () => io.disconnect();
  }, [vimeoId]);

  return (
    <div ref={containerRef} className={`ff-slot ${arClass(aspect)}`}>
      {imgSrc ? (
        <img src={imgSrc} alt={imgAlt} style={{ position: "absolute", top: 0, left: 0, width: "100%", height: "100%", objectFit: "cover", objectPosition: "center top" }} />
      ) : vimeoId ? (
        iframeReady && (
          <iframe
            ref={iframeRef}
            src={`https://player.vimeo.com/video/${vimeoId}?badge=0&autopause=0&autoplay=1&muted=1&loop=1&player_id=0&app_id=58479&playsinline=1`}
            allow="autoplay; fullscreen; picture-in-picture; playsinline"
            allowFullScreen
            style={{ position: "absolute", top: 0, left: 0, width: "100%", height: "100%", border: 0 }}
            title="Video"
          />
        )
      ) : (
        <>
          {tag && <div className="ff-slot-tag">{tag}</div>}
          {slate && (
            <div className="ff-slate">
              {slate.map((line, i) => <span key={i}>{line}</span>)}
            </div>
          )}
          {withPlay && (
            <div className="ff-slot-play" aria-hidden>
              <svg width="14" height="16" viewBox="0 0 14 16" fill="currentColor"><path d="M0 0 L14 8 L0 16 Z" /></svg>
            </div>
          )}
          {caption && <div className="ff-slot-caption">{caption}</div>}
        </>
      )}
    </div>
  );
}

// ─────────────────────── NAV ───────────────────────
function Nav({ t, lang, setLang }) {
  const [scrolled, setScrolled] = useState(false);
  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 24);
    onScroll();
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);

  const go = (id) => (e) => {
    e.preventDefault();
    const el = document.getElementById(id);
    if (el) window.scrollTo({ top: el.offsetTop - 16, behavior: "smooth" });
  };

  return (
    <nav className={`ff-nav ${scrolled ? "is-scrolled" : ""}`}>
      <a href="#top" onClick={go("top")} className="ff-logo">
        FILM<span className="amp">&amp;</span>FLIGHT
      </a>
      <div className="ff-nav-links">
        <a href="#work" onClick={go("work")}>{t.nav.work}</a>
        <a href="#process" onClick={go("process")}>{t.nav.services}</a>
        <a href="#about" onClick={go("about")}>{t.nav.about}</a>
        <a href="#contact" onClick={go("contact")}>{t.nav.contact}</a>
      </div>
      <div className="ff-nav-right">
        <button className="ff-pill" onClick={() => setLang(lang === "de" ? "en" : "de")} aria-label="Language">
          <span className={`seg ${lang === "de" ? "on" : ""}`}>DE</span>
          <span className={`seg ${lang === "en" ? "on" : ""}`}>EN</span>
        </button>
      </div>
    </nav>
  );
}

// ─────────────────────── HERO ───────────────────────
function Hero({ t, lang }) {
  return (
    <header className="ff-hero" id="top">
      <div className="ff-hero-inner">
        <Reveal className="ff-hero-eyebrow">
          <div className="ff-eyebrow">{t.hero.eyebrow}</div>
        </Reveal>
        <Reveal delay={120}>
          <h1 className="ff-hero-title">
            {t.hero.tagline.map((line, i) => {
              const isLast = i === t.hero.tagline.length - 1;
              return (
                <React.Fragment key={i}>
                  {isLast ? <span className="it">{line}</span> : line}
                  {!isLast && <br />}
                </React.Fragment>
              );
            })}
          </h1>
        </Reveal>
        <Reveal delay={220}>
          <div className="ff-hero-ctas">
            <a href="#work" onClick={(e) => { e.preventDefault(); document.getElementById("work")?.scrollIntoView({ behavior: "smooth", block: "start" }); }} className="ff-btn">
              {t.hero.cta_primary}
              <span className="arr">→</span>
            </a>
            <a href="#contact" onClick={(e) => { e.preventDefault(); document.getElementById("contact")?.scrollIntoView({ behavior: "smooth", block: "start" }); }} className="ff-btn ff-btn-ghost">
              {t.hero.cta_secondary}
            </a>
          </div>
        </Reveal>
      </div>
      <div className="ff-hero-foot" style={{ justifyContent: "flex-end" }}>
        <span className="scroll">↓ {t.hero.scroll}</span>
      </div>
    </header>
  );
}

// ─────────────────────── WORK SECTION ───────────────────────
function Work({ t, lang }) {
  const [openCases, setOpenCases] = useState(() => new Set());
  const toggleCase = (id) => {
    setOpenCases((prev) => {
      const next = new Set(prev);
      if (next.has(id)) next.delete(id);
      else next.add(id);
      return next;
    });
  };

  const projects = PROJECTS.filter((p) => !p.placeholder);
  const visible = projects.sort((a, b) => (b.order || 0) - (a.order || 0));

  return (
    <section className="ff-section" id="work">
      <div className="ff-container">
        <div className="ff-section-head">
          <div>
            <div className="ff-eyebrow">{t.work.eyebrow}</div>
            <h2>{t.work.title}</h2>
          </div>
        </div>
        <CinemaList
          items={visible}
          t={t}
          lang={lang}
          openCases={openCases}
          toggleCase={toggleCase}
        />
      </div>
    </section>
  );
}

// ─────────────────────── CINEMA LIST ───────────────────────
function CinemaList({ items, t, lang, openCases, toggleCase }) {
  return (
    <div className="ff-cinema">
      {items.map((p, i) => {
        const aspect = p.hero?.aspect || p.aspect;
        const isVertical = aspect === "9:16";
        const cls = ["ff-project", i % 2 === 1 ? "is-reverse" : "", isVertical ? "is-vertical" : ""].filter(Boolean).join(" ");
        const hasCase = p.stills?.length > 0;
        const isOpen = openCases?.has(p.id);
        const caseId = `case-${p.id.toLowerCase()}`;
        return (
          <div key={p.id} className="ff-cinema-block">
            <Reveal as="article" className={cls}>
              <div className="ff-project-media">
                <MediaSlot
                  aspect={p.hero?.aspect || p.aspect}
                  caption={`▶  ${p.hero?.caption || ""}`}
                  slate={[`TAKE ${String(i + 1).padStart(2, "0")}`, `${p.aspect}`]}
                  tag={p.placeholder ? (lang === "de" ? "Slot · Video folgt" : "Slot · footage TBD") : "Drone · Reel"}
                  vimeoId={p.hero?.vimeoId}
                />
              </div>
              <div className="ff-project-meta">
                <div className="ff-project-topic">{localized(p.brandSub || p.client, lang)}</div>
                <h3 className="ff-project-title">{localized(p.brand || p.client, lang)}</h3>
                <p className="ff-project-sub">{localized(p.subtitle, lang)}</p>
                <div className="ff-project-tags">
                  {(p.tags || []).map((tg) => <span key={tg} className="ff-tag">{tg}</span>)}
                </div>
                <div className="ff-meta-row" style={{ display: "flex", flexDirection: "column", gap: 6, marginBottom: 18 }}>
                  <span>{t.meta.category}, {localized(p.category, lang)}</span>
                  {p.location && <span>{t.meta.location}, {p.location}</span>}
                  <span>{t.meta.year}, {p.year}</span>
                </div>
                {hasCase && (
                  <button
                    type="button"
                    className={`ff-case-toggle ${isOpen ? "is-open" : ""}`}
                    onClick={() => toggleCase(p.id)}
                    aria-expanded={isOpen}
                    aria-controls={caseId}
                  >
                    <span className="lbl">{isOpen ? t.work.case_close : t.work.case_open}</span>
                  </button>
                )}
              </div>
            </Reveal>
            {hasCase && (
              <div className={`ff-case-wrap ${isOpen ? "is-open" : ""}`} id={caseId}>
                <CaseStudy project={p} t={t} lang={lang} />
              </div>
            )}
          </div>
        );
      })}
    </div>
  );
}

// ─────────────────────── GRID LIST ───────────────────────
function GridList({ items, t, lang }) {
  return (
    <div className="ff-grid">
      {items.map((p, i) => (
        <Reveal key={p.id} as="article" className="ff-grid-item" delay={(i % 4) * 80}>
          <MediaSlot
            aspect={p.aspect}
            caption={p.placeholder ? `// ${lang === "de" ? "Slot · Material wird ergänzt" : "Slot · footage to be added"}` : `▶  ${p.hero?.caption}`}
            slate={[p.id, `${p.aspect}`]}
            tag={p.placeholder ? (lang === "de" ? "Slot frei" : "Open slot") : null}
          />
          <div className="ff-grid-meta">
            <div>
              <h3>{localized(p.title, lang)}</h3>
              <p>{localized(p.category, lang)} · {p.year}</p>
            </div>
            <span className="ff-mono">{p.id}</span>
          </div>
        </Reveal>
      ))}
    </div>
  );
}

// ─────────────────────── CASE STUDY (detailed) ───────────────────────
function CaseStudy({ project: p, t, lang }) {
  if (!p) return null;
  return (
    <div className="ff-case is-inline">
      <div className="ff-case-inner">
        <div className="ff-case-head">
          <div className="ff-mono">{t.work.case_study}  ·  {p.year}</div>
          <p className="sub">{localized(p.caseSubtitle || p.subtitle, lang)}</p>
        </div>

        <div className="ff-case-stills">
          {p.stills?.map((s, i) => (
            <div key={i}>
              <MediaSlot
                aspect={s.aspect}
                caption={`◇  ${s.caption}`}
                slate={[`STILL ${String(i + 1).padStart(2, "0")}`, s.aspect]}
                withPlay={false}
                vimeoId={s.vimeoId}
              />
            </div>
          ))}
        </div>

        <div className="ff-case-info">
          <div>
            <div className="lbl">{localized(p.clientLabel, lang) || t.meta.client}</div>
            <div className="val">{localized(p.client, lang)}</div>
            <div className="val" style={{ color: "var(--fg-mute)", fontSize: 13, marginTop: 4 }}>{localized(p.region, lang)}</div>
          </div>
          <div>
            <div className="lbl">{t.meta.role}</div>
            <div className="val">{localized(p.role, lang)}</div>
          </div>
          <div>
            <div className="lbl">{t.meta.location}</div>
            <div className="val">{p.location}</div>
          </div>
          <div>
            <div className="lbl">{t.meta.deliverables}</div>
            <div className="val">
              {localized(p.deliverables, lang).map((d, i) => (
                <div key={i} style={{ marginBottom: 2 }}>· {d}</div>
              ))}
            </div>
          </div>
        </div>

        {p.credits?.length > 0 && (
          <div className="ff-case-credits">
            {p.credits.map((c, i) => (
              <div key={i} className="row">
                <span className="role">{localized(c.role, lang)}</span>
                <span>{c.name}</span>
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  );
}

// ─────────────────────── PROCESS ───────────────────────
function Process({ t, lang }) {
  return (
    <section className="ff-section" id="process" style={{ borderTop: "1px solid var(--line)" }}>
      <div className="ff-container">
        <div className="ff-section-head">
          <div>
            <div className="ff-eyebrow">{t.process.eyebrow}</div>
            <h2>{t.process.title}</h2>
          </div>
        </div>
        <div className="ff-services-list">
          {PROCESS.map((s) => (
            <Reveal key={s.code} as="div" className="ff-svc">
              <div className="code">{s.code}</div>
              <h3>
                {localized(s.title, lang)}
                {s.badge && <span className="ff-svc-badge">{localized(s.badge, lang)}</span>}
              </h3>
              <p>{localized(s.body, lang)}</p>
            </Reveal>
          ))}
        </div>
      </div>
    </section>
  );
}

// ─────────────────────── ABOUT ───────────────────────
function About({ t, lang }) {
  return (
    <section className="ff-section" id="about" style={{ borderTop: "1px solid var(--line)" }}>
      <div className="ff-container">
        <div className="ff-section-head" style={{ gridTemplateColumns: "1fr", marginBottom: 40 }}>
          <div className="ff-eyebrow">{t.about.eyebrow}</div>
        </div>
        <div className="ff-about">
          <Reveal>
            <MediaSlot
              aspect="4:5"
              imgSrc="/portrait.jpg"
              imgAlt="Manuel Perhofer · Founder, FILM & FLIGHT"
            />
          </Reveal>
          <div className="ff-about-body">
            <Reveal>
              <h3>{t.about.title}</h3>
              <div className="ff-mono">{t.about.sub}</div>
            </Reveal>
            {t.about.body.map((p, i) => (
              <Reveal key={i} as="p" delay={i * 80}>{p}</Reveal>
            ))}
          </div>
        </div>
      </div>
    </section>
  );
}

// ─────────────────────── TESTIMONIALS ───────────────────────
function Testimonials({ t, lang }) {
  return (
    <section className="ff-section" id="testimonials">
      <div className="ff-container">
        <div className="ff-section-head">
          <div>
            <div className="ff-eyebrow">{t.testimonials.eyebrow}</div>
            <h2>{t.testimonials.title}</h2>
          </div>
          <div className="ff-section-sub">
            {lang === "de"
              ? "Die ersten Zitate kommen mit den ersten bezahlten Projekten. Diese Slots werden eins nach dem anderen durch echte Stimmen ersetzt."
              : "Real quotes arrive with the first paid projects. These slots get replaced one by one as voices come in."}
          </div>
        </div>
        <div className="ff-quotes">
          {TESTIMONIALS.map((q, i) => (
            <Reveal key={i} as="figure" className="ff-quote" delay={i * 100}>
              <p className="q">{localized(q.quote, lang)}</p>
              <figcaption>
                <div style={{ fontFamily: "var(--ff-display)", fontSize: 18, fontStyle: "italic", marginBottom: 4 }}>{q.author}</div>
                <div className="author">{localized(q.role, lang)}</div>
              </figcaption>
            </Reveal>
          ))}
        </div>
      </div>
    </section>
  );
}

// ─────────────────────── CONTACT ───────────────────────
function Contact({ t, lang }) {
  return (
    <section className="ff-contact" id="contact">
      <div className="ff-contact-inner">
        <Reveal>
          <div className="ff-eyebrow">{t.contact.eyebrow}</div>
        </Reveal>
        <Reveal delay={80}>
          <h2>
            {t.contact.title[0]}<br />
            <span className="it">{t.contact.title[1]}</span>
          </h2>
        </Reveal>
        <Reveal delay={160}>
          <p className="sub">{t.contact.sub}</p>
        </Reveal>
        <Reveal delay={220}>
          <div className="ff-contact-grid">
            <a className="ff-contact-card" href={`https://wa.me/${CONTACT.whatsapp.replace(/\D/g, "")}`} target="_blank" rel="noreferrer">
              <span className="ff-mono">01 · {t.contact.whatsapp}</span>
              <span className="val">{CONTACT.whatsapp}</span>
              <span className="arr">→</span>
            </a>
            <a className="ff-contact-card" href={`mailto:${CONTACT.email}`}>
              <span className="ff-mono">02 · {t.contact.email}</span>
              <span className="val">{CONTACT.email}</span>
              <span className="arr">→</span>
            </a>
            <a className="ff-contact-card" href={`tel:${CONTACT.phone.replace(/\s/g, "")}`}>
              <span className="ff-mono">03 · {t.contact.phone}</span>
              <span className="val">{CONTACT.phone}</span>
              <span className="arr">→</span>
            </a>
          </div>
        </Reveal>
        <Reveal delay={300}>
          <div className="ff-meta-row" style={{ marginTop: 32, display: "flex", gap: 32, flexWrap: "wrap" }}>
            <span><span className="ff-dot" style={{ marginRight: 8, background: "oklch(0.78 0.13 145)" }}></span>{t.contact.availability}</span>
            <span>· {t.contact.based}</span>
            <span>· {CONTACT.instagram}</span>
          </div>
        </Reveal>
      </div>
    </section>
  );
}

// ─────────────────────── FOOTER ───────────────────────
function Footer({ t }) {
  return (
    <footer className="ff-foot">
      <div>
        <div className="lg">FILM<span style={{ fontFamily: "var(--ff-body)", fontStyle: "normal", fontWeight: 700, color: "var(--fg)", margin: "0 3px", fontSize: 18, letterSpacing: "0.04em" }}>&amp;</span>FLIGHT</div>
        <div style={{ marginTop: 8 }}>© 2026 · {t.foot.rights}</div>
      </div>
      <div className="links">
        <a href="/impressum.html">{t.foot.legal}</a>
        <a href="/datenschutz.html">{t.foot.privacy}</a>
        <a href={`https://instagram.com/${CONTACT.instagram.replace(/^@/, "")}`} target="_blank" rel="noreferrer">{CONTACT.instagram}</a>
      </div>
    </footer>
  );
}

// ─────────────────────── APP ───────────────────────
function App() {
  const [lang, setLang] = useState("de");
  const t = T[lang];

  useEffect(() => {
    document.documentElement.setAttribute("data-aesthetic", "reel");
    document.documentElement.setAttribute("lang", lang);
  }, [lang]);

  return (
    <>
      <Nav t={t} lang={lang} setLang={setLang} />
      <Hero t={t} lang={lang} />
      <Work t={t} lang={lang} />
      <Process t={t} lang={lang} />
      <About t={t} lang={lang} />
      {/* <Testimonials t={t} lang={lang} /> */}
      <Contact t={t} lang={lang} />
      <Footer t={t} />
    </>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<App />);
