"use client";

import { gsap } from "gsap";
import { ScrollTrigger } from "gsap/all";
import { useEffect, useRef } from "react";
import { useRouter } from "next/navigation";

const BrandCommitment = () => {
  const router = useRouter();
  const sectionRef = useRef<HTMLElement>(null);
  const svgRef = useRef<SVGSVGElement>(null);
  const headingRef = useRef<HTMLHeadingElement>(null);
  const text1Ref = useRef<HTMLParagraphElement>(null);
  const text2Ref = useRef<HTMLParagraphElement>(null);
  const text3Ref = useRef<HTMLParagraphElement>(null);
  const paragraphRef = useRef<HTMLParagraphElement>(null);
  const buttonRef = useRef<HTMLButtonElement>(null);
  const arrowRef = useRef<HTMLImageElement>(null);
  const labelRef = useRef<HTMLSpanElement>(null);
  const underlineRef = useRef<HTMLSpanElement>(null);
  const hoverTlRef = useRef<gsap.core.Timeline | null>(null);
  const resetTimeoutRef = useRef<NodeJS.Timeout | null>(null);

  useEffect(() => {
    if (!sectionRef.current || !svgRef.current) return;

    // Helper functions for responsive animation values
    const getViewportWidth = () =>
      typeof window !== "undefined" ? window.innerWidth : 1920;

    // Convert dvw to pixels (for horizontal transforms)
    const dvwToPx = (dvw: number) => (dvw / 100) * getViewportWidth();

    // Convert rem to pixels (for font-related animations, assuming 16px base)
    const remToPx = (rem: number) => rem * 16;

    // Get responsive values based on breakpoints
    const getResponsiveValues = () => {
      const width = getViewportWidth();

      // Legacy HD (1024-1279px)
      if (width >= 1024 && width < 1280) {
        return {
          arrowXInitial: dvwToPx(-0.75), // -0.75dvw for lg
          arrowXMove: dvwToPx(0.5), // 0.5dvw for lg
          labelXMove: dvwToPx(0.125), // 0.125dvw for lg
          textYMove: -remToPx(0.0625), // -0.0625rem for lg
          scrollStart: "30% 70%", // Adjusted for smaller screens
        };
      }
      // FHD (1280-1535px)
      if (width >= 1280 && width < 1536) {
        return {
          arrowXInitial: dvwToPx(-0.625), // -0.625dvw for xl
          arrowXMove: dvwToPx(0.5), // 0.5dvw for xl
          labelXMove: dvwToPx(0.125), // 0.125dvw for xl
          textYMove: -remToPx(0.0625), // -0.0625rem for xl
          scrollStart: "30% 68%", // Original FHD value
        };
      }
      // 2K+ (1536px+)
      return {
        arrowXInitial: dvwToPx(-0.625), // -0.625dvw for 2xl
        arrowXMove: dvwToPx(0.5), // 0.5dvw for 2xl
        labelXMove: dvwToPx(0.125), // 0.125dvw for 2xl
        textYMove: -remToPx(0.0625), // -0.0625rem for 2xl
        scrollStart: "30% 68%", // Original value
      };
    };

    const responsiveValues = getResponsiveValues();

    // ------------SVG Animation prepartaion ------------ //

    const allPaths = Array.from(
      svgRef.current.querySelectorAll("path")
    ) as SVGPathElement[];

    if (allPaths.length === 0) return;

    // Assume first path is the main outline
    const [mainOutline, ...rest] = allPaths;

    // Sort each group bottom-to-top using their bounding box bottom (y + height)
    const sortBottomToTop = (arr: SVGPathElement[]) =>
      arr
        .map((el) => ({ el, bottom: el.getBBox().y + el.getBBox().height }))
        .sort((a, b) => b.bottom - a.bottom)
        .map((i) => i.el);

    // Initial states: set up stroke drawing
    const withLengths = allPaths.map((p) => {
      const svgPath = p as SVGPathElement;
      const len = svgPath.getTotalLength ? svgPath.getTotalLength() : 0;
      svgPath.style.strokeDasharray = String(len);
      svgPath.style.strokeDashoffset = String(len);
      return { el: p, len };
    });

    // -------------- svg animation timeline ----------- //

    const tl = gsap.timeline({ paused: true });

    // Draw outer outline first
    tl.to(mainOutline, {
      strokeDashoffset: 0,
      duration: 1.8,
      ease: "power1.out",
    });

    // Draw remaining paths bottom-to-top
    const restBottomToTopAll = sortBottomToTop(rest);

    if (restBottomToTopAll.length) {
      tl.to(
        restBottomToTopAll,
        {
          strokeDashoffset: 0,
          duration: 1.5,
          stagger: { amount: 2.5, from: "start" },
          ease: "power1.out",
        },
        "-=0.1"
      );

      tl.fromTo(
        ".brick",
        { opacity: 0 },
        { opacity: 1, duration: 1.5, ease: "none" },
        "-=2.0"
      );
    }

    const st = ScrollTrigger.create({
      trigger: sectionRef.current,
      start: responsiveValues.scrollStart,
      end: "95% bottom",
      onEnter: () => {
        tl.restart();
      },
    });

    // ---------------------------
    // Text animations (scroll-reveal style for h2 > p)
    // ---------------------------
    // Prepare each line with an overflow wrapper and inner translateY(100%)
    function prepareRevealLine(el: HTMLElement | null) {
      if (!el) return null;
      const raw = el.textContent || "";
      el.innerHTML = `<span style=\"display:block; overflow:hidden;\"><span class=\"reveal-line\" style=\"display:block; transform: translateY(100%);\">${raw}</span></span>`;
      gsap.set(el, { opacity: 1 });
      return el.querySelector(".reveal-line") as HTMLElement | null;
    }

    const line1 = prepareRevealLine(text1Ref.current);
    const line2 = prepareRevealLine(text2Ref.current);
    const line3 = prepareRevealLine(text3Ref.current);

    if (paragraphRef.current) {
      const text = paragraphRef.current.textContent || "";
      const words = text.split(" ");
      paragraphRef.current.innerHTML = words
        .map((word) => `<span style="opacity: 0;">${word}</span>`)
        .join(" ");
    }

    if (buttonRef.current) {
      gsap.set(buttonRef.current, { scale: 0.9, opacity: 0 });
    }

    // Arrow/underline initial state
    if (arrowRef.current) {
      gsap.set(arrowRef.current, {
        x: responsiveValues.arrowXInitial,
        opacity: 0,
      });
    }
    if (underlineRef.current) {
      gsap.set(underlineRef.current, {
        scaleX: 0,
        opacity: 0,
        transformOrigin: "left center",
      });
    }

    const textTl = gsap.timeline({ paused: true });
    if (line1) {
      textTl.to(line1, {
        y: responsiveValues.textYMove,
        duration: 0.6,
        ease: "sine.inOut",
      });
    }
    if (line2) {
      textTl.to(
        line2,
        { y: responsiveValues.textYMove, duration: 0.6, ease: "sine.inOut" },
        "-=0.1"
      );
    }
    if (line3) {
      textTl.to(
        line3,
        { y: responsiveValues.textYMove, duration: 0.6, ease: "sine.inOut" },
        "-=0.1"
      );
    }

    if (paragraphRef.current) {
      const wordSpans = paragraphRef.current.querySelectorAll("span");
      textTl.to(wordSpans, {
        opacity: 1,
        duration: 0.4,
        stagger: 0.05,
        ease: "power2.out",
      });
    }

    textTl.to(
      buttonRef.current,
      {
        scale: 1,
        opacity: 1,
        duration: 1.08,
        ease: "power2.out",
      },
      "+=0.2"
    );

    // Animate underline when button appears
    textTl.to(
      underlineRef.current,
      { opacity: 1, scaleX: 1, duration: 0.5, ease: "power2.out" },
      "-=0.5"
    );

    // Hover micro-interactions for button arrow
    const onBtnEnter = () => {
      if (hoverTlRef.current) hoverTlRef.current.kill();
      const currentValues = getResponsiveValues();
      const tlh = gsap.timeline();
      tlh
        .to(
          arrowRef.current,
          { opacity: 1, x: 0, duration: 0.36, ease: "power2.out" },
          0
        )
        .to(arrowRef.current, {
          x: currentValues.arrowXMove,
          duration: 0.4,
          ease: "sine.out",
        })
        .to(arrowRef.current, { x: 0, duration: 0.4, ease: "sine.inOut" })
        .to(
          labelRef.current,
          { x: currentValues.labelXMove, duration: 0.36, ease: "sine.out" },
          0
        );
      hoverTlRef.current = tlh;
    };
    const onBtnLeave = () => {
      if (hoverTlRef.current) hoverTlRef.current.kill();
      const currentValues = getResponsiveValues();
      gsap.to(arrowRef.current, {
        x: currentValues.arrowXInitial,
        opacity: 0,
        duration: 0.36,
        ease: "power2.out",
      });
      // Keep underline visible - don't hide it
      gsap.to(labelRef.current, { x: 0, duration: 0.36, ease: "sine.out" });
    };

    if (buttonRef.current) {
      buttonRef.current.addEventListener("mouseenter", onBtnEnter);
      buttonRef.current.addEventListener("mouseleave", onBtnLeave);
    }

    const textSt = ScrollTrigger.create({
      trigger: sectionRef.current,
      start: "top 50%",
      end: "bottom 20%",
      onEnter: () => {
        textTl.restart();
      },
    });

    const resetTimeout = resetTimeoutRef.current;

    return () => {
      st.kill();
      textSt.kill();

      // Clean up timeout
      if (resetTimeout) clearTimeout(resetTimeout);

      if (buttonRef.current) {
        buttonRef.current.removeEventListener("mouseenter", onBtnEnter);
        buttonRef.current.removeEventListener("mouseleave", onBtnLeave);
      }
    };
  }, []);

  return (
    <section
      ref={sectionRef}
      id="brand-commitment"
      className="bg-white lg:min-h-dvh container mx-auto mt-20"
    >
      <div className="grid md:grid-cols-6 lg:grid-cols-5 lg:gap-8 xl:gap-10 2xl:gap-10 items-center lg:py-12 xl:py-20 2xl:py-36">
        {/* left side column*/}
        <div className="col-span-1 md:col-span-3 lg:col-span-2 xl:col-span-2 lg:mr-auto xl:mr-auto 2xl:ml-8 2xl:mb-8 mb-10 order-2 md:order-1 lg:px-4 xl:px-6 2xl:px-0 2xl:-translate-x-[25%] mx-auto md:mx-0">
          <svg
            ref={svgRef}
            viewBox="0 0 386 853"
            fill="none"
            xmlns="http://www.w3.org/2000/svg"
            className="min-w-80 md:min-w-full h-[450px] md:h-[500px] lg:w-[38dvw] lg:h-[85dvh] xl:w-[40dvw] xl:h-[91dvh] 2xl:w-[36dvw] 2xl:h-[80dvh] lg:pb-4 lg:px-4 xl:pb-6 xl:px-6"
          >
            <path
              d="M79.1528 126.621L149.76 1.23315L385.13 155.524V852.132H120.818H0.887695L1.21837 818.991L88.0462 820.676L88.4813 798.982L40.4466 797.089L39.6635 706.074L42.2044 705.727L41.9956 703.191L79.5357 694.228L79.031 548.831L57.9723 542.491L57.5546 540.511L54.857 539.66L55.1877 376.216L58.0071 374.879L57.9375 373.819L79.3617 363.936L79.1528 126.621Z"
              stroke="black"
              strokeMiterlimit="10"
            />

            <path
              d="M355.247 351.83L150.282 256.838L79.3442 343.614"
              stroke="black"
              strokeMiterlimit="10"
            />
            <path
              d="M355.248 310.04L149.43 209.437L79.3096 304.742"
              stroke="black"
              strokeMiterlimit="10"
            />
            <path
              d="M355.248 269.969L149.865 162.037L79.2747 263.195"
              stroke="black"
              strokeMiterlimit="10"
            />
            <path
              d="M355.247 229.325L150.282 115.053L79.2224 222.742"
              stroke="black"
              strokeMiterlimit="10"
            />
            <path
              d="M355.247 190.401L150.282 66.8018L79.4834 183.193"
              stroke="black"
              strokeMiterlimit="10"
            />

            <path
              d="M355.248 393.637L178.738 320.93L150.961 310.04L117.146 348.339L58.6338 375.608"
              stroke="black"
              strokeMiterlimit="10"
            />
            <path
              d="M55.3792 415.245L178.79 363.832L355.247 430.495"
              stroke="black"
              strokeMiterlimit="10"
            />
            <path
              d="M355.247 470.496L178.79 410.173L55.3792 456.653"
              stroke="black"
              strokeMiterlimit="10"
            />
            <path
              d="M55.4836 498.321L179.329 457.156L355.248 510.271"
              stroke="black"
              strokeMiterlimit="10"
            />
            <path
              d="M355.248 551.332L150.491 497.783L109.557 528.057L57.9724 542.491"
              stroke="black"
              strokeMiterlimit="10"
            />
            <path
              d="M79.7793 549.022L110.01 528.387"
              stroke="black"
              strokeMiterlimit="10"
            />
            <path
              d="M355.248 590.604L150.3 543.829L79.4487 587.113"
              stroke="black"
              strokeMiterlimit="10"
            />
            <path
              d="M79.3096 627.704L150.248 591.264L355.248 630.518"
              stroke="black"
              strokeMiterlimit="10"
            />
            <path
              d="M355.247 670.415L149.76 638.977L79.7793 668.001"
              stroke="black"
              strokeMiterlimit="10"
            />
            <path
              d="M354.812 709.687L125.447 682.73L79.5356 694.228"
              stroke="black"
              strokeMiterlimit="10"
            />
            {/* --- bottom brick starts---- */}
            <path
              d="M123.672 790.818V687.819L84.7917 696.208V794.049L153.502 796.463V792.503L125.83 791.513L123.568 791.548L123.672 790.818Z"
              stroke="black"
              strokeMiterlimit="10"
              className="brick"
            />
            <path
              d="M123.672 790.818V687.819L84.7917 696.208V794.049L153.502 796.463V792.503L125.83 791.513L123.568 791.548L123.672 790.818Z"
              fill="#E2E2E2"
              className="brick"
            />
            {/* --- bottom brick ends ---- */}
            <path
              d="M356.692 799.034L125.83 791.513L125.447 682.73L356.361 710.139L356.692 799.034Z"
              stroke="black"
              strokeMiterlimit="10"
            />
            <path
              d="M132.008 791.721V683.511"
              stroke="black"
              strokeMiterlimit="10"
            />
            <path
              d="M139.022 684.328V684.345V791.721"
              stroke="black"
              strokeMiterlimit="10"
            />
            <path
              d="M146.018 685.162V685.179V792.138"
              stroke="black"
              strokeMiterlimit="10"
            />
            <path
              d="M153.502 686.03V686.065V792.277"
              stroke="black"
              strokeMiterlimit="10"
            />
            <path
              d="M161.003 686.916V686.951V792.607"
              stroke="black"
              strokeMiterlimit="10"
            />
            <path
              d="M168.487 687.802V687.854V792.885"
              stroke="black"
              strokeMiterlimit="10"
            />
            <path
              d="M175.988 688.67V688.74V793.146V793.198"
              stroke="black"
              strokeMiterlimit="10"
            />
            <path
              d="M183.471 689.556V689.626V793.337"
              stroke="black"
              strokeMiterlimit="10"
            />
            <path
              d="M190.973 690.442V690.511V793.632V793.667"
              stroke="black"
              strokeMiterlimit="10"
            />
            <path
              d="M198.456 691.31V691.397V793.858"
              stroke="black"
              strokeMiterlimit="10"
            />
            <path
              d="M205.957 692.196V692.3V794.118"
              stroke="black"
              strokeMiterlimit="10"
            />
            <path
              d="M213.441 693.082V693.186V794.292"
              stroke="black"
              strokeMiterlimit="10"
            />
            <path
              d="M220.942 693.95V694.072V794.518"
              stroke="black"
              strokeMiterlimit="10"
            />
            <path
              d="M228.426 694.836V694.958V794.848V795.004"
              stroke="black"
              strokeMiterlimit="10"
            />
            <path
              d="M235.927 695.722V695.844V795.004"
              stroke="black"
              strokeMiterlimit="10"
            />
            <path
              d="M243.41 696.591V696.747V795.265"
              stroke="black"
              strokeMiterlimit="10"
            />
            <path
              d="M250.911 697.476V697.633V795.595V795.734"
              stroke="black"
              strokeMiterlimit="10"
            />
            <path
              d="M258.395 698.362V698.519V795.734"
              stroke="black"
              strokeMiterlimit="10"
            />
            <path
              d="M265.896 699.231V699.404V796.064"
              stroke="black"
              strokeMiterlimit="10"
            />
            <path
              d="M273.38 700.116V700.29V796.324V796.515"
              stroke="black"
              strokeMiterlimit="10"
            />
            <path
              d="M280.881 701.002V701.193V796.515"
              stroke="black"
              strokeMiterlimit="10"
            />
            <path
              d="M288.347 701.871V702.079V796.811V796.828"
              stroke="black"
              strokeMiterlimit="10"
            />
            <path
              d="M295.865 702.757V702.965V797.054V797.123"
              stroke="black"
              strokeMiterlimit="10"
            />
            <path
              d="M303.332 703.642V703.851V797.297V797.401"
              stroke="black"
              strokeMiterlimit="10"
            />
            <path
              d="M310.85 704.528V704.737V797.401"
              stroke="black"
              strokeMiterlimit="10"
            />
            <path
              d="M318.351 705.397V705.623V797.783V797.818"
              stroke="black"
              strokeMiterlimit="10"
            />
            <path
              d="M325.835 706.283V706.526V798.027V798.061"
              stroke="black"
              strokeMiterlimit="10"
            />
            <path
              d="M333.301 707.168V707.412V798.061"
              stroke="black"
              strokeMiterlimit="10"
            />
            <path
              d="M340.82 708.037V708.297V798.061"
              stroke="black"
              strokeMiterlimit="10"
            />
            <path
              d="M348.321 708.923V709.183V798.756V799.034"
              stroke="black"
              strokeMiterlimit="10"
            />
            <path
              d="M84.7916 739.162L40.0115 745.936"
              stroke="black"
              strokeMiterlimit="10"
            />

            <path
              d="M355.178 135.914L356.744 852.131"
              stroke="black"
              strokeMiterlimit="10"
            />
          </svg>
        </div>

        {/* right side column */}
        <div className="col-span-1 md:col-span-3 lg:col-span-2 xl:col-span-2 lg:space-y-16 xl:space-y-24 2xl:space-y-28 order-1 md:order-2 mb-10 md:mb-0 lg:px-4 xl:px-6 2xl:px-0 mx-auto">
          <div
            ref={headingRef}
            className="text-2xl md:text-3xl lg:text-[3rem] xl:text-[3.75rem] 2xl:text-[6.25rem] lg:leading-normal xl:leading-normal 2xl:leading-snug font-times-sans commitment-title lg:mt-4 xl:mt-0 2xl:mt-10"
          >
            <p
              ref={text1Ref}
              className="text-center md:text-right font-times-sans"
            >
              Broadening Life
            </p>
            <p
              ref={text2Ref}
              className="text-center md:text-left whitespace-nowrap font-times-sans"
            >
              Horizons with Integrity
            </p>
            <p
              ref={text3Ref}
              className="text-center md:text-left font-times-sans"
            >
              & Innovations
            </p>
          </div>
          <div className="hidden lg:block lg:w-2/3 xl:w-2/3 2xl:w-2/3 2xl:ml-auto lg:space-y-6 xl:space-y-8">
            <p
              ref={paragraphRef}
              className="font-creato font-normal text-base 2xl:text-lg text-[#333333] leading-relaxed lg:pb-3 xl:pb-4"
            >
              Navana Real Estate combines architectural innovation with a
              commitment to enhancing quality of life. The tagline “BROADEN LIFE
              BOUNDARIES” reflects their dedication to redefining lifestyles and
              expanding possibilities.
            </p>
            <button
              ref={buttonRef}
              onClick={() => router.push("/story")}
              className="flex items-center lg:gap-1.5 xl:gap-2 2xl:gap-2 lg:-ml-3 xl:-ml-4 2xl:-ml-4 text-[#333333] lg:px-3 lg:py-1.5 xl:px-4 xl:py-2 2xl:px-4 2xl:py-2 rounded overflow-hidden cursor-pointer"
            >
              <span ref={labelRef} className="relative inline-block">
                <span>Learn More</span>
                <span
                  ref={underlineRef}
                  className="absolute left-0 -bottom-0.5 h-px w-full bg-[#333333]"
                />
              </span>
              {/* eslint-disable-next-line @next/next/no-img-element */}
              <img
                ref={arrowRef}
                src="/icons/arrow-narrow-right.svg"
                alt="arrow"
                className="w-5 h-5"
              />
            </button>
          </div>
        </div>
      </div>
    </section>
  );
};

export default BrandCommitment;
