"use client";

import { useState, useEffect } from 'react';
import Link from 'next/link';
import { useRouter } from 'next/navigation';

export default function Navbar() {
  const [isOpen, setIsOpen] = useState(false);
  const [isLogged, setIsLogged] = useState(false);
  const [showLogoutConfirm, setShowLogoutConfirm] = useState(false);
  const router = useRouter();

  useEffect(() => {
    const checkAuth = () => {
      const uid = localStorage.getItem('vgproducts_uid') || sessionStorage.getItem('USERID');
      setIsLogged(!!uid);
    };
    checkAuth();
    // Check periodically or handle logout event
    window.addEventListener('storage', checkAuth);
    return () => window.removeEventListener('storage', checkAuth);
  }, []);

  const handleLogoutClick = () => {
    setShowLogoutConfirm(true);
  };

  const performLogout = () => {
    localStorage.removeItem('vgproducts_uid');
    localStorage.removeItem('d4a_email');
    sessionStorage.removeItem('USERID');
    setIsLogged(false);
    setIsOpen(false);
    setShowLogoutConfirm(false);
    router.push('/');
    // trigger state update for other components
    window.dispatchEvent(new Event('storage'));
  };

  const toggleMenu = () => setIsOpen(!isOpen);

  return (
    <nav className={isOpen ? "nav-active" : ""}>
      <Link href="/" className="nav-logo">
        <img src="/assets/vg-fence.png" alt="VG Fence Products" style={{ height: '40px', width: 'auto' }} />
      </Link>

      {/* Hamburger Menu Toggle */}
      <button className="menu-toggle" onClick={toggleMenu} aria-label="Toggle Menu">
        <div className={isOpen ? "hamburger active" : "hamburger"}>
          <span></span>
          <span></span>
          <span></span>
        </div>
      </button>

      <ul className={isOpen ? "nav-links active" : "nav-links"}>
        <li><Link href="/" onClick={() => setIsOpen(false)}>Home</Link></li>
        <li><Link href="/about" onClick={() => setIsOpen(false)}>About</Link></li>
        <li><Link href="/products" onClick={() => setIsOpen(false)}>Products</Link></li>
        <li><Link href="/manufacturing" onClick={() => setIsOpen(false)}>Manufacturing</Link></li>
        <li><Link href="/rentals" onClick={() => setIsOpen(false)}>Rentals</Link></li>
        <li><Link href="/blog" onClick={() => setIsOpen(false)}>Blog</Link></li>
        <li><Link href="/contact" onClick={() => setIsOpen(false)}>Contact</Link></li>
        <li className="mobile-cta-li">
          {isLogged ? (
            <button onClick={handleLogoutClick} className="nav-cta" style={{ width: '100%', justifyContent: 'center', appearance: 'none', border: 'none', cursor: 'pointer' }}>
              Logout
            </button>
          ) : (
            <Link href="/login" className="nav-cta" onClick={() => setIsOpen(false)} style={{ width: '100%', justifyContent: 'center' }}>
              Login
            </Link>
          )}
        </li>
      </ul>

      {isLogged ? (
        <button onClick={handleLogoutClick} className="nav-cta desktop-cta" style={{ appearance: 'none', border: 'none', cursor: 'pointer' }}>
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"/><polyline points="16 17 21 12 16 7"/><line x1="21" y1="12" x2="9" y2="12"/></svg>
          Logout
        </button>
      ) : (
        <Link href="/login" className="nav-cta desktop-cta">
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/></svg>
          Login
        </Link>
      )}

      {/* Logout Confirmation Modal */}
      {showLogoutConfirm && (
        <div style={{
          position: 'fixed',
          top: 0, left: 0, right: 0, bottom: 0,
          backgroundColor: 'rgba(0,10,30,0.7)',
          display: 'flex',
          justifyContent: 'center',
          alignItems: 'center',
          zIndex: 99999,
          backdropFilter: 'blur(4px)'
        }}>
          <div style={{
            background: '#ffffff',
            padding: '32px',
            borderRadius: '12px',
            width: '90%',
            maxWidth: '400px',
            boxShadow: '0 25px 50px -12px rgba(0, 0, 0, 0.25)',
            textAlign: 'center'
          }}>
            <h3 style={{ fontSize: '24px', fontWeight: 800, color: 'var(--navy)', marginBottom: '12px', fontFamily: 'var(--font-display)' }}>Confirm Logout</h3>
            <p style={{ color: 'var(--gray-600)', marginBottom: '32px', fontSize: '15px', lineHeight: 1.5 }}>
              Are you sure you want to log out of your account?
            </p>
            <div style={{ display: 'flex', gap: '16px', justifyContent: 'center' }}>
              <button 
                onClick={() => setShowLogoutConfirm(false)}
                className="btn-secondary"
                style={{ flex: 1, padding: '12px', border: '1px solid var(--gray-300)', color: 'var(--gray-700)', borderRadius: '6px', fontWeight: 600, cursor: 'pointer' }}
              >
                Cancel
              </button>
              <button 
                onClick={performLogout}
                className="btn-primary"
                style={{ flex: 1, padding: '12px', background: 'var(--orange)', color: '#fff', border: 'none', borderRadius: '6px', fontWeight: 600, cursor: 'pointer' }}
              >
                Logout
              </button>
            </div>
          </div>
        </div>
      )}
    </nav>
  );
}
