"use client";
import Link from "next/link";
import { usePathname } from "next/navigation";
import { useState, useEffect } from "react";
import { useTheme } from "next-themes";
import Image from "next/image";
import { User, MessageCircle } from "lucide-react";
import logo from "../assets/logo-main.png";
import "../styles/components/Navbar.css";
import { useAuth } from "../context/AuthContext";
import NavbarSearch from "./NavbarSearch";


export default function Navbar() {
  const pathname = usePathname();
  const { isAuthenticated } = useAuth();
  const [isMounted, setIsMounted] = useState(false);

  useEffect(() => {
    setIsMounted(true);
  }, []);

  return (
    <nav className="navbar">
      <div className="navbar-container">
        {/* Left: Navigation links + Hamburger + Mobile Search */}
        <div className="nav-left">
          <button
            className="hamburger-persistent"
            aria-label="Menu"
            id="hamburger-trigger"
          >
            <span></span>
            <span></span>
            <span></span>
          </button>

          {/* Mobile Search (Visible < 1400px) */}
          <div className="mobile-search-container xl:hidden flex items-center">
            <NavbarSearch variant="mobile" />
          </div>

          <ul className="nav-links desktop-links">
            <li className={pathname === "/" ? "current-menu-item" : ""}>
              <Link href="/" prefetch={true}>HEM</Link>
            </li>
            <li className={pathname === "/products" ? "current-menu-item" : ""}>
              <Link href="/products" prefetch={true}>PRODUKTER</Link>
            </li>
            <li className={pathname === "/salja-mobler" ? "current-menu-item" : ""}>
              <Link href="/salja-mobler" prefetch={true}>SÄLJA MÖBLER</Link>
            </li>
            <li className={pathname === "/om-oss" ? "current-menu-item" : ""}>
              <Link href="/om-oss" prefetch={true}>OM OSS</Link>
            </li>
            <li className={pathname === "/kontakta-oss" ? "current-menu-item" : ""}>
              <Link href="/kontakta-oss" prefetch={true}>KONTAKTA OSS</Link>
            </li>
          </ul>
        </div>

        {/* Center: Logo Only */}
        <div className="nav-center">
          <Link href="/" className="logo-link">
            <Image
              src={logo}
              alt="Logo"
              width={80}
              height={80}
              className="logo"
              priority
            />
          </Link>
        </div>

        {/* Right side: profile + theme toggle */}
        <NavbarClientExtras isAuthenticated={isAuthenticated} isMounted={isMounted} />
      </div>
    </nav>
  );
}

