"use client";

import { createContext, useContext, useEffect, useState } from "react";
import { usePathname } from "next/navigation";
import { AnimatePresence, MotionConfig, motion } from "framer-motion";
import Lenis from "lenis";
import Logo from "./Logo";
import { getBrandCopy } from "@/lib/brand";

declare global {
  interface Window {
    __lenis?: Lenis;
  }
}

const IntroContext = createContext(false);
/** true cuando la intro terminó y las animaciones de la portada pueden empezar */
export const useIntroDone = () => useContext(IntroContext);

const SEEN_KEY = "alterra-intro-seen";

/** The intro only plays on the home page; inner pages show their content (and main image) immediately. */
const isHomePath = (path: string) => path === "/" || path === "/es" || path === "/en";

export default function Experience({ children }: { children: React.ReactNode }) {
  const initialPath = usePathname();
  const [showIntro, setShowIntro] = useState(() => isHomePath(initialPath));
  const [done, setDone] = useState(() => !isHomePath(initialPath));

  // Intro: completa la primera vez por sesión, casi instantánea después.
  useEffect(() => {
    let seen = false;
    try {
      seen = sessionStorage.getItem(SEEN_KEY) === "1";
      sessionStorage.setItem(SEEN_KEY, "1");
    } catch {}
    const reduce = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
    const ms = seen || reduce ? 150 : 1400;
    const id = window.setTimeout(() => setShowIntro(false), ms);
    return () => window.clearTimeout(id);
  }, []);

  // Scroll suave (Lenis) + enlaces internos.
  useEffect(() => {
    if (window.matchMedia("(prefers-reduced-motion: reduce)").matches) return;
    const lenis = new Lenis({ duration: 1.25, easing: (t) => 1 - Math.pow(1 - t, 4) });
    window.__lenis = lenis;
    let raf = 0;
    const loop = (time: number) => {
      lenis.raf(time);
      raf = requestAnimationFrame(loop);
    };
    raf = requestAnimationFrame(loop);

    const onClick = (e: MouseEvent) => {
      const a = (e.target as HTMLElement).closest('a[href^="#"]');
      if (!a) return;
      const hash = a.getAttribute("href")!;
      const target = hash === "#" ? null : document.querySelector(hash);
      if (!target) return;
      e.preventDefault();
      lenis.scrollTo(target as HTMLElement, { offset: hash === "#inicio" ? 0 : -70 });
      history.replaceState(null, "", hash);
    };
    document.addEventListener("click", onClick);
    return () => {
      document.removeEventListener("click", onClick);
      cancelAnimationFrame(raf);
      lenis.destroy();
      delete window.__lenis;
    };
  }, []);

  // Al cambiar de página, empezar arriba (Lenis no lo hace solo).
  const pathname = usePathname();
  useEffect(() => {
    window.__lenis?.scrollTo(0, { immediate: true });
  }, [pathname]);

  useEffect(() => {
    if (showIntro) window.__lenis?.stop();
    else window.__lenis?.start();
  }, [showIntro]);

  return (
    <MotionConfig reducedMotion="user">
      <IntroContext.Provider value={done}>{children}</IntroContext.Provider>
      <AnimatePresence onExitComplete={() => setDone(true)}>
        {showIntro && (
          <motion.div
            key="intro"
            className="fixed inset-0 z-[100] flex items-center justify-center bg-ink text-cream"
            exit={{ clipPath: "inset(0 0 100% 0)" }}
            transition={{ duration: 1, ease: [0.76, 0, 0.24, 1] }}
          >
            <div className="flex flex-col items-center">
              <motion.div
                initial={{ opacity: 0, y: 14, letterSpacing: "0.1em" }}
                animate={{ opacity: 1, y: 0, letterSpacing: "0.28em" }}
                transition={{ duration: 1.2, ease: [0.22, 1, 0.36, 1] }}
              >
                <Logo variant="stacked" height={180} priority className="h-32 sm:h-44" />
              </motion.div>
              <motion.span
                className="mt-8 block h-px bg-gold"
                initial={{ width: 0 }}
                animate={{ width: 180 }}
                transition={{ duration: 1.4, delay: 0.3, ease: [0.22, 1, 0.36, 1] }}
              />
              <motion.p
                className="mt-6 px-6 text-center text-[0.62rem] tracking-[0.34em] text-cream/75 uppercase"
                initial={{ opacity: 0 }}
                animate={{ opacity: 1 }}
                transition={{ duration: 1, delay: 0.6 }}
              >
                {getBrandCopy(initialPath.startsWith("/es") ? "es" : "en").signature}
              </motion.p>
            </div>
          </motion.div>
        )}
      </AnimatePresence>
    </MotionConfig>
  );
}
