'use client';

import Link from 'next/link';
import { useState, useEffect, useRef } from 'react';
import { useCartStore, useWishlistStore, useAuthStore } from '@/lib/store';
import type { Product } from '@/lib/types';

export default function Navbar() {
  const [mobileOpen, setMobileOpen] = useState(false);
  const [searchQuery, setSearchQuery] = useState('');
  const [searchResults, setSearchResults] = useState<Product[]>([]);
  const [showDropdown, setShowDropdown] = useState(false);
  const searchRef = useRef<HTMLDivElement>(null);
  const cartCount = useCartStore(s => s.getCount());
  const wishlistCount = useWishlistStore(s => s.getCount());
  const user = useAuthStore(s => s.user);

  // Close search dropdown on outside click
  useEffect(() => {
    function handleClick(e: MouseEvent) {
      if (searchRef.current && !searchRef.current.contains(e.target as Node)) {
        setShowDropdown(false);
      }
    }
    document.addEventListener('click', handleClick);
    return () => document.removeEventListener('click', handleClick);
  }, []);

  async function handleSearch(q: string) {
    setSearchQuery(q);
    if (q.trim().length < 2) { setShowDropdown(false); return; }
    try {
      const res = await fetch(`/api/products/search?q=${encodeURIComponent(q)}`);
      const data = await res.json();
      if (data.data?.length) {
        setSearchResults(data.data.slice(0, 5));
        setShowDropdown(true);
      } else {
        setShowDropdown(false);
      }
    } catch {
      setShowDropdown(false);
    }
  }

  return (
    <>
      <header className="sticky top-0 z-50 navbar-gradient shadow-xl">
        {/* Top Bar */}
        <div className="bg-primary-dark bg-opacity-60 border-b border-white border-opacity-10">
          <div className="max-w-7xl mx-auto px-4 py-1.5 flex justify-between items-center text-xs text-blue-100">
            <div className="flex items-center gap-4">
              <span>📦 Free shipping on orders over $49</span>
              <span className="hidden md:inline">|</span>
              <span className="hidden md:inline">🔒 Secure Shopping Guaranteed</span>
            </div>
            <div className="flex items-center gap-3">
              <Link href="/account/orders" className="hover:text-white transition-colors">Track Order</Link>
              <span>|</span>
              {user ? (
                <Link href="/account" className="hover:text-white transition-colors">Hi, {user.first_name}</Link>
              ) : (
                <Link href="/login" className="hover:text-white transition-colors">Sign In</Link>
              )}
            </div>
          </div>
        </div>

        {/* Main Nav */}
        <div className="max-w-7xl mx-auto px-4 py-3">
          <div className="flex items-center gap-3">
            {/* Hamburger (Mobile) */}
            <button onClick={() => setMobileOpen(true)} className="md:hidden text-white p-2 rounded-lg hover:bg-white hover:bg-opacity-10 shrink-0">
              <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 6h16M4 12h16M4 18h16"/></svg>
            </button>

            {/* Logo */}
            <Link href="/" className="flex items-center gap-2 shrink-0">
              <img src="/images/logo.png" alt="SceneKey Store" className="w-9 h-9 object-contain rounded-xl shadow-lg bg-accent/10" />
              <div className="hidden sm:block">
                <span className="text-white font-black text-xl tracking-tight leading-none block">SceneKey</span>
                <span className="text-accent text-xs font-semibold tracking-widest">STORE</span>
              </div>
              <span className="text-white font-black text-xl tracking-tight sm:hidden">SceneKey</span>
            </Link>

            {/* Search Bar — desktop only */}
            <div className="hidden md:flex flex-1 min-w-0 mx-2" ref={searchRef}>
              <div className="relative w-full flex items-center bg-white rounded-xl shadow-inner overflow-hidden">
                <input
                  type="text"
                  placeholder="Search products, brands, categories..."
                  className="flex-1 min-w-0 pl-4 pr-2 py-2.5 text-sm text-gray-800 bg-white focus:outline-none"
                  autoComplete="off"
                  value={searchQuery}
                  onChange={e => handleSearch(e.target.value)}
                />
                <Link href={`/category?q=${encodeURIComponent(searchQuery)}`} className="shrink-0 bg-accent hover:bg-yellow-400 text-primary font-bold px-4 py-2.5 transition-colors flex items-center gap-1.5">
                  <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"/></svg>
                  <span className="hidden lg:inline text-sm font-semibold">Search</span>
                </Link>
                {showDropdown && searchResults.length > 0 && (
                  <div className="absolute top-full left-0 right-0 mt-1 bg-white rounded-xl shadow-2xl border border-gray-100 overflow-hidden z-50">
                    {searchResults.map(p => (
                      <Link key={p.id} href={`/products/${p.id}`} onClick={() => setShowDropdown(false)}
                        className="flex items-center gap-3 px-4 py-3 hover:bg-gray-50 transition-colors">
                        <img src={p.image_url} alt={p.name} className="w-10 h-10 object-cover rounded-lg" />
                        <div>
                          <div className="text-sm font-medium text-gray-800 line-clamp-1">{p.name}</div>
                          <div className="text-xs text-blue-700 font-semibold">${p.price}</div>
                        </div>
                      </Link>
                    ))}
                  </div>
                )}
              </div>
            </div>

            {/* Nav Icons */}
            <div className="flex items-center gap-1 shrink-0 ml-auto md:ml-0">
              <Link href="/wishlist" className="relative p-2.5 text-white hover:bg-white hover:bg-opacity-10 rounded-xl transition-colors group">
                <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4.318 6.318a4.5 4.5 0 000 6.364L12 20.364l7.682-7.682a4.5 4.5 0 00-6.364-6.364L12 7.636l-1.318-1.318a4.5 4.5 0 00-6.364 0z"/></svg>
                {wishlistCount > 0 && <span className="absolute -top-1 -right-1 w-5 h-5 bg-red-500 rounded-full text-xs flex items-center justify-center font-bold text-white">{wishlistCount}</span>}
                <span className="hidden md:block text-xs text-blue-100 group-hover:text-white text-center -mt-0.5">Wishlist</span>
              </Link>
              <Link href="/account" className="relative p-2.5 text-white hover:bg-white hover:bg-opacity-10 rounded-xl transition-colors group hidden md:block">
                <svg className="w-6 h-6 mx-auto" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z"/></svg>
                <span className="hidden md:block text-xs text-blue-100 group-hover:text-white text-center -mt-0.5">Account</span>
              </Link>
              <Link href="/cart" className="relative p-2.5 text-white hover:bg-white hover:bg-opacity-10 rounded-xl transition-colors group">
                <svg className="w-6 h-6 mx-auto" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 3h2l.4 2M7 13h10l4-8H5.4M7 13L5.4 5M7 13l-2.293 2.293c-.63.63-.184 1.707.707 1.707H17m0 0a2 2 0 100 4 2 2 0 000-4zm-8 2a2 2 0 11-4 0 2 2 0 014 0z"/></svg>
                {cartCount > 0 && <span className="absolute -top-1 -right-1 w-5 h-5 bg-accent text-primary rounded-full text-xs flex items-center justify-center font-black">{cartCount}</span>}
                <span className="hidden md:block text-xs text-blue-100 group-hover:text-white text-center -mt-0.5">Cart</span>
              </Link>
            </div>
          </div>
        </div>

        {/* Mobile Search Row */}
        <div className="md:hidden border-t border-white border-opacity-10 px-4 py-2.5">
          <div className="flex items-center bg-white rounded-xl overflow-hidden shadow-inner">
            <input
              type="text"
              placeholder="Search products, brands..."
              className="flex-1 min-w-0 pl-4 pr-2 py-2.5 text-sm text-gray-800 bg-white focus:outline-none"
              autoComplete="off"
              value={searchQuery}
              onChange={e => handleSearch(e.target.value)}
            />
            <Link href={`/category?q=${encodeURIComponent(searchQuery)}`} className="shrink-0 bg-accent hover:bg-yellow-400 text-primary font-bold px-4 py-2.5 transition-colors">
              <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"/></svg>
            </Link>
          </div>
        </div>

        {/* Category Nav Bar (Desktop) */}
        <div className="bg-primary-dark bg-opacity-40 border-t border-white border-opacity-10 hidden md:block">
          <div className="max-w-7xl mx-auto px-4">
            <nav className="flex items-center gap-1 overflow-x-auto category-scroll py-1">
              <Link href="/category" className="text-white text-sm font-semibold px-4 py-2 rounded-lg hover:bg-white hover:bg-opacity-10 whitespace-nowrap transition-colors flex items-center gap-1.5">
                <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 6h16M4 10h16M4 14h16M4 18h16"/></svg>
                All Categories
              </Link>
              <Link href="/category/laptops" className="text-blue-100 text-sm px-4 py-2 rounded-lg hover:bg-white hover:bg-opacity-10 whitespace-nowrap transition-colors">💻 Laptops</Link>
              <Link href="/category/phones" className="text-blue-100 text-sm px-4 py-2 rounded-lg hover:bg-white hover:bg-opacity-10 whitespace-nowrap transition-colors">📱 Smartphones</Link>
              <Link href="/category/tvs" className="text-blue-100 text-sm px-4 py-2 rounded-lg hover:bg-white hover:bg-opacity-10 whitespace-nowrap transition-colors">📺 TVs</Link>
              <Link href="/category/headphones" className="text-blue-100 text-sm px-4 py-2 rounded-lg hover:bg-white hover:bg-opacity-10 whitespace-nowrap transition-colors">🎧 Audio</Link>
              <Link href="/category/cameras" className="text-blue-100 text-sm px-4 py-2 rounded-lg hover:bg-white hover:bg-opacity-10 whitespace-nowrap transition-colors">📷 Cameras</Link>
              <Link href="/category/tablets" className="text-blue-100 text-sm px-4 py-2 rounded-lg hover:bg-white hover:bg-opacity-10 whitespace-nowrap transition-colors">🖥️ Tablets</Link>
              <Link href="/category/speakers" className="text-blue-100 text-sm px-4 py-2 rounded-lg hover:bg-white hover:bg-opacity-10 whitespace-nowrap transition-colors">🔊 Speakers</Link>
              <Link href="/category/smart-home" className="text-blue-100 text-sm px-4 py-2 rounded-lg hover:bg-white hover:bg-opacity-10 whitespace-nowrap transition-colors">🏠 Smart Home</Link>
              <Link href="/#deals" className="text-accent text-sm font-bold px-4 py-2 rounded-lg hover:bg-white hover:bg-opacity-10 whitespace-nowrap transition-colors flex items-center gap-1">
                🔥 Today&apos;s Deals
              </Link>
            </nav>
          </div>
        </div>
      </header>

      {/* Mobile Slide Menu */}
      {mobileOpen && <div className="fixed inset-0 bg-black bg-opacity-50 z-40 md:hidden" onClick={() => setMobileOpen(false)} />}
      <div className={`fixed top-0 left-0 h-full w-72 bg-white z-50 shadow-2xl transform transition-transform duration-300 md:hidden overflow-y-auto ${mobileOpen ? 'translate-x-0' : '-translate-x-full'}`}>
        <div className="navbar-gradient p-5 flex items-center justify-between">
          <div className="flex items-center gap-2">
            <img src="/images/logo.png" alt="SceneKey Store" className="w-8 h-8 object-contain rounded-lg bg-accent/10" />
            <span className="text-white font-black text-lg">SceneKey</span>
          </div>
          <button onClick={() => setMobileOpen(false)} className="text-white">
            <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12"/></svg>
          </button>
        </div>
        <nav className="p-4 space-y-1">
          <Link href="/" onClick={() => setMobileOpen(false)} className="flex items-center gap-3 px-4 py-3 rounded-xl bg-blue-50 text-primary font-semibold">
            <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 12l2-2m0 0l7-7 7 7M5 10v10a1 1 0 001 1h3m10-11l2 2m-2-2v10a1 1 0 01-1 1h-3m-6 0a1 1 0 001-1v-4a1 1 0 011-1h2a1 1 0 011 1v4a1 1 0 001 1m-6 0h6"/></svg>Home
          </Link>
          <Link href="/category" onClick={() => setMobileOpen(false)} className="flex items-center gap-3 px-4 py-3 rounded-xl text-gray-700 hover:bg-gray-50 font-medium">
            <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10"/></svg>Categories
          </Link>
          <Link href="/cart" onClick={() => setMobileOpen(false)} className="flex items-center gap-3 px-4 py-3 rounded-xl text-gray-700 hover:bg-gray-50 font-medium">
            <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 3h2l.4 2M7 13h10l4-8H5.4M7 13L5.4 5M7 13l-2.293 2.293c-.63.63-.184 1.707.707 1.707H17m0 0a2 2 0 100 4 2 2 0 000-4zm-8 2a2 2 0 11-4 0 2 2 0 014 0z"/></svg>Cart
          </Link>
          <Link href="/wishlist" onClick={() => setMobileOpen(false)} className="flex items-center gap-3 px-4 py-3 rounded-xl text-gray-700 hover:bg-gray-50 font-medium">
            <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4.318 6.318a4.5 4.5 0 000 6.364L12 20.364l7.682-7.682a4.5 4.5 0 00-6.364-6.364L12 7.636l-1.318-1.318a4.5 4.5 0 00-6.364 0z"/></svg>Wishlist
          </Link>
          <Link href="/account/orders" onClick={() => setMobileOpen(false)} className="flex items-center gap-3 px-4 py-3 rounded-xl text-gray-700 hover:bg-gray-50 font-medium">
            <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"/></svg>Orders
          </Link>
          <Link href="/account" onClick={() => setMobileOpen(false)} className="flex items-center gap-3 px-4 py-3 rounded-xl text-gray-700 hover:bg-gray-50 font-medium">
            <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z"/></svg>Account
          </Link>
          <hr className="my-2" />
          {user ? (
            <div className="px-4 py-3 text-sm text-gray-500">Signed in as {user.email}</div>
          ) : (
            <Link href="/login" onClick={() => setMobileOpen(false)} className="flex items-center justify-center gap-2 px-4 py-3 rounded-xl bg-primary text-white font-bold">Sign In / Register</Link>
          )}
        </nav>
      </div>
    </>
  );
}
