"use client";

import Image from "next/image";
import { useEffect, useRef } from "react";
import { ensureGsap, motionEnabled } from "@/lib/motion";
import { useClientFlag } from "@/lib/useClientFlag";
import { IMMERSION_IMAGES } from "@/content/site";
import type { Dictionary } from "@/lib/i18n";

/**
 * 03 — Destination Immersion.
 * Ocean → Islands → Mountains → Heritage → Architecture → Ecosystem.
 * Pinned, scroll-scrubbed sequence: each landscape rises through a mask while the
 * previous one recedes; the label word is swapped with a masked type transition.
 * Without motion (no JS / reduced motion) the scenes simply stack vertically.
 */
export default function Immersion({ t }: { t: Dictionary["immersion"] }) {
  const root = useRef<HTMLElement>(null);
  const pinned = useClientFlag(motionEnabled);

  useEffect(() => {
    const el = root.current;
    if (!pinned || !el) return;
    const { gsap } = ensureGsap();
    const ctx = gsap.context(() => {
      const scenes = gsap.utils.toArray<HTMLElement>(".im-scene");
      const labels = gsap.utils.toArray<HTMLElement>(".im-label");
      const places = gsap.utils.toArray<HTMLElement>(".im-place");
      const ticks = gsap.utils.toArray<HTMLElement>(".im-tick");
      const n = scenes.length;

      gsap.set(scenes.slice(1), { clipPath: "inset(100% 0% 0% 0%)" });
      gsap.set(labels.slice(1), { yPercent: 110 });
      gsap.set(places.slice(1), { opacity: 0, y: 12 });

      const tl = gsap.timeline({
        defaults: { ease: "none" },
        scrollTrigger: {
          trigger: el,
          start: "top top",
          end: () => `+=${window.innerHeight * (n - 0.4)}`,
          pin: ".im-stage",
          scrub: 0.8,
          anticipatePin: 1,
          invalidateOnRefresh: true,
        },
      });

      // Intro title drifts away as the journey begins.
      tl.to(".im-intro", { opacity: 0, yPercent: -30, duration: 0.5 }, 0);
      gsap.set(ticks[0], { scaleX: 1 });

      for (let i = 1; i < n; i++) {
        const at = i - 0.5;
        tl.to(scenes[i], { clipPath: "inset(0% 0% 0% 0%)", duration: 1, ease: "power2.inOut" }, at)
          .fromTo(scenes[i].querySelector(".im-img"), { scale: 1.25 }, { scale: 1.02, duration: 1.2 }, at)
          .to(scenes[i - 1].querySelector(".im-img"), { scale: 1.12, yPercent: -6, duration: 1 }, at)
          .to(scenes[i - 1].querySelector(".im-dim"), { opacity: 0.75, duration: 1 }, at)
          .to(labels[i - 1], { yPercent: -110, duration: 0.5, ease: "power2.in" }, at + 0.15)
          .to(labels[i], { yPercent: 0, duration: 0.6, ease: "power3.out" }, at + 0.45)
          .to(places[i - 1], { opacity: 0, y: -12, duration: 0.3 }, at + 0.15)
          .to(places[i], { opacity: 1, y: 0, duration: 0.4 }, at + 0.55)
          .to(ticks[i], { scaleX: 1, duration: 0.6 }, at + 0.3);
      }
      tl.to({}, { duration: 0.4 });
    }, el);
    return () => ctx.revert();
  }, [pinned]);

  return (
    <section
      ref={root}
      data-theme="dark"
      aria-labelledby="immersion-title"
      className="relative bg-navy-ink text-white"
    >
      <div className={pinned ? "im-stage relative h-[100svh] overflow-hidden" : "relative flex flex-col"}>
        {IMMERSION_IMAGES.map((src, i) => (
          <figure
            key={src}
            className={`im-scene ${pinned ? "absolute inset-0" : "relative h-[80svh] min-h-[480px]"} overflow-hidden`}
            style={{ zIndex: i + 1 }}
          >
            <div className="im-img absolute inset-0 will-change-transform">
              <Image
                src={src}
                alt={`${t.scenes[i].label} — ${t.scenes[i].place}`}
                fill
                sizes="100vw"
                quality={75}
                className="object-cover"
              />
            </div>
            <div className="im-dim absolute inset-0 bg-navy-ink opacity-0" aria-hidden="true" />
            <div className="absolute inset-0 bg-gradient-to-b from-navy-ink/50 via-transparent to-navy-ink/80" aria-hidden="true" />
            {!pinned && (
              <figcaption className="container-x absolute inset-x-0 bottom-10">
                <span className="display display-lg block">{t.scenes[i].label}</span>
                <span className="mt-2 block text-sm tracking-wide text-white/80">{t.scenes[i].place}</span>
              </figcaption>
            )}
          </figure>
        ))}

        {/* Overlay UI */}
        <div className={`${pinned ? "absolute" : "relative order-first"} inset-0 z-20 pointer-events-none`}>
          <div className={`im-intro container-x ${pinned ? "absolute inset-x-0 top-[calc(var(--header-h)+3rem)]" : "py-16"}`}>
            <p className="eyebrow text-gold-light">{t.eyebrow}</p>
            <h2 id="immersion-title" className="display display-md mt-5 max-w-[18ch]">
              {t.title}
            </h2>
          </div>

          {pinned && (
            <div className="container-x absolute inset-x-0 bottom-8 md:bottom-12">
              <div className="flex flex-col gap-6 md:flex-row md:items-end md:justify-between">
                <div aria-hidden="true">
                  <div
                    className="display relative h-[0.95em] text-[clamp(3.5rem,13vw,12rem)] leading-[0.95]"
                    style={{ clipPath: "inset(0 -100vw 0 0)" }}
                  >
                    {t.scenes.map((s) => (
                      <span key={s.label} className="im-label absolute left-0 top-0 block whitespace-nowrap">
                        {s.label}
                      </span>
                    ))}
                    <span className="invisible">{t.scenes[0].label}</span>
                  </div>
                  <div className="relative mt-3 h-10 max-w-[34ch] sm:max-w-none">
                    {t.scenes.map((s) => (
                      <span key={s.place} className="im-place absolute left-0 top-0 text-sm tracking-wide text-white/85">
                        {s.place}
                      </span>
                    ))}
                  </div>
                </div>
                <div className="flex flex-col items-start gap-4 md:items-end">
                  <div className="flex gap-2" aria-hidden="true">
                    {t.scenes.map((s) => (
                      <span key={s.label} className="relative h-px w-8 bg-white/25 md:w-12">
                        <span className="im-tick absolute inset-0 origin-left scale-x-0 bg-gold" />
                      </span>
                    ))}
                  </div>
                  <p className="max-w-[46ch] text-[0.7rem] leading-relaxed text-white/60 md:text-right">{t.note}</p>
                </div>
              </div>
            </div>
          )}
        </div>
        {!pinned && <p className="container-x py-8 text-xs text-white/60">{t.note}</p>}
      </div>
    </section>
  );
}
