"use client";

import Image from "next/image";
import Link from "next/link";
import { onepageHeaderData } from "@/data/shared/onepageHeaderData";
import { useEffect, useState } from "react";
import { Link as ScrollLink } from "react-scroll";

export default function HeaderSection() {
  const [isSticky, setIsSticky] = useState(false);
  const [isSearchActive, setIsSearchActive] = useState(false);
  const [isMobileMenuActive, setIsMobileMenuActive] = useState(false);
  const [currentPath, setCurrentPath] = useState("");
  const [activeSection, setActiveSection] = useState("home");
  const [isScrolling, setIsScrolling] = useState(false);

  // Check if navigation item is active
  const isActive = (href: string) => {
    const sectionId = href.replace("#", "");
    return activeSection === sectionId;
  };

  useEffect(() => {
    // Set current path on client side only
    setCurrentPath(window.location.pathname);

    const handleScroll = () => {
      const scrollPosition =
        window.scrollY || document.documentElement.scrollTop;
      const shouldBeSticky = scrollPosition > 50;

      setIsSticky(shouldBeSticky);

      // Only update active section if not in smooth scroll animation
      if (!isScrolling) {
        // Determine which section is currently in view
        const sections = onepageHeaderData.navigation.map((item) =>
          item.href.replace("#", ""),
        );
        let currentActiveSection = "home";

        sections.forEach((sectionId) => {
          const element = document.getElementById(sectionId);
          if (element) {
            const rect = element.getBoundingClientRect();
            const elementTop = rect.top + window.scrollY;
            const elementHeight = rect.height;

            // Check if section is in view (with some offset for header)
            // Use a more precise detection: section should take up significant viewport space
            const viewportHeight = window.innerHeight;
            const elementVisibleTop = Math.max(
              0,
              elementTop - scrollPosition - 100,
            );
            const elementVisibleBottom = Math.min(
              elementHeight,
              viewportHeight - 100,
            );
            const visiblePercentage =
              (elementVisibleBottom - elementVisibleTop) / elementHeight;

            if (visiblePercentage > 0.3) {
              // Section is more than 30% visible
              currentActiveSection = sectionId;
            }
          }
        });

        setActiveSection(currentActiveSection);
      }
    };

    // Initial check on mount
    handleScroll();

    window.addEventListener("scroll", handleScroll, { passive: true });
    return () =>
      window.removeEventListener("scroll", handleScroll, {
        passive: true,
      } as any);
  }, []);

  return (
    <>
      {/* Mobile Menu */}
      <div className={`mobile-menu ${isMobileMenuActive ? "active" : ""}`}>
        {/* Close Button */}
        <div className="close-btn" onClick={() => setIsMobileMenuActive(false)}>
          <Image
            src={onepageHeaderData.mobileMenu.closeIcon.src}
            alt={onepageHeaderData.mobileMenu.closeIcon.alt}
            width={24}
            height={24}
          />
        </div>
        <nav>
          <ul className="main-menu11 menu-style11">
            {onepageHeaderData.navigation.map((item, index) => (
              <li key={index} className={isActive(item.href) ? "active" : ""}>
                <ScrollLink
                  to={item.href.replace("#", "")}
                  spy={true}
                  smooth={true}
                  offset={-70}
                  duration={500}
                  style={{ cursor: "pointer" }}
                  aria-label={`Navigate to ${item.text} section`}
                  role="menuitem"
                  tabIndex={0}
                  onClick={() => {
                    setIsMobileMenuActive(false);
                    setIsScrolling(true);
                    setActiveSection(item.href.replace("#", ""));
                    setTimeout(() => setIsScrolling(false), 600);
                  }}
                  onKeyDown={(e) => {
                    if (e.key === "Enter" || e.key === " ") {
                      e.preventDefault();
                      setIsMobileMenuActive(false);
                      setIsScrolling(true);
                      setActiveSection(item.href.replace("#", ""));
                      setTimeout(() => setIsScrolling(false), 600);
                    }
                  }}
                >
                  {item.text}
                </ScrollLink>
              </li>
            ))}
          </ul>
        </nav>
      </div>
      <div
        className={`menu-overlay ${isMobileMenuActive ? "active" : ""}`}
        onClick={() => setIsMobileMenuActive(false)}
      />
      {/* search box */}
      <div className={`search-popup ${isSearchActive ? "active" : ""}`}>
        <form className="search-form">
          <input
            type="text"
            placeholder={onepageHeaderData.searchPopup.placeholder}
            required={true}
          />
          <button type="submit" className="submit-btn">
            <Image
              src={onepageHeaderData.searchPopup.submitIcon.src}
              alt={onepageHeaderData.searchPopup.submitIcon.alt}
              width={20}
              height={20}
            />
          </button>
        </form>
      </div>
      <div
        className={`search-overlay ${isSearchActive ? "active" : ""}`}
        onClick={() => setIsSearchActive(false)}
      />
      {/* Header */}
      <header className={`header-main ${isSticky ? "sticky" : ""}`}>
        <div className="carousel-container">
          <div className="header-bottom">
            <div className="row">
              {/* Logo */}
              <div className="col-lg-2 col-md-6 col-sm-6">
                <div className="header-logo">
                  <Link
                    href={onepageHeaderData.logo.href}
                    className="logo"
                    title="Home"
                  >
                    <Image
                      src={onepageHeaderData.logo.lightSrc}
                      alt={onepageHeaderData.logo.alt}
                      width={130}
                      height={30}
                    />
                  </Link>
                  <Link href={onepageHeaderData.logo.href} title="Home">
                    <Image
                      src={onepageHeaderData.logo.darkSrc}
                      alt={`${onepageHeaderData.logo.alt} Dark`}
                      width={130}
                      height={30}
                    />
                  </Link>
                </div>
              </div>
              {/* Navigation Menu */}
              <div className="col-lg-7">
                <nav
                  className="main-menu11 menu-style11"
                  aria-label="Main Navigation"
                >
                  <ul>
                    {onepageHeaderData.navigation.map((item, index) => (
                      <li
                        key={index}
                        className={isActive(item.href) ? "active" : ""}
                      >
                        <ScrollLink
                          to={item.href.replace("#", "")}
                          spy={true}
                          smooth={true}
                          offset={-50}
                          duration={500}
                          style={{ cursor: "pointer" }}
                          aria-label={`Navigate to ${item.text} section`}
                          role="menuitem"
                          tabIndex={0}
                          onClick={() => {
                            setIsScrolling(true);
                            setActiveSection(item.href.replace("#", ""));
                            setTimeout(() => setIsScrolling(false), 600);
                          }}
                          onKeyDown={(e) => {
                            if (e.key === "Enter" || e.key === " ") {
                              e.preventDefault();
                              setIsScrolling(true);
                              setActiveSection(item.href.replace("#", ""));
                              setTimeout(() => setIsScrolling(false), 600);
                            }
                          }}
                        >
                          {item.text}
                        </ScrollLink>
                      </li>
                    ))}
                  </ul>
                </nav>
              </div>
              {/* Buttons */}
              <div className="col-lg-3 col-md-6 col-sm-6">
                <div className="header-btn">
                  <button
                    type="button"
                    className="search-btn"
                    aria-label={onepageHeaderData.buttons.search.ariaLabel}
                    onClick={() => setIsSearchActive(!isSearchActive)}
                  >
                    <Image
                      src={onepageHeaderData.buttons.search.iconSrc}
                      alt={onepageHeaderData.buttons.search.alt}
                      width={20}
                      height={20}
                    />
                  </button>
                  <Link
                    href={onepageHeaderData.buttons.login.href}
                    id={onepageHeaderData.buttons.login.id}
                    className="login-btn"
                  >
                    {onepageHeaderData.buttons.login.text}
                  </Link>
                  <Link
                    href={onepageHeaderData.buttons.signup.href}
                    className={`sign-btn ${onepageHeaderData.buttons.signup.className}`}
                  >
                    {onepageHeaderData.buttons.signup.text}
                  </Link>
                  {/* Hamburger for mobile */}
                  <button
                    className="hamburger-btn"
                    aria-label="Toggle Menu"
                    onClick={() => setIsMobileMenuActive(!isMobileMenuActive)}
                  >
                    <span />
                    <span />
                    <span />
                  </button>
                </div>
              </div>
            </div>
          </div>
          <div className="separator-line" />
        </div>
      </header>
    </>
  );
}
