import { useGSAP } from "@gsap/react";
import gsap from "gsap";
import { useRef, useEffect } from "react";
import { useWidthTracker } from "@/hooks/useWidthTracker";

const SearchProject = () => {
  const searchPinCardRef = useRef<HTMLDivElement>(null);
  // Track width changes (always enabled)
  useWidthTracker({
    ref: searchPinCardRef as React.RefObject<HTMLElement>,
    onWidthChange: (width, percentage) => {
      console.log(`Width changed: ${width}px (${percentage.toFixed(2)}%)`);
    },
  });

  // Set initial width percentage when component mounts
  useEffect(() => {
    if (searchPinCardRef.current) {
      const element = searchPinCardRef.current;
      const currentWidth = element.offsetWidth;
      const parentWidth = element.parentElement?.offsetWidth || 0;
      const initialPercentage =
        parentWidth > 0 ? (currentWidth / parentWidth) * 100 : 0;

      console.log(`Initial width percentage: ${initialPercentage.toFixed(2)}%`);
    }
  }, []);

  useGSAP(() => {
    const clipPathReveaslTl = gsap.timeline({
      scrollTrigger: {
        trigger: ".search-pin-section",
        start: "top 25%",
        end: "bottom 75%",
        scrub: 1.5,
      },
    });

    clipPathReveaslTl.to(".search-pin-card", {
      clipPath: "polygon(0% 0%, 100% 0%, 100% 50%, 100% 100%, 0% 100%, 0% 50%)",
      width: "100%",
      ease: "power1.inOut",
      onUpdate: function () {
        // Use GSAP's progress to calculate percentage
        const progress = this.progress(); // 0 to 1
        const animationPercentage = progress * 100;

        console.log(
          `GSAP Animation Progress: ${animationPercentage.toFixed(2)}%`
        );

        // Also log the actual element dimensions for debugging
        if (searchPinCardRef.current) {
          const element = searchPinCardRef.current;
          const currentWidth = element.offsetWidth;
          const parentWidth = element.parentElement?.offsetWidth || 0;
          const actualWidthPercentage =
            parentWidth > 0 ? (currentWidth / parentWidth) * 100 : 0;

          console.log(
            `Actual element width: ${currentWidth}px (${actualWidthPercentage.toFixed(
              2
            )}%)`
          );
        }
      },
    });
  });

  return (
    <section className="min-h-[80dvh] bg-[#F3F3F3] flex items-center justify-center search-pin-section">
      <div
        ref={searchPinCardRef}
        className=" bg-white min-h-96 min-w-96 search-pin-card flex items-center justify-center"
        style={{
          clipPath:
            "polygon(0% 0%, 70% 0%, 100% 30%, 100% 100%, 30% 100%, 0% 70%)",
        }}
      >
        <h1 className="text-7xl font-bold">Search</h1>

        <div className="w-[1200px] h-20 bg-red-400"></div>
        {/* <div className="relative w-full h-full">
          <MobileFilter widthPercentage={widthPercentage} />
        </div> */}
      </div>
    </section>
  );
};

export default SearchProject;
