"use client";

import Link from "next/link";
import Image from "next/image";
import { usePathname } from "next/navigation";
import { useState } from "react";
import { navLinks, siteConfig } from "@/lib/site-config";
import type { NavChild } from "@/lib/site-config";
import {
  ChevronDownIcon,
  InstagramIcon,
  MenuIcon,
} from "@/components/ui/icons";
import MobileMenu from "@/components/layout/MobileMenu";

/** Returns true if any child href matches the current pathname. */
function isChildActive(children: NavChild[], pathname: string): boolean {
  return children.some((child) => {
    if (child.href.startsWith("/#")) return false;
    const path = child.href.split("#")[0];
    if (!path || path === "/") return pathname === "/";
    return pathname.startsWith(path);
  });
}

export default function Navbar() {
  const [menuOpen, setMenuOpen] = useState(false);
  const [openDropdown, setOpenDropdown] = useState<string | null>(null);
  const pathname = usePathname();

  return (
    <>
      <header className="fixed inset-x-0 top-0 z-40 h-[60px] bg-secondary/95 shadow-md backdrop-blur-md md:h-[72px]">
        <div className="mx-auto flex h-full max-w-content items-center justify-between px-4 sm:px-6 lg:px-8">
          <Link
            href="/"
            className="flex items-center gap-2 font-display text-xl tracking-wide text-cream"
          >
            <Image
              src="/images/skr-yudanshakai-logo.jpg"
              alt="SKR Yudanshakai"
              width={40}
              height={40}
              className="rounded-full flex-shrink-0"
              priority
            />
            <span>Shotokan Karate Club Arbon</span>
          </Link>

          <nav
            aria-label="Hauptnavigation"
            className="hidden items-center gap-7 md:flex"
          >
            {navLinks.map((item) => {
              if (item.children) {
                const active = isChildActive(item.children, pathname);
                return (
                  <div
                    key={item.label}
                    className="group relative"
                    onMouseEnter={() => setOpenDropdown(item.label)}
                    onMouseLeave={() => setOpenDropdown(null)}
                  >
                    {/* Dropdown trigger */}
                    <button
                      className={`flex items-center border-b-[3px] pb-1 text-sm font-medium tracking-wide transition-colors duration-fast ${
                        active
                          ? "border-primary text-cream"
                          : "border-transparent text-gray-200 hover:text-cream"
                      }`}
                      aria-haspopup="true"
                      aria-expanded={openDropdown === item.label}
                      type="button"
                    >
                      {item.label}
                      <ChevronDownIcon className="ml-1 h-3 w-3 transition-transform duration-fast group-hover:rotate-180" />
                    </button>

                    {/* Dropdown panel — shown on group hover via CSS */}
                    <div className="absolute left-0 top-full hidden min-w-[220px] rounded-lg bg-secondary py-2 shadow-xl group-hover:block">
                      {item.children.map((child) => (
                        <Link
                          key={child.href}
                          href={child.href}
                          className="block px-4 py-2 text-sm text-gray-200 hover:bg-[#2a2a2a] hover:text-cream"
                        >
                          {child.label}
                        </Link>
                      ))}
                    </div>
                  </div>
                );
              }

              // Simple link (no children)
              const active =
                item.href === "/"
                  ? pathname === "/"
                  : pathname.startsWith(item.href);
              return (
                <Link
                  key={item.href}
                  href={item.href}
                  className={`border-b-[3px] pb-1 text-sm font-medium tracking-wide transition-colors duration-fast ${
                    active
                      ? "border-primary text-cream"
                      : "border-transparent text-gray-200 hover:text-cream"
                  }`}
                >
                  {item.label}
                </Link>
              );
            })}
          </nav>

          <div className="hidden items-center gap-5 md:flex">
            {siteConfig.social.instagram && (
              <a
                href={siteConfig.social.instagram}
                target="_blank"
                rel="noopener noreferrer"
                aria-label="Instagram (öffnet in neuem Tab)"
                className="text-gray-200 transition-colors duration-fast hover:text-accent"
              >
                <InstagramIcon className="h-5 w-5" />
              </a>
            )}
            <Link
              href="/kontakt#kontakt-formular"
              className="rounded bg-primary px-5 py-2.5 text-sm font-semibold text-cream transition-colors duration-fast hover:bg-primary-light"
            >
              Probetraining
            </Link>
          </div>

          <button
            onClick={() => setMenuOpen(true)}
            aria-label="Menü öffnen"
            className="p-2 text-cream md:hidden"
          >
            <MenuIcon className="h-7 w-7" />
          </button>
        </div>
      </header>

      <MobileMenu open={menuOpen} onClose={() => setMenuOpen(false)} />
    </>
  );
}
