'use client';

import Link from 'next/link';
import { usePathname } from 'next/navigation';
import { useEffect, useRef, useState } from 'react';
import type { CitySummary } from '@/types';
import type { NavItem } from '@/lib/admin/types';
import { routes } from '@/lib/routes';
import { ChevronDownIcon, CloseIcon, MenuIcon } from '@/components/icons/common';
import { LogoHeader, LogoMobile } from '@/components/icons/logos';
import { sortPublicEventCities } from '@/lib/events/public-cities';
import { customBrandUrl } from '@/lib/media/display-url';

const DESKTOP_MIN_WIDTH = 992;

function isEventsItem(item: NavItem): boolean {
  const path = navPath(item.url);
  return path === '/events' || path === '/event' || item.label.toLowerCase() === 'events';
}

/** Pathname of an internal menu href, or '' for external / hash-only links. */
function navPath(url: string): string {
  const path = url.split('#')[0]?.split('?')[0] ?? '';
  if (!path.startsWith('/')) return '';
  return path.length > 1 ? path.replace(/\/+$/, '') : path;
}

/** True when this menu href is the page, or a parent of the page, the user is viewing. */
function isCurrentSection(pathname: string, url: string): boolean {
  const target = navPath(url);
  if (!target) return false;
  const current = pathname.length > 1 ? pathname.replace(/\/+$/, '') : pathname;
  if (target === '/') return current === '/';
  return current === target || current.startsWith(`${target}/`);
}

function BrandMark({ logoUrl, siteName, mobile }: { logoUrl: string; siteName: string; mobile?: boolean }) {
  const src = customBrandUrl(logoUrl);
  if (!src) return mobile ? <LogoMobile /> : <LogoHeader />;
  return (
    // eslint-disable-next-line @next/next/no-img-element
    <img src={src} alt={siteName} className={mobile ? 'phone-logo m-0' : 'nav-logo-svg'} style={{ height: mobile ? 28 : 30, width: 'auto' }} />
  );
}

function sortCitiesByName(cities: CitySummary[]): CitySummary[] {
  return sortPublicEventCities(cities);
}

