'use client';
import { useState } from 'react';
import { useWalletAuth } from '../lib/WalletAuthContext';
import WalletModal from './WalletModal';
import type { Page } from '../page';

const NAV_ITEMS: { id: Page; label: string }[] = [
  { id: 'home', label: 'Home' },
  { id: 'agent-hub', label: 'Agent Hub' },
  { id: 'vns', label: 'VNS' },
  { id: 'bonds', label: 'Bonds' },
  { id: 'trust', label: 'Trust' },
  { id: 'escrow', label: 'Escrow' },
  { id: 'bridge', label: 'Bridge' },
  { id: 'docs', label: 'Developers' },
];

const MORE_ITEMS: { id: Page; label: string }[] = [
  { id: 'discover', label: 'Discover' },
  { id: 'marketplace', label: 'Marketplace' },
  { id: 'register', label: 'Register' },
  { id: 'verify', label: 'Verify' },
  { id: 'vkp', label: 'VKP Keys' },
  { id: 'sdk', label: 'SDK' },
  { id: 'api', label: 'API' },
  { id: 'zk-proofs', label: 'ZK Proofs' },
];

const ALL_NAV_ITEMS = [...NAV_ITEMS, ...MORE_ITEMS];

const WALLET_NAMES: Record<string, string> = {
  coinbase: 'Coinbase',
  base: 'Base',
  metamask: 'MetaMask',
  walletconnect: 'WalletConnect',
};

