"use client";

import { useState, useEffect, useRef, useCallback } from "react";
import { usePathname } from "next/navigation";
import { company, navLinks } from "@/constants";

export default function DynamicNotchNav() {
  const [isOpen, setIsOpen] = useState(false);
  const [isMobile, setIsMobile] = useState(false);
  const pathname = usePathname();
  const isHome = pathname === "/";
  const [notchDimensions, setNotchDimensions] = useState({
    centerWidth: 120,
    curveWidth: 90,
    logoPodWidth: 120,
    sidePadding: 60
  });
  const navRef = useRef<HTMLDivElement>(null);
  const logoRef = useRef<HTMLImageElement>(null);

  // Calculate dynamic notch dimensions based on logo size
  const calculateNotchDimensions = useCallback(() => {
    if (logoRef.current) {
      const logoWidth = logoRef.current.offsetWidth;
      const padding = 8; // breathing room around logo
      const centerWidth = Math.round(logoWidth + padding * 2);
      const curveWidth = Math.round(centerWidth * 0.75); // proportional curve width
      const sidePadding = Math.round(centerWidth / 2);

      setNotchDimensions({
        centerWidth,
        curveWidth,
        logoPodWidth: centerWidth,
        sidePadding
      });
    }
  }, []);

  useEffect(() => {
    const checkMobile = () => setIsMobile(window.innerWidth < 1024);
    checkMobile();
    const handleResize = () => {
      checkMobile();
      calculateNotchDimensions();
    };
    window.addEventListener("resize", handleResize);
    return () => window.removeEventListener("resize", handleResize);
  }, [calculateNotchDimensions]);

  // Recalculate when logo loads
  useEffect(() => {
    calculateNotchDimensions();
  }, [calculateNotchDimensions]);

  // Close menu on click outside
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (navRef.current && !navRef.current.contains(event.target as Node)) {
        setIsOpen(false);
      }
    };

    if (isOpen) {
      document.addEventListener('mousedown', handleClickOutside);
      return () => document.removeEventListener('mousedown', handleClickOutside);
    }
  }, [isOpen]);

  // Smooth scroll to section, offset so it lands fully below the 84px notch bar
  const scrollToSection = (href: string) => {
    const element = document.querySelector(href);
    if (element) {
      const top = element.getBoundingClientRect().top + window.scrollY - 30;
      window.scrollTo({ top, behavior: 'smooth' });
      setIsOpen(false);
    }
  };

  // Unified link handler: page links navigate, anchor links scroll on home
  // or navigate home + hash from other pages.
  const handleNavClick = (e: React.MouseEvent, href: string) => {
    e.preventDefault();
    setIsOpen(false);

    const isAnchor = href.startsWith("#");
    if (!isAnchor) {
      window.location.href = href;
      return;
    }
    if (isHome) {
      scrollToSection(href);
    } else {
      window.location.href = `/${href}`;
    }
  };

  // On homepage load with a hash (e.g. returning from blog), scroll smoothly
  useEffect(() => {
    if (isHome && window.location.hash) {
      const href = window.location.hash;
      const tryScroll = () => {
        const element = document.querySelector(href);
        if (element) {
          const top = element.getBoundingClientRect().top + window.scrollY - 30;
          window.scrollTo({ top, behavior: 'smooth' });
        }
      };
      // Wait a tick for the page to render
      const t = window.setTimeout(tryScroll, 100);
      return () => window.clearTimeout(t);
    }
  }, [isHome]);

  const navy = "#060e20";
  const gold = "#c9a24b";

  return (
    <>
      <header
        ref={navRef}
        className="fixed left-0 right-0 top-0 z-50 flex justify-center"
      >
        <div style={{ position: 'relative', width: '100%', maxWidth: '1920px', height: '84px' }}>
          {/* Background Structure - The Notch */}
          <div style={{ position: 'absolute', inset: 0, zIndex: 0 }}>
            {/* Top bar - full-height solid bar on mobile, 30px strip on desktop */}
            <div className="absolute top-0 left-0 w-full h-[84px] lg:h-[30px]" style={{ background: navy }}></div>

            {/* The dip under the logo area - desktop only */}
            <div className="hidden lg:flex" style={{ position: 'absolute', top: '30px', left: '50%', transform: 'translateX(-50%)' }}>
              {/* Left SVG curve - symmetric S-curve with horizontal tangents at both ends */}
              <svg width={notchDimensions.curveWidth} height="54" viewBox={`0 0 ${notchDimensions.curveWidth} 54`} fill="none">
                <path d={`M0 0 C${notchDimensions.curveWidth * 0.5} 0 ${notchDimensions.curveWidth * 0.5} 54 ${notchDimensions.curveWidth} 54 L${notchDimensions.curveWidth} 0 Z`} fill={navy} />
              </svg>

              {/* Center flat area - dynamic width to fit logo */}
              <div style={{ width: `${notchDimensions.centerWidth}px`, height: '54px', background: navy }}></div>

              {/* Right SVG curve - symmetric S-curve with horizontal tangents at both ends */}
              <svg width={notchDimensions.curveWidth} height="54" viewBox={`0 0 ${notchDimensions.curveWidth} 54`} fill="none">
                <path d={`M${notchDimensions.curveWidth} 0 C${notchDimensions.curveWidth * 0.5} 0 ${notchDimensions.curveWidth * 0.5} 54 0 54 L0 0 Z`} fill={navy} />
              </svg>
            </div>
          </div>

          {/* Navigation Links - positioned in the 30px top strip */}
          <div className="container-x h-[84px] lg:h-[30px]" style={{ position: 'relative', zIndex: 10, display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
            {/* Left side nav links */}
            <nav className="hidden lg:flex items-center gap-6" style={{ paddingRight: `${notchDimensions.sidePadding}px` }}>
              {navLinks.slice(0, Math.ceil(navLinks.length / 2)).map((link) => (
                <a
                  key={link.href}
                  href={link.href}
                  onClick={(e) => handleNavClick(e, link.href)}
                  className="text-xs font-medium text-white/80 hover:text-white transition-colors"
                >
                  {link.label}
                </a>
              ))}
            </nav>

            {/* Right side nav links */}
            <nav className="hidden lg:flex items-center gap-6" style={{ paddingLeft: `${notchDimensions.sidePadding}px` }}>
              {navLinks.slice(Math.ceil(navLinks.length / 2)).map((link) => (
                <a
                  key={link.href}
                  href={link.href}
                  onClick={(e) => handleNavClick(e, link.href)}
                  className="text-xs font-medium text-white/80 hover:text-white transition-colors"
                >
                  {link.label}
                </a>
              ))}
              <a
                href="/contact/"
                onClick={(e) => handleNavClick(e, "/contact/")}
                className="px-3 py-1 bg-gradient-to-r from-gold to-gold/80 text-white text-xs font-semibold rounded-full shadow-lg"
                style={{ background: gold }}
              >
                Contact
              </a>
            </nav>

            {/* Mobile menu button */}
            <button
              onClick={() => setIsOpen(!isOpen)}
              className="lg:hidden w-8 h-8 flex items-center justify-center text-white hover:bg-white/10 transition-colors rounded"
              aria-label={isOpen ? "Close menu" : "Open menu"}
              style={{ zIndex: 20 }}
            >
              {!isOpen ? (
                <svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 6h16M4 12h16M4 18h16" />
                </svg>
              ) : (
                <svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                </svg>
              )}
            </button>
          </div>

          {/* Logo Pod - centered in full 84px height, links home */}
          <a
            href="/"
            onClick={(e) => { if (!isHome) return; e.preventDefault(); window.scrollTo({ top: 0, behavior: 'smooth' }); }}
            style={{ position: 'absolute', top: 0, left: '50%', transform: 'translateX(-50%)', zIndex: 10, display: 'flex', alignItems: 'center', justifyContent: 'center', height: '84px', width: `${notchDimensions.logoPodWidth}px` }}
          >
            <img ref={logoRef} src="/logo.svg" alt={`${company.name} logo`} className="w-[72px] h-[72px]" />
          </a>
        </div>

        {/* Mobile Menu */}
        {isOpen && isMobile && (
          <div className="lg:hidden absolute top-[84px] left-0 right-0" style={{ background: "#060e20", borderTop: '1px solid rgba(255,255,255,0.1)' }}>
            <nav className="flex flex-col p-4">
              {navLinks.map((link) => (
                <a
                  key={link.href}
                  href={link.href}
                  onClick={(e) => handleNavClick(e, link.href)}
                  className="px-4 py-3 text-sm font-medium text-white/80 hover:text-white hover:bg-white/10 rounded-lg transition-all"
                >
                  {link.label}
                </a>
              ))}
              <a
                href="/contact/"
                onClick={(e) => handleNavClick(e, "/contact/")}
                className="mt-2 px-4 py-3 text-sm font-semibold text-white rounded-lg text-center"
                style={{ background: gold }}
              >
                Get in touch
              </a>
            </nav>
          </div>
        )}
      </header>

      {/* Spacer for fixed header */}
      
    </>
  );
}
