"use client";

import { useEffect, useRef, useState } from "react";
import { gsap } from "gsap";
import { useGSAP } from "@gsap/react";
import { ArrowRight } from "@/components/ui/icons";
import AnimatedButton from "@/components/ui/AnimatedButton";

/**
 * Cinematic GSAP hero.
 *  - Slide changes wipe in from the right (clip-path) while the old image
 *    gently scales — film-style cut.
 *  - Headline words reveal through overflow masks, per slide.
 *  - Subtle mouse parallax on the background.
 *  - Vertical slide menu (right), ghost index numeral + progress bar (left).
 *  - Auto-advances; any interaction restarts the timer.
 *
 * Swap slide images in /public/images (HeroBanner*.jpg).
 */
const SLIDES = [
  {
    id: "web",
    image: "/images/HeroBanner1.jpg",
    tag: "Web Platforms",
    title: "Software that ships and scales.",
    desc: "Production-grade web platforms engineered for speed, stability and growth.",
  },
  {
    id: "mobile",
    image: "/images/HeroBanner2.jpg",
    tag: "Mobile Apps",
    title: "Apps people love to open.",
    desc: "Native and cross-platform experiences crafted down to the last interaction.",
  },
  {
    id: "ai",
    image: "/images/HeroBanner3.jpg",
    tag: "Artificial Intelligence",
    title: "Intelligence, built into product.",
    desc: "Generative AI, ML and automation woven into the heart of your software.",
  },
];

const HOLD = 6; // seconds per slide

