"use client";

import React, { useState, useEffect } from "react";
import { usePathname, useRouter } from "next/navigation";
import Image from "next/image";
import { Menu, X, MessageCircle, Image as ImageIcon, Sun, Moon, Globe } from "lucide-react";
import { useTheme } from "next-themes";
import { useTranslations } from "next-intl";
import IntentLink from "@/components/IntentLink";

interface NavbarProps {
  logoUrl?: string;
  locale: string;
}

const navLinks: Record<string, { name: string; href: string }[]> = {
  tr: [
    { name: "Ocaklar", href: "/products?category=hobs" },
    { name: "Serilerimiz", href: "/collections" },
    { name: "Hakkımızda", href: "#about" },
    { name: "Sertifikalarımız", href: "#certificates" },
    { name: "Katalog", href: "#catalog-download" },
    { name: "İletişim", href: "#contact" },
  ],
  en: [
    { name: "Hobs", href: "/products?category=hobs" },
    { name: "Collections", href: "/collections" },
    { name: "About", href: "#about" },
    { name: "Certificates", href: "#certificates" },
    { name: "Catalog", href: "#catalog-download" },
    { name: "Contact", href: "#contact" },
  ],
  ru: [
    { name: "Варочные панели", href: "/products?category=hobs" },
    { name: "Коллекции", href: "/collections" },
    { name: "О нас", href: "#about" },
    { name: "Сертификаты", href: "#certificates" },
    { name: "Каталог", href: "#catalog-download" },
    { name: "Контакты", href: "#contact" },
  ],
};

const ctaLabels: Record<string, string> = {
  tr: "Bize Ulaş",
  en: "Contact Us",
  ru: "Связаться",
};

const localeLabels: Record<string, string> = {
  tr: "TR",
  en: "EN",
  ru: "RU",
};

