"use client";

import { useEffect, useRef, useState } from "react";
import Link from "next/link";

export default function FloatingBookButton({
  cta,
}: {
  cta?: {
    label?: string | null;
    href?: string | null;
    ctaId?: string | null;
  } | null;
}) {
  const [visible, setVisible] = useState(true);
  const [hideNearFooter, setHideNearFooter] = useState(false);

  const btnRef = useRef<HTMLAnchorElement>(null);
  const lastScroll = useRef(0);

  useEffect(() => {
    const handleScroll = () => {
      const y = window.scrollY;
      const h = window.innerHeight;
      const full = document.documentElement.scrollHeight;

      const scrollingUp = y < lastScroll.current;

      // Ensure button is visible at the top (y < 100), or when scrolling up, or after scrolling down 200px
      setVisible(y < 100 || y > 200 || scrollingUp);
      setHideNearFooter(y + h >= full - 160);

      lastScroll.current = y;
    };

    handleScroll();

    window.addEventListener("scroll", handleScroll, { passive: true });

    return () => {
      window.removeEventListener("scroll", handleScroll);
    };
  }, []);

  useEffect(() => {
    const btn = btnRef.current;
    if (!btn) return;

    let raf = 0;

    const handleMove = (e: MouseEvent) => {
      cancelAnimationFrame(raf);

      raf = requestAnimationFrame(() => {
        const rect = btn.getBoundingClientRect();

        const x = (e.clientX - rect.left - rect.width / 2) * 0.12;
        const y = (e.clientY - rect.top - rect.height / 2) * 0.18;

        btn.style.transform = `translate(${x}px, ${y}px) scale(1.04)`;
      });
    };

    const reset = () => {
      btn.style.transform = "translate(0px, 0px) scale(1)";
    };

    btn.addEventListener("mousemove", handleMove);
    btn.addEventListener("mouseleave", reset);

    return () => {
      cancelAnimationFrame(raf);
      btn.removeEventListener("mousemove", handleMove);
      btn.removeEventListener("mouseleave", reset);
    };
  }, []);

  return (
    <>
      <style jsx global>{`
        @keyframes floatyPremium {
          0%,
          100% {
            transform: translateY(0px);
          }
          50% {
            transform: translateY(-8px);
          }
        }
      `}</style>

      <div className="pointer-events-none fixed bottom-24 right-0 z-50 hidden w-full justify-end sm:flex">
        <div
          className={`pointer-events-auto transition-all duration-700 ease-[cubic-bezier(0.22,1,0.36,1)] ${visible && !hideNearFooter
            ? "translate-x-0 opacity-100"
            : "translate-x-full opacity-0"
            } animate-[floatyPremium_6s_ease-in-out_infinite]`}
        >
          <Link
            ref={btnRef}
            href={cta?.href ?? "#"}
            id={cta?.ctaId ?? undefined}
            aria-label={cta?.label ?? "Book Now"}
            className={`
              group relative overflow-hidden
              flex items-center justify-center gap-4

              h-[54px] sm:h-[78px]
              w-[180px] sm:w-[320px]

              rounded-l-[140px]

              bg-[#85714D]
              text-white uppercase
              tracking-[0.08em]

              text-[13px] sm:text-[18px]
              font-medium

              shadow-[0_8px_30px_rgba(0,0,0,0.25)]
              hover:shadow-[0_18px_60px_rgba(0,0,0,0.42)]

              transition-all duration-500
              active:scale-[0.96]

              will-change-transform
            `}
          >

            <span
              className={`
                absolute inset-0
                rounded-l-[140px]
                bg-white/10
                opacity-0
                blur-xl
                transition-all duration-500
                group-hover:opacity-100
              `}
            />


            <span
              className={`
                absolute inset-y-0 -left-[120%] w-[60%]
                bg-gradient-to-r from-transparent via-white/30 to-transparent
                skew-x-[-25deg]
                group-hover:left-[140%]
                transition-all duration-1000
              `}
            />

            <span className="relative z-10">{cta?.label ?? "BOOK NOW"}</span>

            <span
              className={`
                relative z-10
                text-[22px] sm:text-[28px]
                transition-all duration-300
                group-hover:translate-x-2
              `}
            >
              →
            </span>
          </Link>
        </div>
      </div>
    </>
  );
}