"use client";

import { useRouter } from "next/navigation";

const NAVBAR_HEIGHT = 80;
const SCROLL_PADDING = 20;

/**
 * Smart scroll function that waits for element to be properly positioned.
 * Can be used standalone without the hook.
 */
export function smartScrollToSection(sectionId: string) {
  const element = document.getElementById(sectionId);

  if (!element) {
    console.warn(`Section with id "${sectionId}" not found`);
    return;
  }

  const isElementReady = () => {
    const rect = element.getBoundingClientRect();
    return rect.height > 0 && element.offsetHeight > 0 && (rect.top !== 0 || rect.bottom !== 0);
  };

  const performScroll = () => {
    try {
      const rect = element.getBoundingClientRect();
      const scrollTop = window.pageYOffset || document.documentElement.scrollTop;
      const targetPosition = rect.top + scrollTop - (NAVBAR_HEIGHT + SCROLL_PADDING);
      const finalPosition = Math.max(0, targetPosition);

      window.scrollTo({ top: finalPosition, behavior: "smooth" });
    } catch {
      element.scrollIntoView({ behavior: "smooth", block: "start" });
    }
  };

  if (isElementReady()) {
    performScroll();
    return;
  }

  let attempts = 0;
  const maxAttempts = 30;

  const waitForElement = () => {
    attempts++;
    if (isElementReady()) {
      performScroll();
      return;
    }
    if (attempts >= maxAttempts) {
      performScroll();
      return;
    }
    setTimeout(waitForElement, 100);
  };

  waitForElement();
}

/**
 * Handles scroll on page load from sessionStorage or URL hash.
 * Call this in useEffect on the homepage.
 */
export function handleInitialScroll() {
  if (typeof window === "undefined") return;

  // Check for section stored in sessionStorage (from cross-page navigation)
  const storedSection = sessionStorage.getItem("scrollToSection");
  if (storedSection) {
    sessionStorage.removeItem("scrollToSection");
    setTimeout(() => smartScrollToSection(storedSection), 500);
    return;
  }

  // Check for hash in URL (direct links)
  const hash = window.location.hash;
  if (hash) {
    const sectionId = hash.substring(1);
    setTimeout(() => smartScrollToSection(sectionId), 200);
  }
}

export const useSmartNavigation = () => {
  const router = useRouter();

  const navigateToSection = (url: string, isScrollLink: boolean = false) => {
    if (!isScrollLink) {
      router.push(url);
      return;
    }

    const sectionId = url.startsWith("#") ? url.substring(1) : url;
    const isOnHomepage = window.location.pathname === "/";

    if (isOnHomepage) {
      smartScrollToSection(sectionId);
    } else {
      sessionStorage.setItem("scrollToSection", sectionId);
      router.push("/");
    }
  };

  return { navigateToSection, smartScrollToSection };
};
