"use client";

import { useRef, useEffect } from "react";
import gsap from "gsap";
import { ScrollTrigger } from "gsap/all";
import BrandCommitmentSVG from "./BrandCommitmentSVG";

export default function BrandCommitmentMobile() {
  const headingRef = useRef<HTMLDivElement>(null);
  const outerPathRef = useRef<SVGPathElement>(null);
  const svgRef = useRef<SVGSVGElement>(null);

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

    // Register ScrollTrigger plugin
    gsap.registerPlugin(ScrollTrigger);

    // ------------SVG Animation preparation ------------ //

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

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

    // Filter out the duplicate outer path with opacity-15 class
    // The first path (with ref) is the main outline, skip the duplicate
    const visiblePaths = allPaths.filter(
      (path) => !path.classList.contains("opacity-15")
    );

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

    // 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 for all visible paths
    visiblePaths.forEach((p) => {
      const svgPath = p as SVGPathElement;
      const len = svgPath.getTotalLength ? svgPath.getTotalLength() : 0;
      svgPath.style.strokeDasharray = String(len);
      svgPath.style.strokeDashoffset = String(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: headingRef.current || svgRef.current,
      start: "top 90%",
      end: "bottom 20%",
      onEnter: () => {
        tl.restart();
      },
    });

    // Animate heading lines first
    if (headingRef.current) {
      const lines = headingRef.current.querySelectorAll("p");
      gsap.set(lines, { opacity: 0, y: 30 });
      const textTl = gsap.timeline({
        scrollTrigger: {
          trigger: headingRef.current,
          start: "top 90%",
          end: "bottom 20%",
        },
      });
      textTl.to(lines, { opacity: 1, y: 0, duration: 1, stagger: 0.15 });
    }

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

  return (
    <section className="px-4 md:px-8 lg:px-16 w-full flex flex-col items-center justify-center py-20">
      <div className="space-y-10">
        <div className="mt-6 text-center">
          <div
            ref={headingRef}
            className="text-xl md:text-2xl text-[clamp(32px,10.7vw,48px)] md:text-[40px] lg:text-[64px] lg:leading-normal 2xl:text-[100px] 2xl:leading-snug font-times-sans commitment-title 2xl:mt-10"
          >
            <p className="text-right">Committed to</p>
            <p>Your Dreams Driven</p>
            <p className="text-left">by Integrity</p>
          </div>
        </div>

        <div className="w-full min-w-80 md:min-w-full h-[450px] md:h-[500px] lg:h-[700px] 2xl:h-[800px]">
          <BrandCommitmentSVG ref={outerPathRef} svgRef={svgRef} />
        </div>
        
        <div className="flex flex-col gap-4">
            <p
              className="font-normal text-[10px] 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
              className="flex items-center text-[#28241E] gap-2"
            >
              <span  className="relative inline-block">
                <span className="text-[12px] font-creato font-normal text-[#28241E]">Learn More</span>
                <span
                
                  className="absolute left-0 -bottom-0.5 h-px w-full bg-[#28241E]"
                />
              </span>
              {/* eslint-disable-next-line @next/next/no-img-element */}
              <img
                src="/icons/arrow-narrow-right.svg"
                alt="arrow"
                className="w-4 h-4"
              />
            </button>
          </div>


      </div>
    </section>
  );
}
