"use client";

import { useEffect, useRef, useState } from "react";
import Link from "next/link";
import { motion } from "framer-motion";
import { ChevronDown, Menu, Volume2, VolumeX, X } from "lucide-react";
import { useSound } from "@/components/providers/sound-provider";

const TOOLS = [
  { href: "/ja-nein-generator", label: "Ja-Nein-Generator", hint: "Schnelle Entscheidungen" },
  { href: "/muenze-werfen", label: "Münze werfen", hint: "Kopf oder Zahl" },
  { href: "/entweder-oder", label: "Entweder oder", hint: "Zwei Optionen abwägen" },
  { href: "/gluecksrad", label: "Glücksrad", hint: "Drehen & auswählen" },
  { href: "/wuerfel-online", label: "Würfel online", hint: "Für Spiel & Zufall" },
  { href: "/zufallszahl-generator", label: "Zufallszahl", hint: "Dein Zahlenbereich" },
  { href: "/magic-8-ball", label: "Magic 8-Ball", hint: "Das kleine Orakel" },
  { href: "/namen-auslosen", label: "Namen auslosen", hint: "Listen & Gewinner" },
];

export default function Nav() {
  const [scrolled, setScrolled] = useState(false);
  const [toolsOpen, setToolsOpen] = useState(false);
  const [mobileOpen, setMobileOpen] = useState(false);
  const dropdownRef = useRef<HTMLDivElement>(null);
  const { enabled, toggle, play } = useSound();

  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 10);
    const onKeyDown = (event: KeyboardEvent) => {
      if (event.key === "Escape") {
        setToolsOpen(false);
        setMobileOpen(false);
      }
    };
    const onPointerDown = (event: MouseEvent) => {
      if (!dropdownRef.current?.contains(event.target as Node)) setToolsOpen(false);
    };

    onScroll();
    window.addEventListener("scroll", onScroll, { passive: true });
    window.addEventListener("keydown", onKeyDown);
    window.addEventListener("mousedown", onPointerDown);
    return () => {
      window.removeEventListener("scroll", onScroll);
      window.removeEventListener("keydown", onKeyDown);
      window.removeEventListener("mousedown", onPointerDown);
    };
  }, []);

  const closeMenus = () => {
    setToolsOpen(false);
    setMobileOpen(false);
  };

  const soundButton = (
    <motion.button
      type="button"
      onClick={() => {
        toggle();
        if (!enabled) play("pop");
      }}
      whileTap={{ scale: 0.88 }}
      aria-label={enabled ? "Sound ausschalten" : "Sound einschalten"}
      title={enabled ? "Sound ausschalten" : "Sound einschalten"}
      className="flex h-10 w-10 shrink-0 cursor-pointer items-center justify-center rounded-full border border-line bg-surface text-ink-soft shadow-soft transition-colors duration-200 hover:border-[#0d7a57]/50 hover:text-[#0d7a57]"
    >
      {enabled ? <Volume2 className="h-[18px] w-[18px]" /> : <VolumeX className="h-[18px] w-[18px]" />}
    </motion.button>
  );

  return (
    <header className={`fixed inset-x-0 top-0 z-50 transition-all duration-300 ${scrolled || mobileOpen ? "border-b border-line/70 bg-paper/95 shadow-[0_4px_24px_rgb(23_23_28/0.05)] backdrop-blur-xl" : "border-b border-transparent bg-transparent"}`}>
      <nav className="mx-auto flex h-16 w-full max-w-6xl items-center justify-between px-5 sm:px-8" aria-label="Hauptnavigation">
        <Link href="/#top" className="group flex items-center gap-2.5" onClick={closeMenus}>
          <img
            src="/icon.svg"
            alt=""
            aria-hidden="true"
            className="h-9 w-9 shrink-0 transition-transform duration-200 group-hover:scale-105"
          />
          <span className="flex items-baseline">
          <span className="text-lg font-semibold tracking-tight">Entscheid</span>
          <span className="font-display text-lg italic text-[#0d7a57] transition-colors group-hover:text-[#095c41]">omat</span>
          </span>
        </Link>

        <div className="hidden items-center gap-1 sm:flex">
          <div ref={dropdownRef} className="relative">
            <button
              type="button"
              onClick={() => setToolsOpen((open) => !open)}
              aria-expanded={toolsOpen}
              aria-haspopup="menu"
              className="inline-flex items-center gap-1.5 rounded-full px-4 py-2 text-sm font-medium text-ink-soft transition-colors duration-200 hover:bg-[#e6f7f0] hover:text-[#0d7a57]"
            >
              Tools <ChevronDown className={`h-4 w-4 transition-transform duration-200 ${toolsOpen ? "rotate-180" : ""}`} />
            </button>
            {toolsOpen && (
              <div role="menu" className="absolute right-0 top-[calc(100%+0.7rem)] w-80 overflow-hidden rounded-3xl border border-line bg-surface p-2 shadow-[0_22px_55px_rgba(17,20,18,0.16)]">
                <p className="px-3 pb-2 pt-1 text-xs font-semibold uppercase tracking-[0.15em] text-ink-soft">Alle Zufalls-Tools</p>
                {TOOLS.map((tool) => (
                  <Link key={tool.href} href={tool.href} role="menuitem" onClick={closeMenus} className="group flex items-center justify-between rounded-2xl px-3 py-2.5 transition-colors hover:bg-[#e6f7f0]">
                    <span><span className="block text-sm font-semibold text-ink group-hover:text-[#0d7a57]">{tool.label}</span><span className="block text-xs text-ink-soft">{tool.hint}</span></span>
                    <span aria-hidden className="text-[#0d7a57] opacity-0 transition-opacity group-hover:opacity-100">→</span>
                  </Link>
                ))}
              </div>
            )}
          </div>
          <Link href="/developer" className="rounded-full px-4 py-2 text-sm font-medium text-ink-soft transition-colors duration-200 hover:bg-[#e6f7f0] hover:text-[#0d7a57]">Extensions &amp; API</Link>
          <Link href="/ratgeber" className="rounded-full px-4 py-2 text-sm font-medium text-ink-soft transition-colors duration-200 hover:bg-[#e6f7f0] hover:text-[#0d7a57]">Ratgeber</Link>
          <Link href="/#features" className="rounded-full px-4 py-2 text-sm font-medium text-ink-soft transition-colors duration-200 hover:bg-[#e6f7f0] hover:text-[#0d7a57]">Features</Link>
          {soundButton}
        </div>

        <div className="flex items-center gap-2 sm:hidden">
          {soundButton}
          <button type="button" onClick={() => setMobileOpen((open) => !open)} aria-expanded={mobileOpen} aria-controls="mobile-menu" aria-label={mobileOpen ? "Menü schließen" : "Menü öffnen"} className="flex h-10 w-10 items-center justify-center rounded-full border border-line bg-surface text-ink shadow-soft">
            {mobileOpen ? <X className="h-5 w-5" /> : <Menu className="h-5 w-5" />}
          </button>
        </div>
      </nav>

      {mobileOpen && (
        <div id="mobile-menu" className="border-t border-line/70 bg-paper px-5 pb-6 pt-4 shadow-xl sm:hidden">
          <div className="mx-auto max-w-6xl">
            <p className="mb-2 text-xs font-semibold uppercase tracking-[0.15em] text-ink-soft">Tools auswählen</p>
            <div className="grid gap-1">
              {TOOLS.map((tool) => <Link key={tool.href} href={tool.href} onClick={closeMenus} className="flex items-center justify-between rounded-2xl px-4 py-3 hover:bg-[#e6f7f0]"><span><span className="block font-semibold text-ink">{tool.label}</span><span className="text-xs text-ink-soft">{tool.hint}</span></span><span className="text-[#0d7a57]">→</span></Link>)}
            </div>
            <Link href="/developer" onClick={closeMenus} className="mt-3 block rounded-2xl border border-line bg-[#e6f7f0] px-4 py-3 font-semibold text-[#0d7a57]">Extensions &amp; Developer Suite</Link>
            <Link href="/ratgeber" onClick={closeMenus} className="mt-2 block rounded-2xl border border-line px-4 py-3 font-semibold text-ink">Ratgeber</Link>
            <Link href="/#features" onClick={closeMenus} className="mt-2 block rounded-2xl border border-line px-4 py-3 font-semibold text-ink">Features</Link>
          </div>
        </div>
      )}
    </header>
  );
}
