"use client";

import { useEffect, useState } from "react";
import { ArrowUp } from "lucide-react";
import {
  rememberReturnPosition,
  takeReturnPosition,
} from "@/src/lib/utils/scrollToId";

/**
 * Global floating "back" / "back to top" button.
 *
 * - When a booking CTA scrolls the user DOWN to the form (in-page #anchor links
 *   like #footerForm / #program-Form / #registration-form), we remember where
 *   they were. Clicking the button then returns them to that spot.
 * - Otherwise it behaves as a normal "back to top".
 */
const SHOW_AFTER = 300;

export default function ScrollToTopButton() {
  const [visible, setVisible] = useState(false);

  useEffect(() => {
    const onScroll = () => setVisible(window.scrollY > SHOW_AFTER);
    onScroll(); // set initial state
    window.addEventListener("scroll", onScroll, { passive: true });

    // Remember the current position whenever the user clicks an in-page anchor
    // link (the booking CTAs), so we can take them back there instead of the top.
    const onAnchorClick = (e: MouseEvent) => {
      const anchor = (e.target as HTMLElement | null)?.closest(
        'a[href*="#"]'
      ) as HTMLAnchorElement | null;
      if (!anchor) return;
      const href = anchor.getAttribute("href") || "";
      // Only same-page hash links (skip external / other-page links).
      if (href.includes("#") && !/^https?:\/\//.test(href)) {
        rememberReturnPosition();
      }
    };
    document.addEventListener("click", onAnchorClick, true);

    return () => {
      window.removeEventListener("scroll", onScroll);
      document.removeEventListener("click", onAnchorClick, true);
    };
  }, []);

  const handleClick = () => {
    // Written either by the anchor listener above or by `scrollToId` (the
    // button CTAs), so both kinds of CTA behave identically.
    const back = takeReturnPosition();
    // If a CTA brought the user down, go back UP to where they were…
    if (back != null && back < window.scrollY - 50) {
      window.scrollTo({ top: back, behavior: "smooth" });
    } else {
      // …otherwise behave as a normal "back to top".
      window.scrollTo({ top: 0, behavior: "smooth" });
    }
  };

  return (
    <button
      type="button"
      onClick={handleClick}
      aria-label="Back"
      className={`
        fixed bottom-6 right-6 z-[1000]
        flex items-center justify-center
        w-12 h-12 rounded-full
        bg-[#0097DC] text-white
        shadow-[0px_8px_16px_rgba(0,0,0,0.2)]
        transition-all duration-300
        hover:bg-[#0084C1] active:bg-[#0084C1]
        ${
          visible
            ? "opacity-100 translate-y-0 pointer-events-auto"
            : "opacity-0 translate-y-4 pointer-events-none"
        }
      `}
    >
      <ArrowUp className="w-6 h-6" strokeWidth={2.5} />
    </button>
  );
}