export default function Navbar({ logoUrl = "/brand/norden.png", locale }: NavbarProps) {
  const t = useTranslations();
  const [mobileMenuOpen, setMobileMenuOpen] = useState(false);
  const [scrolled, setScrolled] = useState(false);
  const [logoError, setLogoError] = useState(false);
  const [showLangMenu, setShowLangMenu] = useState(false);
  const { setTheme, resolvedTheme } = useTheme();
  const pathname = usePathname();
  const router = useRouter();

  useEffect(() => {
    document.documentElement.lang = locale;
  }, [locale]);

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

  useEffect(() => {
    if (!mobileMenuOpen) return;
    const closeOnEscape = (event: KeyboardEvent) => {
      if (event.key === "Escape") setMobileMenuOpen(false);
    };
    window.addEventListener("keydown", closeOnEscape);
    return () => window.removeEventListener("keydown", closeOnEscape);
  }, [mobileMenuOpen]);

  const links = navLinks[locale] || navLinks["tr"];
  const ctaLabel = ctaLabels[locale] || ctaLabels["tr"];
  const whatsappUrl = `https://wa.me/905394671328?text=${encodeURIComponent(t("catalog.whatsapp_general"))}`;

  const switchLocale = (newLocale: string) => {
    // Replace the locale prefix in the current pathname
    const segments = pathname.split("/");
    if (["tr", "en", "ru"].includes(segments[1])) {
      segments[1] = newLocale;
    } else {
      segments.splice(1, 0, newLocale);
    }
    const newPath = segments.join("/") || `/${newLocale}`;
    const query = window.location.search;
    const hash = window.location.hash;
    router.replace(`${newPath}${query}${hash}`);
    setShowLangMenu(false);
  };

  const renderLogo = () => {
    if (logoError || !logoUrl) {
      return (
        <div className="flex items-center gap-2" style={{ color: "var(--fg-muted)" }}>
          <ImageIcon size={18} style={{ color: "var(--ember)" }} />
          <span className="font-serif text-lg tracking-wide" style={{ color: "var(--fg-primary)" }}>Norden</span>
        </div>
      );
    }
    return (
      <div className="relative h-9 w-[150px] flex items-center">
        <Image
          src="/brand/nordenwhite.png"
          alt="Norden Logo"
          width={900}
          height={190}
          className="theme-logo-dark h-auto w-[150px] object-contain object-left"
          onError={() => setLogoError(true)}
          fetchPriority="high"
        />
        <Image
          src={logoUrl}
          alt="Norden Logo"
          width={385}
          height={88}
          className="theme-logo-light h-auto w-[150px] object-contain object-left"
          onError={() => setLogoError(true)}
          fetchPriority="high"
        />
      </div>
    );
  };

  return (
    <>
      <nav className="norden-nav-enter fixed top-4 left-0 right-0 z-50 px-4">
        <div
          className={`mx-auto max-w-7xl w-full rounded-full transition-all duration-300 ${
            scrolled ? "liquid-glass shadow-lg" : "bg-transparent border border-transparent"
          }`}
          style={{ boxShadow: scrolled ? "0 8px 32px rgba(0,0,0,0.3)" : undefined }}
        >
          {/* Desktop 3-Column Grid */}
          <div className="hidden lg:grid grid-cols-[auto_1fr_auto] items-center w-full px-6 py-3">
            {/* Left: Logo */}
            <div className="flex justify-start">
              <IntentLink href={`/${locale}`} className="inline-flex min-h-11 items-center">
                {renderLogo()}
              </IntentLink>
            </div>

            {/* Center: Links */}
            <div className="flex justify-center gap-4 px-4">
              {links.map((link) => (
                <IntentLink
                  key={link.name}
                  href={`/${locale}${link.href.startsWith("/") ? link.href : link.href}`}
                  className="whitespace-nowrap font-sans text-xs font-light tracking-wide transition-colors duration-200"
                  style={{ color: "var(--fg-secondary)" }}
                  onMouseEnter={(e) => (e.currentTarget.style.color = "var(--ember)")}
                  onMouseLeave={(e) => (e.currentTarget.style.color = "var(--fg-secondary)")}
                >
                  {link.name}
                </IntentLink>
              ))}
            </div>

            {/* Right: Locale Switcher + Theme Toggle + CTA */}
            <div className="flex justify-end items-center gap-3">
              {/* Language Selector */}
              <div className="relative">
                <button
                  onClick={() => setShowLangMenu(!showLangMenu)}
                  className="flex min-h-11 items-center gap-1.5 rounded-full px-3 py-2 text-xs font-mono uppercase tracking-widest transition-all duration-200"
                  style={{ color: "var(--fg-secondary)", border: "1px solid var(--border)" }}
                  aria-label={t("catalog.change_language")}
                  aria-expanded={showLangMenu}
                  aria-haspopup="menu"
                >
                  <Globe size={12} />
                  {localeLabels[locale]}
                </button>
                {showLangMenu && (
                    <div
                      className="norden-popover-enter absolute top-full right-0 mt-2 liquid-glass rounded-xl overflow-hidden min-w-[80px] shadow-xl"
                      style={{ border: "1px solid var(--border)" }}
                    >
                      {(["tr", "en", "ru"] as const).map((loc) => (
                        <button
                          key={loc}
                          onClick={() => switchLocale(loc)}
                          className="w-full px-4 py-2.5 text-xs font-mono uppercase tracking-widest text-left transition-colors duration-150"
                          style={{
                            color: locale === loc ? "var(--ember)" : "var(--fg-secondary)",
                            background: locale === loc ? "rgba(196,147,90,0.08)" : "transparent",
                          }}
                        >
                          {localeLabels[loc]}
                        </button>
                      ))}
                    </div>
                )}
              </div>

              {/* Theme Toggle */}
              <button
                  onClick={() => setTheme(resolvedTheme === "dark" ? "light" : "dark")}
                  className="flex h-11 w-11 items-center justify-center rounded-full transition-all duration-300"
                  style={{
                    border: "1px solid var(--border)",
                    color: "var(--fg-secondary)",
                    background: "transparent",
                  }}
                  aria-label={t("catalog.toggle_theme")}
                >
                  <Sun className="theme-icon-sun" size={14} />
                  <Moon className="theme-icon-moon" size={14} />
                </button>

              {/* CTA */}
              <a
                href={whatsappUrl}
                target="_blank"
                rel="noopener noreferrer"
                className="glass-pill flex min-h-11 items-center gap-2 rounded-full px-5 py-2 font-sans text-xs font-medium uppercase tracking-widest transition-all hover:scale-[1.03] active:scale-[0.97]"
                style={{ color: "var(--ember)" }}
              >
                <MessageCircle size={13} />
                {ctaLabel}
              </a>
            </div>
          </div>

          {/* Mobile Row */}
          <div className="flex lg:hidden items-center justify-between w-full px-5 py-3">
            <IntentLink href={`/${locale}`} className="inline-flex min-h-11 items-center">{renderLogo()}</IntentLink>
            <div className="flex items-center gap-2">
              <button
                  onClick={() => setTheme(resolvedTheme === "dark" ? "light" : "dark")}
                  className="flex h-11 w-11 items-center justify-center rounded-full"
                  style={{ border: "1px solid var(--border)", color: "var(--fg-muted)" }}
                  aria-label={t("catalog.toggle_theme")}
                >
                  <Sun className="theme-icon-sun" size={13} />
                  <Moon className="theme-icon-moon" size={13} />
                </button>
              <button
                onClick={() => setMobileMenuOpen(!mobileMenuOpen)}
                className="flex h-11 w-11 items-center justify-center rounded-full transition-colors duration-200"
                style={{ color: "var(--fg-primary)" }}
                aria-label={t("catalog.toggle_menu")}
                aria-expanded={mobileMenuOpen}
                aria-controls="mobile-navigation-panel"
              >
                {mobileMenuOpen ? <X size={20} /> : <Menu size={20} />}
              </button>
            </div>
          </div>
        </div>
      </nav>

      {/* Mobile Menu Panel */}
      {mobileMenuOpen && (
          <div
            id="mobile-navigation-panel"
            className="norden-mobile-panel-enter fixed inset-0 z-40 backdrop-blur-md pt-24 px-6 flex flex-col lg:hidden overflow-y-auto"
            style={{ background: "rgba(17,17,19,0.97)" }}
          >
            <div className="flex flex-col gap-6 text-center">
              {links.map((link, idx) => (
                <div
                  className="norden-mobile-item-enter"
                  style={{ animationDelay: `${idx * 50}ms` }}
                  key={link.name}
                >
                  <IntentLink
                    href={`/${locale}${link.href.startsWith("/") ? link.href : link.href}`}
                    onClick={() => setMobileMenuOpen(false)}
                    className="font-serif text-2xl tracking-wide block py-2 transition-colors"
                    style={{ color: "var(--fg-primary)" }}
                    onMouseEnter={(e) => (e.currentTarget.style.color = "var(--ember)")}
                    onMouseLeave={(e) => (e.currentTarget.style.color = "var(--fg-primary)")}
                  >
                    {link.name}
                  </IntentLink>
                </div>
              ))}

              {/* Locale switcher in mobile */}
              <div className="flex justify-center gap-3 mt-4">
                {(["tr", "en", "ru"] as const).map((loc) => (
                  <button
                    key={loc}
                    onClick={() => { switchLocale(loc); setMobileMenuOpen(false); }}
                    className="min-h-11 rounded-full px-4 py-2 font-mono text-xs uppercase tracking-widest transition-all"
                    style={{
                      color: locale === loc ? "var(--ember)" : "var(--fg-muted)",
                      border: `1px solid ${locale === loc ? "var(--ember)" : "var(--border)"}`,
                      background: locale === loc ? "rgba(196,147,90,0.08)" : "transparent",
                    }}
                  >
                    {localeLabels[loc]}
                  </button>
                ))}
              </div>
            </div>

            <div className="mt-auto mb-10">
              <a
                href={whatsappUrl}
                target="_blank"
                rel="noopener noreferrer"
                onClick={() => setMobileMenuOpen(false)}
                className="w-full text-center glass-pill py-3.5 rounded-full font-sans text-sm uppercase tracking-widest font-medium flex items-center justify-center gap-2"
                style={{ color: "var(--ember)" }}
              >
                <MessageCircle size={16} />
                {ctaLabel}
              </a>
            </div>
          </div>
      )}
    </>
  );
}
