"use client";

import { useState, useEffect, useTransition } from "react";
import { motion, AnimatePresence } from "framer-motion";
import { Menu, X, Languages } from "lucide-react";
import { ThemeToggle } from "@/shared/components/theme-toggle";
import { useTranslations, useLocale } from "next-intl";
import { usePathname, useRouter } from "@/i18n/routing";

const SECTIONS = ["experience", "tech-stack", "projects", "contact"];

export function Navbar() {
  const [isScrolled, setIsScrolled] = useState(false);
  const [isOpen, setIsOpen] = useState(false);
  const [activeSection, setActiveSection] = useState("");
  const t = useTranslations("Navigation");
  const locale = useLocale();
  const router = useRouter();
  const pathname = usePathname();
  const [isPending, startTransition] = useTransition();

  useEffect(() => {
    const handleScroll = () => setIsScrolled(window.scrollY > 20);
    window.addEventListener("scroll", handleScroll);
    return () => window.removeEventListener("scroll", handleScroll);
  }, []);

  // #4 Scroll spy — highlight active nav link
  useEffect(() => {
    const observer = new IntersectionObserver(
      (entries) => {
        for (const entry of entries) {
          if (entry.isIntersecting) {
            setActiveSection(entry.target.id);
          }
        }
      },
      { rootMargin: "-40% 0px -55% 0px", threshold: 0 }
    );

    for (const id of SECTIONS) {
      const el = document.getElementById(id);
      if (el) observer.observe(el);
    }

    return () => observer.disconnect();
  }, []);

  const navLinks = [
    { href: "#experience", id: "experience", label: t("experience") },
    { href: "#tech-stack", id: "tech-stack", label: t("techStack") },
    { href: "#projects", id: "projects", label: t("projects") },
    { href: "#contact", id: "contact", label: t("contact") },
  ];

  const switchLocale = (newLocale: string) => {
    startTransition(() => {
      router.replace(pathname, { locale: newLocale });
      setIsOpen(false);
    });
  };

  return (
    <motion.header
      initial={{ y: -100 }}
      animate={{ y: 0 }}
      transition={{ duration: 0.6, ease: [0.25, 0.4, 0.25, 1] }}
      className={`fixed top-0 left-0 right-0 z-50 transition-all duration-500 ${
        isScrolled
          ? "glass shadow-lg border-b border-border/50"
          : "bg-transparent"
      }`}
    >
      <nav className="max-w-6xl mx-auto px-6 py-4 flex items-center justify-between">
        {/* #12 Logo with hover glow */}
        <a href="#" className="flex items-center gap-2 group">
          <div className="w-9 h-9 rounded-lg bg-gradient-to-br from-accent to-purple-500 flex items-center justify-center text-white font-bold text-sm shadow-lg shadow-accent/25 group-hover:shadow-accent/50 group-hover:scale-110 transition-all duration-300">
            A
          </div>
          <span className="font-mono font-bold text-lg tracking-tight">
            ando<span className="text-accent">.dev</span>
          </span>
        </a>

        {/* Desktop Nav with scroll spy */}
        <div className="hidden md:flex items-center gap-1">
          {navLinks.map((link) => (
            <a
              key={link.href}
              href={link.href}
              className={`relative px-4 py-2 text-sm font-medium transition-colors group ${
                activeSection === link.id
                  ? "text-foreground"
                  : "text-muted-foreground hover:text-foreground"
              }`}
            >
              {link.label}
              <span
                className={`absolute bottom-0 left-1/2 -translate-x-1/2 h-0.5 bg-accent rounded-full transition-all duration-300 ${
                  activeSection === link.id ? "w-6" : "w-0 group-hover:w-6"
                }`}
              />
            </a>
          ))}
          <div className="ml-4 pl-4 border-l border-border/50 flex items-center gap-2">
            {/* Language Switcher */}
            <div className="flex items-center gap-1 bg-muted/50 p-1 rounded-xl border border-border/50">
              <button
                disabled={isPending}
                onClick={() => switchLocale("id")}
                className={`px-2 py-1 text-xs font-bold rounded-lg transition-colors ${
                  locale === "id"
                    ? "bg-background shadow-sm text-foreground"
                    : "text-muted-foreground hover:text-foreground"
                }`}
              >
                ID
              </button>
              <button
                disabled={isPending}
                onClick={() => switchLocale("en")}
                className={`px-2 py-1 text-xs font-bold rounded-lg transition-colors ${
                  locale === "en"
                    ? "bg-background shadow-sm text-foreground"
                    : "text-muted-foreground hover:text-foreground"
                }`}
              >
                EN
              </button>
            </div>

            <ThemeToggle />
          </div>
        </div>

        {/* Mobile Menu Button */}
        <div className="flex md:hidden items-center gap-2">
          <ThemeToggle />
          <button
            onClick={() => setIsOpen(!isOpen)}
            className="p-2.5 rounded-xl bg-muted/50 border border-border/50"
            aria-label="Toggle menu"
          >
            {isOpen ? <X size={18} /> : <Menu size={18} />}
          </button>
        </div>
      </nav>

      {/* Mobile Nav */}
      <AnimatePresence>
        {isOpen && (
          <motion.div
            initial={{ opacity: 0, height: 0 }}
            animate={{ opacity: 1, height: "auto" }}
            exit={{ opacity: 0, height: 0 }}
            className="md:hidden glass border-t border-border/50 overflow-hidden"
          >
            <div className="px-6 py-4 flex flex-col gap-1">
              {navLinks.map((link) => (
                <a
                  key={link.href}
                  href={link.href}
                  onClick={() => setIsOpen(false)}
                  className={`px-4 py-3 text-sm font-medium rounded-lg transition-colors ${
                    activeSection === link.id
                      ? "text-accent bg-accent/5"
                      : "text-muted-foreground hover:text-foreground hover:bg-muted/50"
                  }`}
                >
                  {link.label}
                </a>
              ))}
              <div className="px-4 py-3 mt-2 border-t border-border/30 flex items-center gap-4">
                <span className="text-sm font-medium flex items-center gap-2 text-muted-foreground">
                  <Languages size={16} /> Language
                </span>
                <div className="flex items-center gap-2">
                  <button
                    onClick={() => switchLocale("id")}
                    className={`px-3 py-1 text-xs font-bold rounded-lg border ${
                      locale === "id"
                        ? "bg-accent/10 border-accent/20 text-accent"
                        : "bg-muted/50 border-border/50 text-muted-foreground"
                    }`}
                  >
                    ID
                  </button>
                  <button
                    onClick={() => switchLocale("en")}
                    className={`px-3 py-1 text-xs font-bold rounded-lg border ${
                      locale === "en"
                        ? "bg-accent/10 border-accent/20 text-accent"
                        : "bg-muted/50 border-border/50 text-muted-foreground"
                    }`}
                  >
                    EN
                  </button>
                </div>
              </div>
            </div>
          </motion.div>
        )}
      </AnimatePresence>
    </motion.header>
  );
}