export default function HeroShowcase() {
  const root = useRef(null);
  const [active, setActive] = useState(0);
  const len = SLIDES.length;
  const slide = SLIDES[active];

  const activeRef = useRef(0);
  const transitioning = useRef(false);
  const imageRefs = useRef([]);
  const progressTween = useRef(null);
  const goRef = useRef(() => {});

  /** Transition to slide idx: wipe the new image in, swap text mid-wipe. */
  const go = (idx) => {
    if (idx === activeRef.current || transitioning.current) return;
    transitioning.current = true;
    progressTween.current?.kill();

    const incoming = imageRefs.current[idx];
    const outgoing = imageRefs.current[activeRef.current];
    activeRef.current = idx;

    const tl = gsap.timeline({
      onComplete: () => {
        transitioning.current = false;
      },
    });

    tl.to(".hx-swap", { y: -30, opacity: 0, duration: 0.4, ease: "power2.in" }, 0)
      .set(incoming, { zIndex: 2, opacity: 1, clipPath: "inset(0 0 0 100%)", scale: 1.12 }, 0)
      .to(incoming, { clipPath: "inset(0 0 0 0%)", duration: 1.1, ease: "power3.inOut" }, 0.1)
      .to(incoming, { scale: 1, duration: 1.8, ease: "power2.out" }, 0.1)
      .to(outgoing, { scale: 1.07, duration: 1.1, ease: "power3.inOut" }, 0.1)
      .call(() => setActive(idx), null, 0.62)
      .set(outgoing, { opacity: 0, zIndex: 1, scale: 1 });
  };
  goRef.current = go;

  /* Intro — chrome + first image (runs once). */
  useGSAP(
    () => {
      const tl = gsap.timeline({ defaults: { ease: "power3.out" } });
      tl.from(imageRefs.current[0], { scale: 1.18, duration: 1.6, ease: "power2.out" }, 0)
        .from(".hx-eyebrow", { y: 18, opacity: 0, duration: 0.6 }, 0.3)
        .from(".hx-cta", { y: 22, opacity: 0, stagger: 0.1, duration: 0.6 }, 0.7)
        .from(".hx-menu-item", { x: 30, opacity: 0, stagger: 0.08, duration: 0.5 }, 0.8)
        .from(".hx-bottom", { y: 16, opacity: 0, duration: 0.6 }, 0.9);
    },
    { scope: root }
  );

  /* Per-slide text reveal + progress (runs on mount and every change). */
  useGSAP(
    () => {
      gsap.fromTo(
        ".hx-word-inner",
        { yPercent: 120 },
        { yPercent: 0, duration: 0.85, stagger: 0.07, ease: "power3.out" }
      );
      gsap.fromTo(
        ".hx-fade",
        { y: 22, opacity: 0 },
        { y: 0, opacity: 1, duration: 0.6, stagger: 0.1, ease: "power2.out", delay: 0.15 }
      );

      progressTween.current?.kill();
      progressTween.current = gsap.fromTo(
        ".hx-progress",
        { scaleX: 0 },
        {
          scaleX: 1,
          duration: HOLD,
          ease: "none",
          onComplete: () => goRef.current((activeRef.current + 1) % len),
        }
      );
    },
    { scope: root, dependencies: [active] }
  );

  /* Mouse parallax on the background. */
  useGSAP(
    () => {
      const el = root.current;
      const xTo = gsap.quickTo(".hx-bg", "x", { duration: 0.9, ease: "power3" });
      const yTo = gsap.quickTo(".hx-bg", "y", { duration: 0.9, ease: "power3" });
      const move = (e) => {
        const r = el.getBoundingClientRect();
        xTo(((e.clientX - r.left) / r.width - 0.5) * -22);
        yTo(((e.clientY - r.top) / r.height - 0.5) * -14);
      };
      el.addEventListener("mousemove", move);
      return () => el.removeEventListener("mousemove", move);
    },
    { scope: root }
  );

  useEffect(() => () => progressTween.current?.kill(), []);

  return (
    <section ref={root} className="relative h-[calc(100svh-5rem)] overflow-hidden">
      {/* Background stack (slightly oversized for parallax) */}
      <div className="hx-bg absolute -inset-6 -z-20">
        {SLIDES.map((s, i) => (
          <div
            key={s.id}
            ref={(el) => (imageRefs.current[i] = el)}
            className="absolute inset-0 will-change-transform"
            style={{
              backgroundImage: `url(${s.image})`,
              backgroundSize: "cover",
              backgroundPosition: "center",
              opacity: i === 0 ? 1 : 0,
              zIndex: i === 0 ? 2 : 1,
            }}
          />
        ))}
      </div>

      {/* Legibility overlays */}
      <div className="absolute inset-0 -z-10 bg-gradient-to-r from-background via-background/55 to-background/15" />
      <div className="absolute inset-0 -z-10 bg-gradient-to-t from-background via-transparent to-background/45" />

      {/* Content */}
      <div className="container relative flex h-full flex-col justify-center">
        <span className="hx-eyebrow inline-flex w-fit items-center gap-2 rounded-full border border-border bg-surface/50 px-4 py-1.5 text-xs font-medium text-muted-foreground backdrop-blur">
          <span className="relative flex h-2 w-2">
            <span className="absolute inline-flex h-full w-full animate-ping rounded-full bg-accent opacity-75" />
            <span className="relative inline-flex h-2 w-2 rounded-full bg-accent" />
          </span>
          A technology studio for ambitious teams
        </span>

        {/* Swappable per-slide block */}
        <div className="hx-swap mt-7 max-w-3xl">
          <span className="hx-fade block text-sm font-semibold uppercase tracking-[0.2em] text-primary">
            {slide.tag}
          </span>
          <h1 className="mt-4 font-heading text-4xl font-bold leading-[1.06] tracking-tight text-foreground drop-shadow-[0_2px_30px_rgba(0,0,0,0.6)] sm:text-6xl md:text-7xl">
            {slide.title.split(" ").map((w, i) => (
              <span key={`${slide.id}-${i}`} className="inline-block overflow-hidden pb-[0.12em] align-bottom">
                <span className="hx-word-inner inline-block">{w}</span>
                {i < slide.title.split(" ").length - 1 && <span>&nbsp;</span>}
              </span>
            ))}
          </h1>
          <p className="hx-fade mt-5 max-w-xl text-base leading-relaxed text-muted-foreground sm:text-lg">
            {slide.desc}
          </p>
        </div>

        <div className="mt-9 flex flex-wrap items-center gap-4">
          <AnimatedButton href="/contact" className="hx-cta">
            Start a project
          </AnimatedButton>
          <a
            href="/portfolio"
            className="hx-cta group inline-flex items-center gap-2 rounded-full border border-border bg-surface/50 px-6 py-3 text-sm font-semibold text-foreground backdrop-blur transition-colors hover:border-primary/50 hover:bg-surface"
          >
            See our work
            <ArrowRight className="h-4 w-4 text-primary transition-transform group-hover:translate-x-0.5" />
          </a>
        </div>
      </div>

      {/* Right — vertical slide menu */}
      <div className="absolute right-6 top-1/2 z-20 hidden -translate-y-1/2 flex-col gap-6 md:flex lg:right-12">
        {SLIDES.map((s, i) => (
          <button
            key={s.id}
            onClick={() => go(i)}
            className={
              "hx-menu-item group flex items-center justify-end gap-3 text-right transition-colors " +
              (i === active ? "text-foreground" : "text-muted-foreground/60 hover:text-muted-foreground")
            }
          >
            <span className="text-xs font-semibold tracking-wider">
              <span className={i === active ? "text-primary" : ""}>0{i + 1}</span>
              <span className="ml-2 hidden text-sm font-medium lg:inline">{s.tag}</span>
            </span>
            <span
              className={
                "h-px transition-all duration-500 " +
                (i === active ? "w-12 bg-primary" : "w-6 bg-muted-foreground/40 group-hover:w-9")
              }
            />
          </button>
        ))}
      </div>

      {/* Bottom-left — ghost numeral + progress */}
      <div className="hx-bottom absolute bottom-7 left-4 z-20 flex items-end gap-5 sm:left-10">
        <span className="font-heading text-7xl font-bold leading-none text-foreground/10 sm:text-8xl">
          0{active + 1}
        </span>
        <div className="mb-3">
          <div className="h-px w-36 overflow-hidden bg-foreground/15 sm:w-48">
            <div className="hx-progress h-full w-full origin-left bg-primary" />
          </div>
          <span className="mt-2 block text-xs tracking-widest text-muted-foreground">
            0{active + 1} / 0{len}
          </span>
        </div>
      </div>
    </section>
  );
}