export default function Nav({ activePage, onNavigate }: { activePage: Page; onNavigate: (p: Page) => void }) {
  const { isUnlocked, address, logout, connect, activeWallet, modalOpen, setModalOpen, connectWallet, connecting } = useWalletAuth();
  const [mobileOpen, setMobileOpen] = useState(false);
  const [walletMenuOpen, setWalletMenuOpen] = useState(false);
  const [moreOpen, setMoreOpen] = useState(false);
  const isMoreActive = MORE_ITEMS.some(item => item.id === activePage);

  const shortAddr = address ? `${address.slice(0, 6)}...${address.slice(-4)}` : '';
  const walletLabel = activeWallet ? WALLET_NAMES[activeWallet] : '';

  return (
    <>
      <nav style={{
        position: 'sticky',
        top: 0,
        zIndex: 100,
        backgroundColor: 'rgba(9,9,11,0.85)',
        backdropFilter: 'blur(20px)',
        WebkitBackdropFilter: 'blur(20px)',
        borderBottom: '1px solid rgba(255,255,255,0.06)',
      }}>
        <div style={{
          maxWidth: 1200,
          margin: '0 auto',
          padding: '0 24px',
          height: 64,
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'space-between',
        }}>
          {/* Logo */}
          <button
            onClick={() => onNavigate('home')}
            style={{
              display: 'flex',
              alignItems: 'center',
              gap: 10,
              background: 'none',
              border: 'none',
              cursor: 'pointer',
              padding: 0,
            }}
          >
            <div style={{
              width: 32,
              height: 32,
              borderRadius: 8,
              background: 'linear-gradient(135deg, #FF6B35, #E55A24)',
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
            }}>
              <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="white" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
                <path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z" />
              </svg>
            </div>
            <span style={{ fontSize: 18, fontWeight: 700, color: '#F4F4F5', letterSpacing: '-0.02em' }}>
              Vaultfire
            </span>
          </button>

          {/* Desktop nav */}
          <div style={{ display: 'flex', alignItems: 'center', gap: 4 }} className="desktop-nav">
            {NAV_ITEMS.map(item => (
              <button
                key={item.id}
                onClick={() => onNavigate(item.id)}
                style={{
                  padding: '8px 14px',
                  borderRadius: 8,
                  fontSize: 13,
                  fontWeight: 500,
                  border: 'none',
                  cursor: 'pointer',
                  transition: 'all 150ms',
                  backgroundColor: activePage === item.id ? 'rgba(255,107,53,0.12)' : 'transparent',
                  color: activePage === item.id ? '#FF6B35' : '#a1a1aa',
                }}
                onMouseEnter={e => {
                  if (activePage !== item.id) {
                    (e.target as HTMLElement).style.color = '#F4F4F5';
                    (e.target as HTMLElement).style.backgroundColor = 'rgba(255,255,255,0.05)';
                  }
                }}
                onMouseLeave={e => {
                  if (activePage !== item.id) {
                    (e.target as HTMLElement).style.color = '#a1a1aa';
                    (e.target as HTMLElement).style.backgroundColor = 'transparent';
                  }
                }}
              >
                {item.label}
              </button>
            ))}

            {/* More dropdown */}
            <div style={{ position: 'relative' }}>
              <button
                onClick={() => setMoreOpen(!moreOpen)}
                style={{
                  padding: '8px 14px',
                  borderRadius: 8,
                  fontSize: 13,
                  fontWeight: 500,
                  border: 'none',
                  cursor: 'pointer',
                  transition: 'all 150ms',
                  backgroundColor: isMoreActive ? 'rgba(255,107,53,0.12)' : moreOpen ? 'rgba(255,255,255,0.05)' : 'transparent',
                  color: isMoreActive ? '#FF6B35' : '#a1a1aa',
                  display: 'flex',
                  alignItems: 'center',
                  gap: 4,
                }}
                onMouseEnter={e => {
                  if (!isMoreActive) {
                    (e.currentTarget as HTMLElement).style.color = '#F4F4F5';
                    (e.currentTarget as HTMLElement).style.backgroundColor = 'rgba(255,255,255,0.05)';
                  }
                }}
                onMouseLeave={e => {
                  if (!isMoreActive && !moreOpen) {
                    (e.currentTarget as HTMLElement).style.color = '#a1a1aa';
                    (e.currentTarget as HTMLElement).style.backgroundColor = 'transparent';
                  }
                }}
              >
                More
                <svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"
                  style={{ transform: moreOpen ? 'rotate(180deg)' : 'rotate(0deg)', transition: 'transform 150ms' }}>
                  <polyline points="6 9 12 15 18 9" />
                </svg>
              </button>
              {moreOpen && (
                <>
                  <div style={{ position: 'fixed', inset: 0, zIndex: 149 }} onClick={() => setMoreOpen(false)} />
                  <div style={{
                    position: 'absolute',
                    top: '100%',
                    right: 0,
                    marginTop: 8,
                    backgroundColor: '#1A1A1E',
                    border: '1px solid rgba(255,255,255,0.08)',
                    borderRadius: 12,
                    padding: 6,
                    minWidth: 180,
                    boxShadow: '0 8px 32px rgba(0,0,0,0.5)',
                    zIndex: 150,
                  }}>
                    {MORE_ITEMS.map(item => (
                      <button
                        key={item.id}
                        onClick={() => { onNavigate(item.id); setMoreOpen(false); }}
                        style={{
                          display: 'block',
                          width: '100%',
                          padding: '10px 14px',
                          borderRadius: 8,
                          border: 'none',
                          textAlign: 'left',
                          fontSize: 13,
                          fontWeight: 500,
                          cursor: 'pointer',
                          transition: 'all 150ms',
                          backgroundColor: activePage === item.id ? 'rgba(255,107,53,0.12)' : 'transparent',
                          color: activePage === item.id ? '#FF6B35' : '#a1a1aa',
                        }}
                        onMouseEnter={e => {
                          if (activePage !== item.id) {
                            (e.target as HTMLElement).style.color = '#F4F4F5';
                            (e.target as HTMLElement).style.backgroundColor = 'rgba(255,255,255,0.05)';
                          }
                        }}
                        onMouseLeave={e => {
                          if (activePage !== item.id) {
                            (e.target as HTMLElement).style.color = '#a1a1aa';
                            (e.target as HTMLElement).style.backgroundColor = 'transparent';
                          }
                        }}
                      >
                        {item.label}
                      </button>
                    ))}
                  </div>
                </>
              )}
            </div>
          </div>

          {/* Right side: wallet + mobile menu */}
          <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
            {/* Wallet button */}
            {isUnlocked && address ? (
              <div style={{ position: 'relative' }}>
                <button
                  onClick={() => setWalletMenuOpen(!walletMenuOpen)}
                  style={{
                    display: 'flex',
                    alignItems: 'center',
                    gap: 8,
                    padding: '8px 14px',
                    borderRadius: 10,
                    border: '1px solid rgba(255,107,53,0.3)',
                    backgroundColor: 'rgba(255,107,53,0.08)',
                    color: '#FF8C5A',
                    fontSize: 13,
                    fontWeight: 600,
                    cursor: 'pointer',
                    transition: 'all 150ms',
                  }}
                >
                  <div style={{ width: 8, height: 8, borderRadius: '50%', backgroundColor: '#10b981' }} />
                  {shortAddr}
                </button>
                {walletMenuOpen && (
                  <div style={{
                    position: 'absolute',
                    top: '100%',
                    right: 0,
                    marginTop: 8,
                    backgroundColor: '#1A1A1E',
                    border: '1px solid rgba(255,255,255,0.08)',
                    borderRadius: 12,
                    padding: 8,
                    minWidth: 200,
                    boxShadow: '0 8px 32px rgba(0,0,0,0.5)',
                    zIndex: 200,
                  }}>
                    {walletLabel && (
                      <div style={{ padding: '6px 12px', fontSize: 12, color: '#a1a1aa', fontWeight: 500 }}>
                        Connected via {walletLabel}
                      </div>
                    )}
                    <div style={{ padding: '4px 12px 8px', fontSize: 11, color: '#71717a', fontFamily: "'JetBrains Mono', monospace", wordBreak: 'break-all' }}>
                      {address}
                    </div>
                    <div style={{ height: 1, backgroundColor: 'rgba(255,255,255,0.06)', margin: '4px 0' }} />
                    <button
                      onClick={() => { setModalOpen(true); setWalletMenuOpen(false); }}
                      style={{
                        width: '100%',
                        padding: '8px 12px',
                        borderRadius: 8,
                        border: 'none',
                        backgroundColor: 'transparent',
                        color: '#a1a1aa',
                        fontSize: 13,
                        cursor: 'pointer',
                        textAlign: 'left',
                      }}
                    >
                      Switch Wallet
                    </button>
                    <button
                      onClick={() => { logout(); setWalletMenuOpen(false); }}
                      style={{
                        width: '100%',
                        padding: '8px 12px',
                        borderRadius: 8,
                        border: 'none',
                        backgroundColor: 'transparent',
                        color: '#ef4444',
                        fontSize: 13,
                        cursor: 'pointer',
                        textAlign: 'left',
                      }}
                    >
                      Disconnect
                    </button>
                  </div>
                )}
              </div>
            ) : (
              <button
                onClick={connect}
                className="connect-wallet-btn"
                style={{
                  padding: '8px 18px',
                  borderRadius: 10,
                  border: 'none',
                  background: 'linear-gradient(135deg, #FF6B35, #E55A24)',
                  color: 'white',
                  fontSize: 13,
                  fontWeight: 600,
                  cursor: 'pointer',
                  transition: 'all 150ms',
                  boxShadow: '0 2px 12px rgba(255,107,53,0.3)',
                }}
              >
                Connect Wallet
              </button>
            )}

            {/* Mobile hamburger */}
            <button
              className="mobile-menu-btn"
              onClick={() => setMobileOpen(!mobileOpen)}
              style={{
                display: 'none',
                padding: 8,
                borderRadius: 8,
                border: 'none',
                backgroundColor: 'transparent',
                color: '#a1a1aa',
                cursor: 'pointer',
              }}
            >
              <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                {mobileOpen ? (
                  <path d="M18 6L6 18M6 6l12 12" />
                ) : (
                  <path d="M3 12h18M3 6h18M3 18h18" />
                )}
              </svg>
            </button>
          </div>
        </div>

        {/* Mobile menu */}
        {mobileOpen && (
          <div className="mobile-menu" style={{
            padding: '8px 16px 16px',
            borderTop: '1px solid rgba(255,255,255,0.06)',
            maxHeight: 'calc(100dvh - 80px)',
            overflowY: 'auto',
          }}>
            {NAV_ITEMS.map(item => (
              <button
                key={item.id}
                onClick={() => { onNavigate(item.id); setMobileOpen(false); }}
                style={{
                  display: 'block',
                  width: '100%',
                  padding: '12px 16px',
                  borderRadius: 8,
                  border: 'none',
                  textAlign: 'left',
                  fontSize: 14,
                  fontWeight: 500,
                  cursor: 'pointer',
                  backgroundColor: activePage === item.id ? 'rgba(255,107,53,0.12)' : 'transparent',
                  color: activePage === item.id ? '#FF6B35' : '#a1a1aa',
                }}
              >
                {item.label}
              </button>
            ))}
            <div style={{ height: 1, backgroundColor: 'rgba(255,255,255,0.06)', margin: '8px 16px' }} />
            <div style={{ padding: '4px 16px 8px', fontSize: 11, fontWeight: 700, color: '#71717a', letterSpacing: '0.06em' }}>EXPLORE</div>
            {MORE_ITEMS.map(item => (
              <button
                key={item.id}
                onClick={() => { onNavigate(item.id); setMobileOpen(false); }}
                style={{
                  display: 'block',
                  width: '100%',
                  padding: '12px 16px',
                  borderRadius: 8,
                  border: 'none',
                  textAlign: 'left',
                  fontSize: 14,
                  fontWeight: 500,
                  cursor: 'pointer',
                  backgroundColor: activePage === item.id ? 'rgba(255,107,53,0.12)' : 'transparent',
                  color: activePage === item.id ? '#FF6B35' : '#a1a1aa',
                }}
              >
                {item.label}
              </button>
            ))}
          </div>
        )}
      </nav>

      {/* Wallet Connect Modal */}
      <WalletModal
        isOpen={modalOpen}
        onClose={() => setModalOpen(false)}
        onSelect={connectWallet}
        connecting={connecting}
      />

      <style>{`
        @media (max-width: 768px) {
          .desktop-nav { display: none !important; }
          .mobile-menu-btn { display: flex !important; }
          .connect-wallet-btn { padding: 6px 12px !important; font-size: 12px !important; }
        }
        @media (min-width: 769px) {
          .mobile-menu { display: none !important; }
        }
      `}</style>
    </>
  );
}