function NavbarClientExtras({ isAuthenticated, isMounted }: { isAuthenticated: boolean; isMounted: boolean }) {
  const [isOpen, setIsOpen] = useState(false);
  const [unreadCount, setUnreadCount] = useState(0);
  const { theme, setTheme, resolvedTheme } = useTheme();
  const [showThemeToggle, setShowThemeToggle] = useState(true);

  // Determine profile destination safely to avoid hydration mismatch
  const profileHref = isMounted && isAuthenticated ? "/me" : "/login";

  useEffect(() => {
    const checkConsent = () => {
      const saved = localStorage.getItem("cookie_consent");
      if (saved) {
        try {
          const parsed = JSON.parse(saved);
          if (parsed.functional === false) {
            setShowThemeToggle(false);
            return;
          }
        } catch (e) {
          console.error("Failed to parse cookie consent", e);
        }
      }
      setShowThemeToggle(true);
    };

    checkConsent();
    window.addEventListener("cookie-consent-updated", checkConsent);
    return () => window.removeEventListener("cookie-consent-updated", checkConsent);
  }, []);

  useEffect(() => {
    if (theme && typeof window !== "undefined") {
      document.cookie = `theme=${theme}; path=/; max-age=31536000`; // 1-year expiry
    }
    const handleResize = () => {
      // Close menu if resized to desktop layout
      if (window.innerWidth >= 1400) setIsOpen(false);
    };
    window.addEventListener("resize", handleResize);
    handleResize();
    return () => window.removeEventListener("resize", handleResize);
  }, [theme]);

  // Fetch unread message count
  useEffect(() => {
    if (!isMounted || !isAuthenticated) return;

    const fetchUnread = async () => {
      try {
        const token = localStorage.getItem('token') || sessionStorage.getItem('token');
        const res = await fetch('/api/conversations/unread', {
          headers: { 'Authorization': `Bearer ${token}` }
        });
        if (res.ok) {
          const data = await res.json();
          setUnreadCount(data.count);
        }
      } catch (err) {
        console.error(err);
      }
    };

    fetchUnread();
    // Poll every 30 seconds
    const interval = setInterval(fetchUnread, 30000);
    return () => clearInterval(interval);
  }, [isMounted, isAuthenticated]);

  useEffect(() => {
    const handleTrigger = () => {
      setIsOpen(prev => !prev);
    };

    const trigger = document.getElementById('hamburger-trigger');
    if (trigger) {
      trigger.addEventListener('click', handleTrigger);
      if (isOpen) {
        trigger.classList.add('open');
      } else {
        trigger.classList.remove('open');
      }
    }

    return () => {
      if (trigger) trigger.removeEventListener('click', handleTrigger);
    };
  }, [isOpen]);

  const toggleMenu = () => setIsOpen(!isOpen);
  const isDarkMode = resolvedTheme === "dark";

  return (
    <>
      <div className="nav-right">
        {/* Desktop Search Bar (Hidden on mobile < 1400px) */}
        <div className="hidden xl:block mr-4">
          <NavbarSearch variant="desktop" />
        </div>

        {/* Profile Icon */}
        <div className="profile-icon-container">
          <Link href={profileHref} prefetch={true} aria-label="Profile">
            <User size={28} className="nav-icon" />
          </Link>
        </div>

        {/* Theme toggle (Always visible) */}
        {showThemeToggle && (
          <div className="theme-toggle flex">
            <label className="flex items-center cursor-pointer">
              <div className="relative">
                <input
                  type="checkbox"
                  className="sr-only"
                  id="theme-switch-desktop"
                  checked={isDarkMode}
                  onChange={() => setTheme(theme === "dark" ? "light" : "dark")}
                  suppressHydrationWarning
                />
                <div className={`w-14 h-7 ${isMounted && isDarkMode ? 'bg-blue-600' : 'bg-gray-400'} rounded-full transition-colors duration-300`}></div>
                <div className={`absolute left-1 top-1 bg-white w-5 h-5 rounded-full flex items-center justify-center transition-transform duration-300 ${isMounted && isDarkMode ? 'transform translate-x-7' : ''}`}>
                  <span className="text-xs" suppressHydrationWarning>
                    {isMounted && isDarkMode ? "🌙" : "☀️"}
                  </span>
                </div>
              </div>
            </label>
          </div>
        )}
      </div>

      {/* Mobile menu overlay */}
      {isMounted && (
        <div
          className={`mobile-overlay ${isOpen ? "active" : ""}`}
          onClick={() => setIsOpen(false)}
        ></div>
      )}

      {/* Mobile menu sidebar */}
      {isMounted && (
        <div className={`mobile-menu ${isOpen ? "active" : ""}`}>
          <div className="mobile-menu-content">
            <ul className="mb-8">
              <li><Link href="/" onClick={toggleMenu} prefetch={true}>HEM</Link></li>
              <li><Link href="/products" onClick={toggleMenu} prefetch={true}>PRODUKTER</Link></li>
              <li><Link href="/salja-mobler" onClick={toggleMenu} prefetch={true}>SÄLJA MÖBLER</Link></li>
              <li><Link href="/om-oss" onClick={toggleMenu} prefetch={true}>OM OSS</Link></li>
              <li><Link href="/kontakta-oss" onClick={toggleMenu} prefetch={true}>KONTAKTA OSS</Link></li>
            </ul>

            <div className="border-t border-[var(--border-color)] pt-6 space-y-6">

              {/* Search in Menu (for small screens or redundancy) */}
              {/* Actually user said "under it add search bar, Log In..." */}
              <div className="w-full">
                <NavbarSearch variant="desktop" /> {/* Full width variant essentially */}
              </div>

              <div className="flex flex-col gap-4">
                {isAuthenticated ? (
                  <>
                    <Link href="/me" onClick={toggleMenu} className="flex items-center gap-3 text-[var(--nav-text)] font-semibold uppercase tracking-wider">
                      <User size={20} /> Min Profil
                    </Link>
                    <Link href="/messages" onClick={toggleMenu} className="flex items-center gap-3 text-[var(--nav-text)] font-semibold uppercase tracking-wider">
                      <MessageCircle size={20} /> Meddelanden
                      {unreadCount > 0 && <span className="text-red-500">({unreadCount})</span>}
                    </Link>
                  </>
                ) : (
                  <Link href="/login" onClick={toggleMenu} className="flex items-center gap-3 text-[var(--nav-text)] font-semibold uppercase tracking-wider">
                    <User size={20} /> Logga in
                  </Link>
                )}
              </div>

              {/* Mobile Theme Toggle */}
              {showThemeToggle && (
                <div className="flex items-center justify-between">
                  <span className="text-[var(--nav-text)] font-semibold uppercase tracking-wider">Tema</span>
                  <div className="theme-toggle">
                    <label className="flex items-center cursor-pointer">
                      <div className="relative">
                        <input
                          type="checkbox"
                          className="sr-only"
                          id="theme-switch-mobile"
                          checked={isDarkMode}
                          onChange={() => setTheme(theme === "dark" ? "light" : "dark")}
                          suppressHydrationWarning
                        />
                        <div className={`w-14 h-7 ${isMounted && isDarkMode ? 'bg-blue-600' : 'bg-gray-400'} rounded-full transition-colors duration-300`}></div>
                        <div className={`absolute left-1 top-1 bg-white w-5 h-5 rounded-full flex items-center justify-center transition-transform duration-300 ${isMounted && isDarkMode ? 'transform translate-x-7' : ''}`}>
                          <span className="text-xs" suppressHydrationWarning>
                            {isMounted && isDarkMode ? "🌙" : "☀️"}
                          </span>
                        </div>
                      </div>
                    </label>
                  </div>
                </div>
              )}
            </div>
          </div>
        </div>
      )}
      <FloatingChatButton isMounted={isMounted} isAuthenticated={isAuthenticated} unreadCount={unreadCount} />
    </>
  );
}

function FloatingChatButton({ isMounted, isAuthenticated, unreadCount }: { isMounted: boolean; isAuthenticated: boolean; unreadCount: number }) {
  if (!isMounted || !isAuthenticated) return null;

  return (
    <Link
      href="/messages"
      className="fixed bottom-6 right-6 z-[3000] bg-blue-600 hover:bg-blue-700 text-white p-4 rounded-full shadow-2xl transition-all hover:scale-110 active:scale-95 flex items-center justify-center group"
      aria-label="Meddelanden"
    >
      <MessageCircle size={30} />
      {unreadCount > 0 && (
        <span className="absolute -top-1 -right-1 bg-red-500 text-white text-[12px] font-bold w-6 h-6 rounded-full flex items-center justify-center border-2 border-white">
          {unreadCount > 9 ? '9+' : unreadCount}
        </span>
      )}
    </Link>
  );
}