export default function HeaderNav({
  cities,
  items,
  logoUrl = '',
  siteName = 'CMORoom',
}: {
  cities: CitySummary[];
  items: NavItem[];
  logoUrl?: string;
  siteName?: string;
}) {
  const pathname = usePathname();
  const [menuOpen, setMenuOpen] = useState(false);
  const menuRef = useRef<HTMLUListElement>(null);
  const currentCity = pathname.match(/^\/events\/([^/]+)$/)?.[1] ?? '';
  const citiesAlpha = sortCitiesByName(cities);

  const [lastPath, setLastPath] = useState(pathname);
  if (pathname !== lastPath) {
    setLastPath(pathname);
    setMenuOpen(false);
  }

  useEffect(() => {
    const menu = menuRef.current;
    if (!menu || window.innerWidth < DESKTOP_MIN_WIDTH) return;
    const dropdowns = Array.from(menu.querySelectorAll<HTMLElement>('.cmr-nav-dropdown'));
    const toggle = (dropdown: HTMLElement, show: boolean) => {
      const trigger = dropdown.querySelector('.cmr-dropdown-toggle');
      trigger?.setAttribute('aria-expanded', String(show));
      trigger?.classList.toggle('show', show);
      dropdown.querySelector('.dropdown-menu')?.classList.toggle('show', show);
    };
    const handlers = dropdowns.map((dropdown) => {
      const enter = () => toggle(dropdown, true);
      const leave = () => toggle(dropdown, false);
      dropdown.addEventListener('mouseenter', enter);
      dropdown.addEventListener('mouseleave', leave);
      return () => {
        dropdown.removeEventListener('mouseenter', enter);
        dropdown.removeEventListener('mouseleave', leave);
      };
    });
    return () => handlers.forEach((off) => off());
  }, [items]);

  useEffect(() => {
    menuRef.current?.querySelectorAll('.dropdown-menu.show, .cmr-dropdown-toggle.show').forEach((el) => el.classList.remove('show'));
  }, [pathname]);

  return (
    <header className="bg-color-black sticky-top z-9999 box-shadow1 py-3">
      <div className="container">
        <div className="header-area d-flex justify-content-between align-items-center gap-3">
          <Link href={routes.home} className="mx-0" aria-label={siteName}>
            <BrandMark logoUrl={logoUrl} siteName={siteName} />
          </Link>
          <ul
            ref={menuRef}
            className={`navbar-nav header-right-side-web-menu companies-menu d-flex flex-lg-row align-items-start align-items-lg-center flex-grow-1 justify-content-lg-center gap-3 gap-lg-4 gap-xl-5 mb-0 py-lg-2${menuOpen ? ' active' : ''}`}
          >
            <li className="d-flex justify-content-between align-items-center w-100 border-bottom pb-3 d-lg-none mb-3">
              <Link href={routes.home} aria-label={siteName}>
                <BrandMark logoUrl={logoUrl} siteName={siteName} mobile />
              </Link>{' '}
              <button type="button" className="mobile-close-btn no-bg-btn m-0" aria-label="Close menu" onClick={() => setMenuOpen(false)}>
                <CloseIcon />
              </button>
            </li>
            {items.map((item) => {
              const children = item.children ?? [];
              const useCities = isEventsItem(item) && children.length === 0 && cities.length > 0;
              const hasDropdown = children.length > 0 || useCities;

              const sectionActive =
                isCurrentSection(pathname, item.url) ||
                children.some((child) => isCurrentSection(pathname, child.url)) ||
                (useCities && currentCity !== '');

              if (!hasDropdown) {
                return (
                  <li key={item.id} className="nav-item">
                    <Link
                      className={`nav-link text-md fw-500 p-0 m-0${sectionActive ? ' active' : ''}`}
                      href={item.url}
                      aria-current={sectionActive ? 'page' : undefined}
                    >
                      {item.label}
                    </Link>
                  </li>
                );
              }

              return (
                <li key={item.id} className="nav-item dropdown cmr-nav-dropdown">
                  <a
                    className={`nav-link text-md fw-500 p-0 m-0 cmr-dropdown-toggle d-flex align-items-center gap-3${sectionActive ? ' active' : ''}`}
                    href={item.url}
                    role="button"
                    data-bs-toggle="dropdown"
                    aria-expanded="false"
                    aria-current={sectionActive ? 'page' : undefined}
                  >
                    {item.label} <ChevronDownIcon />
                  </a>
                  <div className={`dropdown-menu cmr-dropdown-menu${useCities ? ' dropdown-menu-events' : ''}`}>
                    {useCities ? (
                      <div className="events-grid">
                        {citiesAlpha.map((city) => {
                          const active = city.slug === currentCity;
                          return (
                            <Link
                              key={city.slug}
                              className={`dropdown-item${active ? ' active' : ''}`}
                              href={routes.city(city.slug)}
                              aria-current={active ? 'page' : undefined}
                            >
                              {city.name}
                            </Link>
                          );
                        })}
                      </div>
                    ) : (
                      children.map((child) => {
                        const childActive = isCurrentSection(pathname, child.url);
                        return (
                          <Link
                            key={child.id}
                            className={`dropdown-item${childActive ? ' active' : ''}`}
                            href={child.url}
                            aria-current={childActive ? 'page' : undefined}
                          >
                            {child.label}
                          </Link>
                        );
                      })
                    )}
                  </div>
                </li>
              );
            })}
          </ul>
          <button type="button" className="mobile-menu-btn d-lg-none" aria-label="Open menu" onClick={() => setMenuOpen(true)}>
            <MenuIcon />
          </button>
        </div>
      </div>
      <div className={`mobile-menu-overlay${menuOpen ? ' active' : ''}`} onClick={() => setMenuOpen(false)} />
    </header>
  );
}
