"use client";

import { useEffect, useRef } from "react";
import { ArrowRight, ArrowLeft } from "lucide-react";
import gsap from "gsap";
import { useLanguage } from "@/lib/i18n/context";

export default function Hero() {
  const { t, locale } = useLanguage();
  const isRTL = locale === "ar";
  const wrapperRef = useRef<HTMLDivElement>(null);
  const imgWrapRef = useRef<HTMLDivElement>(null);
  const textRef    = useRef<HTMLDivElement>(null);

  // Refs for per-element staggered entry
  const labelRef   = useRef<HTMLParagraphElement>(null);
  const line1Ref   = useRef<HTMLDivElement>(null);
  const line2Ref   = useRef<HTMLDivElement>(null);
  const subtextRef = useRef<HTMLParagraphElement>(null);
  const ctaRef     = useRef<HTMLDivElement>(null);
  const scrollRef  = useRef<HTMLDivElement>(null);

  // ── Staggered GSAP entry ─────────────────────────────────────────────────
  useEffect(() => {
    const tl = gsap.timeline({ delay: 0.15 });

    // Label — soft fade up
    tl.fromTo(labelRef.current,
      { opacity: 0, y: 14 },
      { opacity: 1, y: 0, duration: 0.7, ease: "power3.out" },
      0.1
    );

    // Headline line 1 — clip reveal (rises from behind overflow mask)
    tl.fromTo(line1Ref.current,
      { y: "106%" },
      { y: "0%", duration: 0.9, ease: "power4.out" },
      0.22
    );

    // Headline line 2 — clip reveal, staggered
    tl.fromTo(line2Ref.current,
      { y: "106%" },
      { y: "0%", duration: 0.9, ease: "power4.out" },
      0.36
    );

    // Subtext — fade up
    tl.fromTo(subtextRef.current,
      { opacity: 0, y: 16 },
      { opacity: 1, y: 0, duration: 0.75, ease: "power3.out" },
      0.55
    );

    // CTAs — fade up
    tl.fromTo(ctaRef.current,
      { opacity: 0, y: 12 },
      { opacity: 1, y: 0, duration: 0.65, ease: "power3.out" },
      0.68
    );

    // Scroll indicator — last, slow fade
    tl.fromTo(scrollRef.current,
      { opacity: 0 },
      { opacity: 1, duration: 0.6, ease: "power2.out" },
      1.0
    );

    return () => { tl.kill(); };
  }, []);

  // ── Scroll-driven zoom-out ────────────────────────────────────────────────
  useEffect(() => {
    const imgWrap = imgWrapRef.current;
    const textEl  = textRef.current;
    if (!imgWrap) return;

    const onScroll = () => {
      const maxScroll = window.innerHeight * 0.45;
      const ratio     = Math.max(0, Math.min(window.scrollY / maxScroll, 1));

      const side   = ratio * 52;
      const top    = ratio * 18;
      const radius = ratio * 18;

      imgWrap.style.left         = `${side}px`;
      imgWrap.style.right        = `${side}px`;
      imgWrap.style.top          = `${top}px`;
      imgWrap.style.borderRadius = `${radius}px`;

      if (textEl) textEl.style.opacity = String(Math.max(0, 1 - ratio * 2.5));
    };

    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);


  return (
    <div ref={wrapperRef} style={{ height: "130vh" }}>
      <section id="home" className="sticky top-0 h-screen overflow-hidden bg-brand-off-white">

        {/* Video + gradient — shrinks on scroll */}
        <div ref={imgWrapRef} className="absolute overflow-hidden" style={{ inset: 0 }}>
          <video
            autoPlay
            muted
            loop
            playsInline
            ref={el => { if (el) el.playbackRate = 0.8; }}
            style={{
              position: "absolute", inset: 0,
              width: "100%", height: "100%",
              objectFit: "cover", objectPosition: "center",
            }}
          >
            <source src="/video-cuts/Champ de Mil.mp4" type="video/mp4" />
          </video>
          <div className="absolute inset-0 bg-linear-to-t from-black/80 via-black/20 to-black/10" />
        </div>

        {/* Text block */}
        <div
          ref={textRef}
          className={`absolute bottom-1/5 lg:bottom-16 z-10 max-w-lg ${isRTL ? "right-10 lg:right-16" : "left-10 lg:left-16"}`}
        >
          {/* Label */}
          <p
            ref={labelRef}
            className="text-brand-yellow text-[10px] font-bold tracking-[0.35em] uppercase mb-5"
            style={{ opacity: 0 }}    // initial — GSAP animates in
          >
            {t.hero.label}
          </p>

          {/* Headline with per-line clip masks */}
          <h1
            className="font-bold leading-none"
            style={{
              fontFamily: "var(--font-space, sans-serif)",
              fontSize:   "clamp(3rem, 5.5vw, 5.5rem)",
            }}
          >
            {/* Line 1 */}
            <span className={`block overflow-hidden ${isRTL ? "pb-3" : ""}`}>
              <div
                ref={line1Ref}
                className="text-white"
                style={{
                  transform:  "translateY(106%)", // initial
                  textShadow: "0 2px 24px rgba(0,0,0,0.45)",
                }}
              >
                {t.hero.line1}
              </div>
            </span>

            {/* Line 2 */}
            <span className={`block overflow-hidden ${isRTL ? "pb-4" : "pb-1"}`}>
              <div
                ref={line2Ref}
                style={{
                  transform:  "translateY(106%)", // initial
                  color:      "var(--color-brand-yellow)",
                  textShadow: "0 2px 24px rgba(0,0,0,0.3)",
                }}
              >
                {t.hero.line2}
              </div>
            </span>
          </h1>

          {/* Subtext */}
          <p
            ref={subtextRef}
            className="text-white/60 text-sm leading-relaxed mt-4 max-w-sm"
            style={{ opacity: 0 }}
          >
            {t.hero.sub}
          </p>

          {/* CTAs */}
          <div
            ref={ctaRef}
            className="mt-7 flex items-center gap-4"
            style={{ opacity: 0 }}
          >
            <a
              href="/produits"
              className="group inline-flex items-center gap-2 bg-brand-yellow text-brand-dark font-bold px-6 py-3 rounded-full text-xs tracking-wide hover:scale-105 transition-transform duration-300"
            >
              {t.hero.cta}
              {isRTL
                ? <ArrowLeft  size={13} strokeWidth={2.5} className="transition-transform duration-300 group-hover:-translate-x-1" />
                : <ArrowRight size={13} strokeWidth={2.5} className="transition-transform duration-300 group-hover:translate-x-1" />}
            </a>
            <a
              href="/a-propos"
              className="text-white/70 text-xs font-semibold tracking-wide hover:text-white transition-colors duration-300 underline underline-offset-4"
            >
              {t.hero.story}
            </a>
          </div>
        </div>

        {/* Scroll indicator */}
        <div
          ref={scrollRef}
          className="lg:hidden absolute bottom-1 left-1/2 -translate-x-1/2 flex flex-col items-center gap-2 text-white/35 z-10"
          style={{ opacity: 0 }}
        >
          <span className="text-[8px] font-bold tracking-[0.38em] uppercase">{t.hero.scroll}</span>
          <div className="w-px h-12 relative overflow-hidden rounded-full bg-white/15">
            <div
              className="absolute left-0 w-full rounded-full bg-white/60"
              style={{ height: "38%", animation: "scrollIndicator 1.7s ease-in-out infinite" }}
            />
          </div>
        </div>

      </section>
    </div>
  );
}
