"use client";

import Image from "next/image";
import Link from "next/link";
import { usePathname } from "next/navigation";
import { useEffect, useState } from "react";
import type { SettingsContent } from "@/lib/content/types";

const navigation = [
  ["Start", "/"],
  ["Leistungen", "/leistungen"],
  ["Funkgeräte-Service", "/funkgeraete-service"],
  ["Reparatur", "/reparatur"],
  ["Über uns", "/ueber-uns"],
  ["Kontakt", "/kontakt"],
] as const;

const fallbackSettings = {
  siteName: "Funktechnik Schubert",
  logoUrl: "/funktechnik_schubert_logo.jpg",
  headerCta: { label: "Reparatur anfragen", href: "/reparatur" },
};

export default function Header() {
  const pathname = usePathname();
  const [menuOpen, setMenuOpen] = useState(false);
  const [settings, setSettings] = useState(fallbackSettings);

  useEffect(() => {
    let active = true;

    async function loadSettings() {
      try {
        const response = await fetch("/api/content/settings");
        const result = await response.json() as { settings?: SettingsContent };
        if (active && response.ok && result.settings) {
          setSettings({
            siteName: result.settings.siteName,
            logoUrl: result.settings.logoUrl,
            headerCta: result.settings.headerCta,
          });
        }
      } catch {
        if (active) setSettings(fallbackSettings);
      }
    }

    void loadSettings();
    return () => {
      active = false;
    };
  }, []);

  return (
    <header className="site-header">
      <div className="container header-inner">
        <Link href="/" className="brand" aria-label={`${settings.siteName} Startseite`} onClick={() => setMenuOpen(false)}>
          <Image
            src={settings.logoUrl}
            alt={settings.siteName}
            width={1672}
            height={941}
            priority
            className="brand-logo"
          />
        </Link>
        <button
          className="menu-toggle"
          type="button"
          aria-expanded={menuOpen}
          aria-controls="site-navigation"
          onClick={() => setMenuOpen((open) => !open)}
        >
          Menü
        </button>
        <nav id="site-navigation" className={menuOpen ? "nav is-open" : "nav"} aria-label="Hauptnavigation">
          {navigation.map(([label, href]) => (
            <Link key={href} href={href} aria-current={pathname === href ? "page" : undefined} onClick={() => setMenuOpen(false)}>
              {label}
            </Link>
          ))}
        </nav>
        <Link className="header-cta" href={settings.headerCta.href}>{settings.headerCta.label}</Link>
      </div>
    </header>
  );
}
