import { siteBrandName } from '@frontend/content/home-page';
import { siteBrandLogo } from '@frontend/content/site-assets';
import { marketingHeaderCta } from '@frontend/content/marketing-navigation';
import {
    type MarketingDropdownNavItem,
    marketingDropdownNavItems,
} from '@frontend/content/marketing-navigation-dropdown';
import type { MarketingRouteName } from '@frontend/content/marketing-routes';
import { useMobileNav } from '@frontend/hooks/use-mobile-nav';
import { LanguageSwitcher } from '@frontend/components/language/language-switcher';
import { marketingRoute } from '@frontend/lib/marketing-route';
import { Link, usePage } from '@inertiajs/react';
import { useEffect, useState } from 'react';

function isNavActive(url: string, routeName: MarketingRouteName): boolean {
    if (routeName === 'home') {
        return url === '/' || url === '';
    }

    if (routeName === 'portfolio' || routeName === 'portfolio.show') {
        return url === '/portfolio' || url.startsWith('/portfolio/');
    }

    if (routeName === 'updates' || routeName === 'updates.show') {
        return url === '/updates' || url.startsWith('/updates/');
    }

    if (routeName === 'services' || routeName === 'services.show') {
        return url === '/services' || url.startsWith('/services/');
    }

    if (routeName === 'clients') {
        return url === '/clients';
    }

    if (routeName === 'testimonials') {
        return url === '/testimonials';
    }

    return url === marketingRoute(routeName);
}

function itemMatchesUrl(item: MarketingDropdownNavItem, url: string): boolean {
    if ('routeName' in item) {
        return isNavActive(url, item.routeName);
    }

    if ('children' in item) {
        return item.children.some((child) => itemMatchesUrl(child, url));
    }

    return false;
}

function NavLink({
    item,
    onNavigate,
}: {
    item: MarketingDropdownNavItem;
    onNavigate: () => void;
}): React.JSX.Element {
    if ('routeName' in item) {
        return (
            <Link href={marketingRoute(item.routeName)} onClick={onNavigate}>
                {item.label}
            </Link>
        );
    }

    return <a href="#">{item.label}</a>;
}

function NavItem({
    item,
    itemKey,
    url,
    openSubKey,
    onToggleSub,
    onNavigate,
}: {
    item: MarketingDropdownNavItem;
    itemKey: string;
    url: string;
    openSubKey: string | null;
    onToggleSub: (key: string, event: React.MouseEvent | React.KeyboardEvent) => void;
    onNavigate: () => void;
}): React.JSX.Element {
    if ('children' in item) {
        const branchActive = item.children.some((child) => itemMatchesUrl(child, url));
        const subOpen = openSubKey === itemKey;

        return (
            <li className={`has-sub${branchActive ? ' current' : ''}${subOpen ? ' sub-open' : ''}`}>
                <a href="#" onClick={(event) => onToggleSub(itemKey, event)}>
                    {item.label}
                </a>
                <span
                    className="submenu-button"
                    role="button"
                    tabIndex={0}
                    onClick={(event) => onToggleSub(itemKey, event)}
                    onKeyDown={(event) => {
                        if (event.key === 'Enter' || event.key === ' ') {
                            onToggleSub(itemKey, event);
                        }
                    }}
                    aria-label={`${item.label} submenu`}
                />
                <ul>
                    {item.children.map((child, index) => (
                        <NavItem
                            key={`${itemKey}-${index}`}
                            item={child}
                            itemKey={`${itemKey}-${index}`}
                            url={url}
                            openSubKey={openSubKey}
                            onToggleSub={onToggleSub}
                            onNavigate={onNavigate}
                        />
                    ))}
                </ul>
            </li>
        );
    }

    const active = itemMatchesUrl(item, url);

    return (
        <li className={active ? 'active' : undefined}>
            <NavLink item={item} onNavigate={onNavigate} />
        </li>
    );
}

export function Header(): React.JSX.Element {
    const { url } = usePage();
    const { isOpen, toggle, close } = useMobileNav();
    const [openSubKey, setOpenSubKey] = useState<string | null>(null);

    useEffect(() => {
        close();
        setOpenSubKey(null);
    }, [url, close]);

    const onToggleSub = (key: string, event: React.MouseEvent | React.KeyboardEvent): void => {
        event.preventDefault();
        setOpenSubKey((current) => (current === key ? null : key));
    };

    return (
        <header className="header-style3">
            <div className="navbar-default border-bottom border-color-light-white">
                <div className="container-fluid px-lg-1-6 px-xl-2-5 px-xxl-2-9">
                    <div className="row align-items-center">
                        <div className="col-12 col-lg-12">
                            <div className="menu_area alt-font">
                                <nav className="navbar navbar-expand-lg navbar-light p-0">
                                    <div className="navbar-header navbar-header-custom">
                                        <Link href={marketingRoute('home')} className="navbar-brand" onClick={close}>
                                            <img
                                                className="site-brand-logo"
                                                src={siteBrandLogo}
                                                data-brand-logo={siteBrandLogo}
                                                alt={siteBrandName}
                                            />
                                        </Link>
                                    </div>

                                    <div
                                        className={`navbar-toggler bg-primary${isOpen ? ' menu-opened' : ''}`}
                                        role="button"
                                        tabIndex={0}
                                        aria-expanded={isOpen}
                                        aria-controls="nav"
                                        onClick={toggle}
                                        onKeyDown={(event) => {
                                            if (event.key === 'Enter' || event.key === ' ') {
                                                toggle();
                                            }
                                        }}
                                    />

                                    <ul className="navbar-nav ms-auto" id="nav" style={isOpen ? { display: 'block' } : undefined}>
                                        {marketingDropdownNavItems.map((item, index) => (
                                            <NavItem
                                                key={`nav-${index}`}
                                                item={item}
                                                itemKey={`nav-${index}`}
                                                url={url}
                                                openSubKey={openSubKey}
                                                onToggleSub={onToggleSub}
                                                onNavigate={close}
                                            />
                                        ))}
                                    </ul>

                                    <div className="attr-nav align-items-xl-center ms-xl-auto main-font">
                                        <ul>
                                            <li className="language-switcher-attr d-inline-flex align-items-center">
                                                <LanguageSwitcher placement="attr" />
                                            </li>
                                            <li className="d-none d-xl-inline-block">
                                                <Link
                                                    href={marketingRoute(marketingHeaderCta.routeName)}
                                                    className="butn-style01 white-hover sm"
                                                    onClick={close}
                                                >
                                                    <span>{marketingHeaderCta.label}</span>
                                                </Link>
                                            </li>
                                        </ul>
                                    </div>
                                </nav>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </header>
    );
}