"use client";

import Image from "next/image";
import { useEffect, useRef } from "react";
import { gsap } from "gsap";
import { SplitText } from "gsap/SplitText";

gsap.registerPlugin(SplitText);

interface HeroClientProps {
  item: {
    heroImage: string;
    title: string;
    description: string;
  };
}

export default function HeroClient({ item }: HeroClientProps) {
  const containerRef = useRef<HTMLDivElement>(null);
  const headingRef = useRef<HTMLHeadingElement>(null);
  const subHeadingRef = useRef<HTMLParagraphElement>(null);

  useEffect(() => {
    const ctx = gsap.context(() => {
      if (!headingRef.current) return;

      const headingSplit = new SplitText(headingRef.current, { type: "words" });
      gsap.fromTo(
        headingSplit.words,
        { yPercent: 120, opacity: 0 },
        {
          yPercent: 0,
          opacity: 1,
          duration: 1.2,
          ease: "expo.out",
          stagger: 0.09,
          delay: 0.3,
        }
      );

      if (subHeadingRef.current) {
        const subSplit = new SplitText(subHeadingRef.current, {
          type: "words",
        });
        gsap.fromTo(
          subSplit.words,
          { yPercent: 100, opacity: 0 },
          {
            yPercent: 0,
            opacity: 1,
            duration: 1,
            ease: "expo.out",
            stagger: 0.04,
            delay: 0.6,
          }
        );
      }
    }, containerRef);

    return () => ctx.revert();
  }, []);

  return (
    <section
      ref={containerRef}
      className="font-switzer tab:p-5 tab:h-[90vh] relative mx-auto w-full max-w-[1650px] overflow-hidden sm:h-[80vh] sm:p-2.5"
    >
      <div className="relative mx-auto flex h-full w-full items-center justify-center overflow-hidden rounded-2xl">
        <Image
          src={item.heroImage}
          alt={item.title}
          width={1200}
          height={600}
          className="absolute inset-0 h-full w-full rounded-2xl object-cover"
        />
        <div className="flex w-full max-w-[1420px] items-center px-5">
          <div className="tab:p-0 tab:mt-0 relative z-20 flex w-full max-w-[850px] flex-col gap-5 sm:mt-10 sm:px-0">
            <h1
              ref={headingRef}
              className="font-switzer sm:text-hero-mobile tab:text-h-1-96 tab:leading-h1 text-left font-semibold text-white sm:leading-[54px]"
            >
              {item.title}
            </h1>
            <p
              ref={subHeadingRef}
              className="font-mium-reg tab:text-b-1-20 sm:text-b-3-16 w-full text-left leading-normal text-white sm:tracking-[-0.6px]"
            >
              {item.description}
            </p>
          </div>
        </div>
        <Image
          src="/images/png/Blob 5.png"
          width={700}
          height={500}
          alt="overlay"
          className="tab:h-[450px] absolute bottom-0 left-0 w-full object-cover sm:h-[40vh]"
        />
      </div>
    </section>
  );
}
