"use client";

import { useEffect, useState, useRef } from "react";
import { useLenis } from "@studio-freight/react-lenis";

/**
 * Custom hook to detect if the background behind the navbar is light or dark.
 * Returns true if the background is light (navbar should have dark background for visibility).
 */
export function useNavbarBackground() {
  const [isLightBackground, setIsLightBackground] = useState(false);
  const lenis = useLenis();
  const rafRef = useRef<number | null>(null);
  const lastCheckRef = useRef<number>(0);

  // Calculate luminance from RGB values (0-1 range)
  const getLuminance = (r: number, g: number, b: number): number => {
    const [rs, gs, bs] = [r, g, b].map((val) => {
      const v = val / 255;
      return v <= 0.03928 ? v / 12.92 : Math.pow((v + 0.055) / 1.055, 2.4);
    });
    return 0.2126 * rs + 0.7152 * gs + 0.0722 * bs;
  };

  // Parse RGB color string to RGB values
  const parseRGB = (rgb: string): [number, number, number] | null => {
    // Handle rgb(r, g, b) format
    const rgbMatch = rgb.match(/rgb\((\d+),\s*(\d+),\s*(\d+)\)/);
    if (rgbMatch) {
      return [
        parseInt(rgbMatch[1], 10),
        parseInt(rgbMatch[2], 10),
        parseInt(rgbMatch[3], 10),
      ];
    }

    // Handle rgba(r, g, b, a) format
    const rgbaMatch = rgb.match(/rgba\((\d+),\s*(\d+),\s*(\d+),\s*[\d.]+\)/);
    if (rgbaMatch) {
      return [
        parseInt(rgbaMatch[1], 10),
        parseInt(rgbaMatch[2], 10),
        parseInt(rgbaMatch[3], 10),
      ];
    }

    return null;
  };

  // Get background color from computed styles, checking parent elements if needed
  const getBackgroundColor = (element: Element): string | null => {
    let current: Element | null = element;
    let depth = 0;
    const maxDepth = 5; // Limit traversal depth

    while (current && depth < maxDepth) {
      const computed = window.getComputedStyle(current);
      const bgColor = computed.backgroundColor;
      const bgImage = computed.backgroundImage;

      // Calculate alpha
      const alpha = bgColor.includes("rgba")
        ? parseFloat(bgColor.match(/rgba\([^)]+,\s*([\d.]+)\)/)?.[1] || "1")
        : 1;

      // Check if background color is not transparent
      const rgb = parseRGB(bgColor);
      if (rgb) {
        // If it's not fully transparent or black, return it
        if (alpha > 0.1 && (rgb[0] > 10 || rgb[1] > 10 || rgb[2] > 10)) {
          return bgColor;
        }
      }

      // If background image exists, still return the background color
      // as it might be a fallback color
      if (bgImage && bgImage !== "none" && bgImage !== "initial") {
        if (rgb && alpha > 0.1) {
          return bgColor;
        }
      }

      // Move to parent element
      current = current.parentElement;
      depth++;
    }

    return null;
  };

  // Check if background is light
  const checkBackground = () => {
    if (typeof window === "undefined") return;

    // Sample points at the navbar position (middle of navbar)
    const navbarHeight = 80; // Approximate navbar height
    const sampleY = navbarHeight / 2;
    const viewportWidth = window.innerWidth;
    const samplePoints = [
      viewportWidth * 0.2, // Left
      viewportWidth * 0.4, // Left-center
      viewportWidth * 0.5, // Center
      viewportWidth * 0.6, // Right-center
      viewportWidth * 0.8, // Right
    ];

    let lightCount = 0;
    let totalSamples = 0;

    for (const x of samplePoints) {
      try {
        const elements = document.elementsFromPoint(x, sampleY);
        
        // Find the first non-navbar element (skip navbar itself and its children)
        let targetElement: Element | null = null;
        for (const el of elements) {
          const tagName = el.tagName.toLowerCase();
          const id = el.id || "";
          const className = typeof el.className === "string" ? el.className : "";
          
          // Skip navbar elements and headroom
          if (
            tagName === "nav" ||
            id.includes("navbar") ||
            className.includes("navbar") ||
            className.includes("custom-headroom") ||
            className.includes("custom-headroom-container") ||
            className.includes("custom-headroom-root")
          ) {
            continue;
          }
          
          // Skip if it's a child of navbar
          const isNavbarChild = el.closest("nav") !== null;
          if (isNavbarChild) continue;
          
          targetElement = el;
          break;
        }

        if (!targetElement) continue;

        // Get background color (will check parent elements if needed)
        const bgColor = getBackgroundColor(targetElement);
        if (!bgColor) continue;

        // Parse and calculate luminance
        const rgb = parseRGB(bgColor);
        if (!rgb) continue;

        const luminance = getLuminance(rgb[0], rgb[1], rgb[2]);
        
        // Lower threshold to be more sensitive to light backgrounds
        // If luminance > 0.4, it's a light background
        if (luminance > 0.4) {
          lightCount++;
        }
        totalSamples++;
      } catch (error) {
        // Silently handle errors (e.g., cross-origin issues)
        console.debug("Background detection error:", error);
      }
    }

    // If any sample indicates light background, show navbar background
    // Also default to true if we can't detect (safer option)
    const isLight = totalSamples > 0 
      ? lightCount > 0 // Changed: if any sample is light, show background
      : true; // Default to showing background if detection fails

    setIsLightBackground(isLight);
  };

  // Throttled check function
  const throttledCheck = () => {
    const now = Date.now();
    // Only check every 100ms to avoid performance issues
    if (now - lastCheckRef.current < 100) {
      return;
    }
    lastCheckRef.current = now;

    if (rafRef.current) {
      cancelAnimationFrame(rafRef.current);
    }

    rafRef.current = requestAnimationFrame(() => {
      checkBackground();
      rafRef.current = null;
    });
  };

  useEffect(() => {
    // Initial check with multiple attempts to ensure DOM is ready
    const initialTimeout1 = setTimeout(() => {
      checkBackground();
    }, 100);
    
    const initialTimeout2 = setTimeout(() => {
      checkBackground();
    }, 500);

    // Check on scroll
    const handleScroll = () => {
      throttledCheck();
    };

    if (lenis) {
      lenis.on("scroll", handleScroll);
    } else {
      window.addEventListener("scroll", handleScroll, { passive: true });
    }

    // Check on resize
    const handleResize = () => {
      throttledCheck();
    };
    window.addEventListener("resize", handleResize, { passive: true });

    // Also check when page becomes visible (handles tab switching)
    const handleVisibilityChange = () => {
      if (!document.hidden) {
        setTimeout(() => checkBackground(), 100);
      }
    };
    document.addEventListener("visibilitychange", handleVisibilityChange);

    return () => {
      clearTimeout(initialTimeout1);
      clearTimeout(initialTimeout2);
      if (rafRef.current) {
        cancelAnimationFrame(rafRef.current);
      }
      if (lenis) {
        lenis.off("scroll", handleScroll);
      } else {
        window.removeEventListener("scroll", handleScroll);
      }
      window.removeEventListener("resize", handleResize);
      document.removeEventListener("visibilitychange", handleVisibilityChange);
    };
  }, [lenis]);

  return isLightBackground;
}

