"use client";

import { useEffect, useRef, useState } from "react";
import Image from "next/image";
import { AnimatePresence, motion, useScroll, useTransform } from "framer-motion";
import Link from "next/link";
import { ChevronDown } from "lucide-react";
import { localizedPath, type Locale } from "@alterra/shared";
import { images } from "@/lib/i18n";
import type { HomeCopy } from "@/lib/home";
import { useIntroDone } from "../Experience";
import BrandSignature from "../brand/BrandSignature";
import { getBrandCopy } from "@/lib/brand";

const EASE = [0.22, 1, 0.36, 1] as const;
const SLIDE_MS = 6500;

export default function HomeHero({ copy, lang }: { copy: HomeCopy["hero"]; lang: Locale }) {
  const ready = useIntroDone();
  const ref = useRef<HTMLElement>(null);
  const [slide, setSlide] = useState(0);
  const slides = images.heroSlides;

  const { scrollYProgress } = useScroll({ target: ref, offset: ["start start", "end start"] });
  const bgY = useTransform(scrollYProgress, [0, 1], ["0%", "22%"]);
  const contentY = useTransform(scrollYProgress, [0, 1], ["0%", "35%"]);
  const contentOpacity = useTransform(scrollYProgress, [0, 0.7], [1, 0]);

  useEffect(() => {
    const id = window.setInterval(() => setSlide((s) => (s + 1) % slides.length), SLIDE_MS);
    return () => window.clearInterval(id);
  }, [slides.length, slide]);

  const show = (delay: number) => ({
    initial: { opacity: 0, y: 24 },
    animate: ready ? { opacity: 1, y: 0 } : undefined,
    transition: { duration: 1.1, delay, ease: EASE },
  });

  const words = copy.title.split(" ");

  return (
    <section ref={ref} className="relative flex min-h-[100svh] items-end overflow-hidden bg-ink text-cream">
      <motion.div className="absolute inset-0" style={{ y: bgY }}>
        <AnimatePresence initial={false}>
          <motion.div
            key={slide}
            className="absolute inset-0"
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            transition={{ duration: 1.8, ease: "easeInOut" }}
          >
            <motion.div
              className="absolute inset-0"
              initial={{ scale: 1.15 }}
              animate={{ scale: 1.02 }}
              transition={{ duration: SLIDE_MS / 1000 + 2, ease: "linear" }}
            >
              <Image src={slides[slide]} alt="" fill priority={slide === 0} sizes="100vw" className="object-cover" />
            </motion.div>
          </motion.div>
        </AnimatePresence>
      </motion.div>
      <div className="absolute inset-0 bg-gradient-to-t from-ink via-ink/55 to-ink/30" />

      <motion.div
        style={{ y: contentY, opacity: contentOpacity }}
        className="relative mx-auto w-full max-w-7xl px-5 pb-28 pt-40 md:px-8 md:pb-32"
      >
        <motion.p {...show(0.1)} className="eyebrow mb-6 flex items-center gap-4 text-gold-light">
          <motion.span
            className="block h-px bg-gold-light"
            initial={{ width: 0 }}
            animate={ready ? { width: 48 } : undefined}
            transition={{ duration: 1.2, delay: 0.1, ease: EASE }}
          />
          {copy.eyebrow}
        </motion.p>

        <h1 className="max-w-5xl font-serif text-[2.6rem] leading-[1.08] font-normal sm:text-6xl lg:text-[5.4rem]">
          {words.map((w, i) => (
            <span key={i} className="inline-block overflow-hidden pb-[0.08em] align-bottom">
              <motion.span
                className="inline-block"
                initial={{ y: "110%" }}
                animate={ready ? { y: "0%" } : undefined}
                transition={{ duration: 1.1, delay: 0.25 + i * 0.07, ease: EASE }}
              >
                {w}
                {i < words.length - 1 && " "}
              </motion.span>
            </span>
          ))}
        </h1>

        <motion.p {...show(0.25 + words.length * 0.07)} className="mt-7 max-w-2xl text-base leading-relaxed text-cream/80 md:text-lg">
          {copy.subtitle}
        </motion.p>
        <motion.div {...show(0.45 + words.length * 0.07)} className="mt-10 flex flex-col gap-4 sm:flex-row">
          <Link
            href={localizedPath(lang, "/properties")}
            className="group relative overflow-hidden bg-gold px-8 py-4 text-center text-[0.8rem] tracking-[0.16em] uppercase text-ink"
          >
            <span className="absolute inset-0 -translate-x-full bg-cream transition-transform duration-500 ease-out group-hover:translate-x-0" />
            <span className="relative">{copy.primary}</span>
          </Link>
          <Link
            href={localizedPath(lang, "/contact")}
            className="border border-cream/40 px-8 py-4 text-center text-[0.8rem] tracking-[0.16em] uppercase transition duration-500 hover:border-cream hover:bg-cream hover:text-ink"
          >
            {copy.secondary}
          </Link>
        </motion.div>
        <motion.div {...show(0.6 + words.length * 0.07)} className="mt-12">
          <BrandSignature text={getBrandCopy(lang).signature} className="text-cream/80" />
        </motion.div>
      </motion.div>

      {/* Indicador de fotos */}
      <motion.div
        {...show(1.2)}
        className="absolute bottom-8 left-5 flex items-center gap-4 md:left-auto md:right-8"
        aria-hidden
      >
        <span className="font-serif text-sm text-cream/80">
          {String(slide + 1).padStart(2, "0")} <span className="text-cream/70">/ {String(slides.length).padStart(2, "0")}</span>
        </span>
        <div className="flex gap-2">
          {slides.map((_, i) => (
            <button
              key={i}
              tabIndex={-1}
              onClick={() => setSlide(i)}
              className="relative h-px w-8 overflow-hidden bg-cream/25 md:w-12"
            >
              {i === slide && (
                <motion.span
                  key={`p-${slide}`}
                  className="absolute inset-y-0 left-0 bg-gold-light"
                  initial={{ width: "0%" }}
                  animate={{ width: "100%" }}
                  transition={{ duration: SLIDE_MS / 1000, ease: "linear" }}
                />
              )}
            </button>
          ))}
        </div>
      </motion.div>

      <motion.a
        {...show(1.3)}
        href="#approach"
        className="absolute bottom-6 left-1/2 hidden -translate-x-1/2 flex-col items-center gap-1 text-cream/60 md:flex"
      >
        <span className="eyebrow text-[0.62rem]">{copy.scroll}</span>
        <ChevronDown size={18} className="animate-bounce" />
      </motion.a>
    </section>
  );
}
