import { useState, useRef, useEffect } from "react";
import { motion, useScroll, useMotionValueEvent } from "framer-motion";
import { Menu, X, ChevronDown } from "lucide-react";

const primaryLinks = [
  { name: "Projekte", href: "#projects" },
  { name: "Erfahrung", href: "#experience" },
  { name: "Über mich", href: "#bio" },
];

const secondaryLinks = [
  { name: "Kompetenzen", href: "#competencies" },
  { name: "Stärken", href: "#strengths" },
  { name: "Skills", href: "#skills" },
];

const mobileGroups = [
  {
    label: "Profil",
    links: [
      { name: "Über mich", href: "#bio" },
      { name: "Kompetenzen", href: "#competencies" },
      { name: "Stärken", href: "#strengths" },
    ],
  },
  {
    label: "Erfahrung & Skills",
    links: [
      { name: "Projekte", href: "#projects" },
      { name: "Erfahrung", href: "#experience" },
      { name: "Skills", href: "#skills" },
    ],
  },
];

export function Navbar() {
  const [isScrolled, setIsScrolled] = useState(false);
  const [mobileOpen, setMobileOpen] = useState(false);
  const [dropdownOpen, setDropdownOpen] = useState(false);
  const dropdownRef = useRef<HTMLDivElement>(null);
  const { scrollY } = useScroll();

  useMotionValueEvent(scrollY, "change", (latest) => {
    setIsScrolled(latest > 20);
  });

  useEffect(() => {
    function handleClickOutside(e: MouseEvent) {
      if (dropdownRef.current && !dropdownRef.current.contains(e.target as Node)) {
        setDropdownOpen(false);
      }
    }
    document.addEventListener("mousedown", handleClickOutside);
    return () => document.removeEventListener("mousedown", handleClickOutside);
  }, []);

  return (
    <motion.header
      className={`fixed top-0 w-full z-50 transition-all duration-300 ${
        isScrolled
          ? "bg-white/95 backdrop-blur-md border-b border-border shadow-sm py-3"
          : "bg-transparent py-5"
      }`}
      initial={{ y: -100 }}
      animate={{ y: 0 }}
      transition={{ duration: 0.4, ease: "easeOut" }}
    >
      <div className="max-w-6xl mx-auto px-4 md:px-8 flex items-center justify-between">
        <a
          href="#hero"
          className="flex items-center gap-2 text-foreground font-bold text-lg tracking-tight"
          data-testid="link-logo"
        >
          <span className="w-8 h-8 rounded-lg bg-primary flex items-center justify-center text-white text-sm font-bold">
            JH
          </span>
          <span className="hidden sm:block text-foreground">Joachim Hummel</span>
        </a>

        <nav className="hidden md:flex items-center gap-1">
          {primaryLinks.map((link) => (
            <a
              key={link.name}
              href={link.href}
              className="px-4 py-2 text-sm font-medium text-muted-foreground hover:text-foreground hover:bg-secondary rounded-lg transition-all"
              data-testid={`link-nav-${link.name.toLowerCase().replace(/\s/g, '-')}`}
            >
              {link.name}
            </a>
          ))}

          <div className="relative" ref={dropdownRef}>
            <button
              onClick={() => setDropdownOpen(!dropdownOpen)}
              className="flex items-center gap-1 px-4 py-2 text-sm font-medium text-muted-foreground hover:text-foreground hover:bg-secondary rounded-lg transition-all"
              data-testid="button-nav-mehr"
              aria-expanded={dropdownOpen}
            >
              Mehr
              <ChevronDown
                className={`w-3.5 h-3.5 transition-transform duration-200 ${dropdownOpen ? "rotate-180" : ""}`}
              />
            </button>

            {dropdownOpen && (
              <motion.div
                initial={{ opacity: 0, y: -6 }}
                animate={{ opacity: 1, y: 0 }}
                transition={{ duration: 0.15 }}
                className="absolute right-0 top-full mt-1.5 w-40 bg-white border border-border rounded-xl shadow-lg py-1.5"
              >
                {secondaryLinks.map((link) => (
                  <a
                    key={link.name}
                    href={link.href}
                    onClick={() => setDropdownOpen(false)}
                    className="block px-4 py-2 text-sm font-medium text-muted-foreground hover:text-foreground hover:bg-secondary transition-all"
                    data-testid={`link-nav-${link.name.toLowerCase()}`}
                  >
                    {link.name}
                  </a>
                ))}
              </motion.div>
            )}
          </div>
        </nav>

        <div className="hidden md:block">
          <a
            href="#contact"
            className="px-4 py-2 bg-primary text-white text-sm font-semibold rounded-lg hover:bg-primary/90 transition-colors"
            data-testid="button-nav-contact"
          >
            Kontakt
          </a>
        </div>

        <button
          className="md:hidden p-2 rounded-lg text-muted-foreground hover:bg-secondary transition-colors"
          onClick={() => setMobileOpen(!mobileOpen)}
          data-testid="button-mobile-menu"
        >
          {mobileOpen ? <X className="w-5 h-5" /> : <Menu className="w-5 h-5" />}
        </button>
      </div>

      {mobileOpen && (
        <motion.div
          initial={{ opacity: 0, y: -8 }}
          animate={{ opacity: 1, y: 0 }}
          className="md:hidden bg-white border-t border-border px-4 py-4 flex flex-col gap-4"
        >
          {mobileGroups.map((group) => (
            <div key={group.label}>
              <p className="px-4 mb-1 text-[10px] font-semibold uppercase tracking-widest text-muted-foreground/60">
                {group.label}
              </p>
              <div className="flex flex-col gap-0.5">
                {group.links.map((link) => (
                  <a
                    key={link.name}
                    href={link.href}
                    onClick={() => setMobileOpen(false)}
                    className="px-4 py-2.5 text-sm font-medium text-muted-foreground hover:text-foreground hover:bg-secondary rounded-lg transition-all"
                  >
                    {link.name}
                  </a>
                ))}
              </div>
            </div>
          ))}

          <div className="pt-1 border-t border-border">
            <a
              href="#contact"
              onClick={() => setMobileOpen(false)}
              className="block px-4 py-3 bg-primary text-white text-sm font-semibold rounded-lg text-center"
            >
              Kontakt aufnehmen
            </a>
          </div>
        </motion.div>
      )}
    </motion.header>
  );
}
