/* eslint-disable @next/next/no-img-element */
"use client";
import gsap from "gsap";
import { ScrollTrigger } from "gsap/ScrollTrigger";
import { useGSAP } from "@gsap/react";
import { useMediaQuery } from "react-responsive";
import { useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
import DownloadBrochureModal from "@/components/molecules/DownloadBrochureModal";

// Safe useLayoutEffect that falls back to useEffect on server
const useIsomorphicLayoutEffect =
  typeof window !== "undefined" ? useLayoutEffect : useEffect;

gsap.registerPlugin(ScrollTrigger);

const ANIMATION_CONFIG = {
  title: {
    base: { x: 110, y: 150 },
    medium: { x: 15, y: 150 },
    fhd: { x: 60, y: 150 },
    twoK: { x: 130, y: 230 },
  },
  paragraph: {
    base: { x: 275, y: 190 },
    medium: (w: number, x: number) => ({
      x,
      y: w <= 1280 ? 175 : 190,
    }),
    fhd: { x: 265, y: 240 },
    twoK: { x: 370, y: 350 },
  },
} as const;

const AnimatedHeroSection = () => {
  const [responsiveXP, setResponsiveXP] = useState(0);
  const [isReady, setIsReady] = useState(false);
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [size, setSize] = useState({
    width: 0,
    height: 0,
  });
  const containerRef = useRef<HTMLElement>(null);

  // Initialize size and mark component as ready after hydration
  useIsomorphicLayoutEffect(() => {
    // Set size immediately
    setSize({
      width: window.innerWidth,
      height: window.innerHeight,
    });
    // Mark as ready after a frame to ensure DOM is settled
    requestAnimationFrame(() => {
      setIsReady(true);
    });
  }, []);

  // Medium screen ( 1024 - 1224)
  const isMediumScreen = useMediaQuery({ minWidth: 1201, maxWidth: 1366 });
  const isFHD = useMediaQuery({ minWidth: 1367 });
  const isTwoK = useMediaQuery({ minWidth: 2000 });

  // Centralize tunable animation offsets so FHD/medium tweaks stay in one place
  const titleOffset = useMemo(() => {
    if (isTwoK) return ANIMATION_CONFIG.title.twoK;
    if (isMediumScreen) return ANIMATION_CONFIG.title.medium;
    if (isFHD) return ANIMATION_CONFIG.title.fhd;
    return ANIMATION_CONFIG.title.base;
  }, [isMediumScreen, isFHD, isTwoK]);

  const paragraphOffset = useMemo(() => {
    if (isMediumScreen)
      return ANIMATION_CONFIG.paragraph.medium(size.width, responsiveXP);
    if (isTwoK) return ANIMATION_CONFIG.paragraph.twoK;
    if (isFHD) return ANIMATION_CONFIG.paragraph.fhd;
    return ANIMATION_CONFIG.paragraph.base;
  }, [isMediumScreen, isFHD, isTwoK, size.width, responsiveXP]);

  useEffect(() => {
    function handleResize() {
      setSize({
        width: window.innerWidth,
        height: window.innerHeight,
      });
    }

    function generateXPercentage(deviceWidthInPx: number) {
      switch (true) {
        case deviceWidthInPx >= 1201 && deviceWidthInPx <= 1240:
          return 215;

        case deviceWidthInPx >= 1241 && deviceWidthInPx <= 1280:
          return 222;

        case deviceWidthInPx >= 1281 && deviceWidthInPx <= 1320:
          return 225;

        case deviceWidthInPx >= 1321 && deviceWidthInPx <= 1340:
          return 230;

        case deviceWidthInPx >= 1341 && deviceWidthInPx <= 1370:
          return 235;

        default:
          return 0;
      }
    }

    const xPercentile = generateXPercentage(size.width);
    setResponsiveXP(xPercentile);

    window.addEventListener("resize", handleResize);
    return () => window.removeEventListener("resize", handleResize);
  }, [size]);

  useGSAP(
    () => {
      // Wait until component is ready and size is known
      if (!isReady || size.width === 0) return;

      // For medium screens, wait until responsiveXP is calculated
      if (responsiveXP === 0 && size.width >= 1201 && size.width <= 1366)
        return;

      // Kill any existing ScrollTriggers for this element to prevent duplicates
      ScrollTrigger.getAll().forEach((st) => {
        if (st.vars.trigger === ".property-hero-image") {
          st.kill();
        }
      });

      const tl = gsap.timeline({
        scrollTrigger: {
          trigger: ".property-hero-image",
          start: "top top",
          end: "+=160%",
          scrub: true,
          pin: true,
          anticipatePin: 1,
          invalidateOnRefresh: true,
        },
      });
      tl.fromTo(
        ".property-hero-image img",
        {
          clipPath: "polygon(0% 0%, 100% 0%, 100% 100%, 0% 100%)",
          scale: 1.0,
          yPercent: 0,
        },
        {
          clipPath: `${
            isMediumScreen
              ? "polygon(28% 0%, 72% 0%, 72% 100%, 28% 100%)"
              : "polygon(32% 0%, 68% 0%, 68% 100%, 32% 100%)"
          }`,
          scale: 0.8,
          yPercent: 3,
          ease: "sine",
        }
      )
        .fromTo(
          ".project-title",
          {
            display: "block",
            opacity: 0,
            scale: 0.5,
            yPercent: 90,
            xPercent: `${isMediumScreen ? 0 : 40}`,
          },
          {
            opacity: 1,
            scale: 0.9,
            yPercent: titleOffset.y,
            // Shift slightly left on FHD to avoid overlap
            xPercent: `${titleOffset.x}`,
            duration: 0.2,
            ease: "sine",
          },
          "-=0.2"
        )
        .fromTo(
          ".paragraph-div",
          {
            display: "block",
            opacity: 0,
            scale: 0.5,
            yPercent: 200,
            xPercent: `${isMediumScreen ? 250 : 335}`,
          },
          {
            opacity: 1,
            scale: 0.9,
            // Lift copy slightly on narrower medium widths (~1280px)
            yPercent: paragraphOffset.y,
            xPercent: `${paragraphOffset.x}`,
            duration: 0.3,
            ease: "sine",
          },
          "-=0.2"
        )
        .to(".property-hero-image", {
          scale: 0.97,
          duration: 0.3,
          ease: "sine",
        })
        .to(".extra-space", {
          display: "block",
          duration: 0.1,
          ease: "sine",
        });

      // Refresh ScrollTrigger after setup
      ScrollTrigger.refresh();
    },
    {
      scope: containerRef,
      dependencies: [
        responsiveXP,
        isMediumScreen,
        isFHD,
        isTwoK,
        size.width,
        isReady,
      ],
    }
  );

  return (
    <section
      ref={containerRef}
      className="property-hero min-h-[120dvh] relative overflow-hidden"
    >
      <div className="relative ">
        <div className="property-hero-image overflow-hidden h-screen w-full relative">
          <div className="project-title absolute space-y-4 hidden">
            <h2 className="font-light text-4xl text-[#28241E] font-creato ">
              Lunaris By Navana
            </h2>
            <div className="flex items-center space-x-2">
              <span>
                <svg
                  width="14"
                  height="18"
                  viewBox="0 0 14 18"
                  fill="none"
                  xmlns="http://www.w3.org/2000/svg"
                >
                  <path
                    d="M7 17.4991L6.51443 17.0634C5.84502 16.4767 0 11.1926 0 7.32741C0 3.2806 3.13401 0 7 0C10.866 0 14 3.2806 14 7.32741C14 11.1926 8.15498 16.4767 7.48835 17.0663L7 17.4991ZM7 1.5844C3.97139 1.58799 1.51707 4.1571 1.51364 7.32737C1.51364 9.75557 5.10972 13.6346 7 15.4099C8.89032 13.6338 12.4864 9.75263 12.4864 7.32737C12.4829 4.1571 10.0286 1.58802 7 1.5844Z"
                    fill="#888888"
                  />
                  <path
                    d="M6.99935 10.2319C5.4669 10.2319 4.22461 8.93149 4.22461 7.32737C4.22461 5.72325 5.4669 4.42285 6.99935 4.42285C8.53179 4.42285 9.77409 5.72325 9.77409 7.32737C9.77409 8.93149 8.53183 10.2319 6.99935 10.2319ZM6.99935 5.87508C6.23313 5.87508 5.61198 6.52528 5.61198 7.32734C5.61198 8.1294 6.23313 8.7796 6.99935 8.7796C7.76557 8.7796 8.38672 8.1294 8.38672 7.32734C8.38672 6.52528 7.7656 5.87508 6.99935 5.87508Z"
                    fill="#888888"
                  />
                </svg>
              </span>

              <p className="font-creato text-[16px] 2xl:text-[18px] text-[#333333] leading-relaxed tracking-wide 2xl:tracking-wider text-left">
                Plot-008, Road-505G, Sector-16, Jolshiri
              </p>
            </div>
          </div>
          <div className="paragraph-div max-w-[400px] 2xl:max-w-[488px] absolute p-2 opacity-0">
            <p className="text-[16px] 2xl:text-[18px] text-[#333333] leading-relaxed tracking-wide 2xl:tracking-wider text-left">
              Nestled in the heart of Uttara, Sector 03, Lunaris by Navana
              embodies distinguished living at its finest. With timeless design,
              masterful craftsmanship, and a coveted address, it reimagines
              modern sophistication for those who live with an elevated sense of
              taste..
            </p>
            <div className="pt-6">
              <button
                onClick={() => setIsModalOpen(true)}
                className="w-full py-4 bg-[#333333] text-white hover:scale-105 transition-transform duration-700 ease-in-out cursor-pointer rounded-sm"
              >
                Download Brochure
              </button>
            </div>
          </div>
          <img
            src="/images/properties/background/background.png"
            alt="navana property image"
            className="w-full h-full object-cover object-center test-image"
          />
          <div className="extra-space h-[5dvh] w-full"></div>
        </div>
      </div>
      <DownloadBrochureModal
        isOpen={isModalOpen}
        onClose={() => setIsModalOpen(false)}
      />
    </section>
  );
};

export default AnimatedHeroSection;
