'use client';
import { useState, useEffect, useCallback } from 'react';
import Nav from './components/Nav';
import Home from './sections/Home';
import Trust from './sections/Trust';
import AgentHub from './sections/AgentHub';
import Escrow from './sections/Escrow';
import VNS from './sections/VNS';
import Bridge from './sections/Bridge';
import BondDashboard from './sections/BondDashboard';
import Docs from './sections/Docs';
import Verify from './sections/Verify';
import Register from './sections/Register';
import SDK from './sections/SDK';
import AgentAPI from './sections/AgentAPI';
import Discover from './sections/Discover';
import AgentMarketplace from './sections/AgentMarketplace';
import ZKProofs from './sections/ZKProofs';
import VKP from './sections/VKP';
import ToastContainer from './components/Toast';
import { ErrorBoundary } from './components/ErrorBoundary';

export type Page = 'home' | 'agent-hub' | 'vns' | 'bonds' | 'trust' | 'escrow' | 'bridge' | 'docs' | 'verify' | 'register' | 'sdk' | 'api' | 'discover' | 'marketplace' | 'zk-proofs' | 'vkp';

export default function App() {
  const [page, setPage] = useState<Page>('home');
  const [transitioning, setTransitioning] = useState(false);

  const navigate = useCallback((p: Page) => {
    if (p === page) return;
    setTransitioning(true);
    setTimeout(() => {
      setPage(p);
      setTransitioning(false);
      window.scrollTo({ top: 0, behavior: 'instant' as ScrollBehavior });
    }, 150);
  }, [page]);

  // Hash-based routing
  useEffect(() => {
    const hash = window.location.hash.slice(1) as Page;
    const valid: Page[] = ['home', 'agent-hub', 'vns', 'bonds', 'trust', 'escrow', 'bridge', 'docs', 'verify', 'register', 'sdk', 'api', 'discover', 'marketplace', 'zk-proofs', 'vkp'];
    if (hash && valid.includes(hash)) setPage(hash);

    const onHash = () => {
      const h = window.location.hash.slice(1) as Page;
      if (h && valid.includes(h)) setPage(h);
    };
    window.addEventListener('hashchange', onHash);
    return () => window.removeEventListener('hashchange', onHash);
  }, []);

  useEffect(() => {
    if (page !== 'home') window.location.hash = page;
    else if (window.location.hash) history.replaceState(null, '', window.location.pathname);
  }, [page]);

  // Expose navigation globally for cross-component use
  useEffect(() => {
    (window as any).__navigate = navigate;
    return () => { delete (window as any).__navigate; };
  }, [navigate]);

  const renderPage = () => {
    switch (page) {
      case 'home': return <Home onNavigate={navigate} />;
      case 'agent-hub': return <AgentHub />;
      case 'vns': return <VNS />;
      case 'bonds': return <BondDashboard />;
      case 'trust': return <Trust onNavigate={navigate} />;
      case 'escrow': return <Escrow />;
      case 'bridge': return <Bridge />;
      case 'docs': return <Docs onNavigate={navigate} />;
      case 'verify': return <Verify />;
      case 'register': return <Register onNavigate={navigate} />;
      case 'sdk': return <SDK />;
      case 'api': return <AgentAPI />;
      case 'discover': return <Discover onNavigate={navigate} />;
      case 'marketplace': return <AgentMarketplace />;
      case 'zk-proofs': return <ZKProofs />;
      case 'vkp': return <VKP />;
      default: return <Home onNavigate={navigate} />;
    }
  };

  return (
    <>
      <ToastContainer />
      <div style={{ minHeight: '100dvh', backgroundColor: '#09090B', display: 'flex', flexDirection: 'column' }}>
        <Nav activePage={page} onNavigate={navigate} />
        <main style={{ flex: 1, opacity: transitioning ? 0 : 1, transition: 'opacity 150ms ease' }}>
          <ErrorBoundary key={page} sectionName={page}>
            {renderPage()}
          </ErrorBoundary>
        </main>
        <footer style={{
          borderTop: '1px solid rgba(255,255,255,0.06)',
          padding: '48px 24px 40px',
        }}>
          <div style={{ maxWidth: 900, margin: '0 auto' }}>
            {/* Top row: Logo + Links */}
            <div style={{
              display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start',
              flexWrap: 'wrap', gap: 32, marginBottom: 32,
            }}>
              {/* Brand */}
              <div>
                <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 12 }}>
                  <div style={{
                    width: 28, height: 28, borderRadius: 7,
                    background: 'linear-gradient(135deg, #FF6B35, #E55A24)',
                    display: 'flex', alignItems: 'center', justifyContent: 'center',
                  }}>
                    <svg width="14" height="14" 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: 16, fontWeight: 700, color: '#F4F4F5' }}>Vaultfire</span>
                </div>
                <p style={{ fontSize: 12, color: '#52525b', maxWidth: 280, lineHeight: 1.6 }}>
                  The trust layer for the agentic web. On-chain identity, reputation, and accountability for AI agents.
                </p>
              </div>

              {/* Link Groups */}
              <div style={{ display: 'flex', gap: 48, flexWrap: 'wrap' }}>
                <div>
                  <div style={{ fontSize: 11, fontWeight: 700, color: '#71717a', letterSpacing: '0.06em', marginBottom: 12 }}>PROTOCOL</div>
                  {[
                    { label: 'Agent Hub', page: 'agent-hub' as Page },
                    { label: 'VNS Names', page: 'vns' as Page },
                    { label: 'AI Bonds', page: 'bonds' as Page },
                    { label: 'Trust Scores', page: 'trust' as Page },
                    { label: 'Escrow', page: 'escrow' as Page },
                    { label: 'Bridge', page: 'bridge' as Page },
                    { label: 'Discover Agents', page: 'discover' as Page },
                    { label: 'Marketplace', page: 'marketplace' as Page },
                    { label: 'ZK Proofs', page: 'zk-proofs' as Page },
                    { label: 'VKP Keys', page: 'vkp' as Page },
                  ].map(l => (
                    <button key={l.label} onClick={() => navigate(l.page)} style={{
                      display: 'block', background: 'none', border: 'none', padding: '4px 0',
                      fontSize: 12, color: '#a1a1aa', cursor: 'pointer', transition: 'color 150ms',
                    }}
                    onMouseEnter={e => (e.target as HTMLElement).style.color = '#FF8C5A'}
                    onMouseLeave={e => (e.target as HTMLElement).style.color = '#a1a1aa'}
                    >{l.label}</button>
                  ))}
                </div>
                <div>
                  <div style={{ fontSize: 11, fontWeight: 700, color: '#71717a', letterSpacing: '0.06em', marginBottom: 12 }}>DEVELOPERS</div>
                  {[
                    { label: 'Documentation', page: 'docs' as Page },
                    { label: 'SDK', page: 'sdk' as Page },
                    { label: 'API Reference', page: 'api' as Page },
                    { label: 'Register Agent', page: 'register' as Page },
                    { label: 'Verify Contracts', page: 'verify' as Page },
                  ].map(l => (
                    <button key={l.label} onClick={() => navigate(l.page)} style={{
                      display: 'block', background: 'none', border: 'none', padding: '4px 0',
                      fontSize: 12, color: '#a1a1aa', cursor: 'pointer', transition: 'color 150ms',
                    }}
                    onMouseEnter={e => (e.target as HTMLElement).style.color = '#FF8C5A'}
                    onMouseLeave={e => (e.target as HTMLElement).style.color = '#a1a1aa'}
                    >{l.label}</button>
                  ))}
                  <a href="https://basescan.org/address/0x01C479F0c039fEC40c0Cf1c5C921bab457d57441" target="_blank" rel="noopener noreferrer" style={{
                    display: 'block', padding: '4px 0', fontSize: 12, color: '#a1a1aa', textDecoration: 'none', transition: 'color 150ms',
                  }}
                  onMouseEnter={e => (e.target as HTMLElement).style.color = '#FF8C5A'}
                  onMouseLeave={e => (e.target as HTMLElement).style.color = '#a1a1aa'}
                  >BaseScan</a>
                  <a href="https://github.com/Ghostkey316" target="_blank" rel="noopener noreferrer" style={{
                    display: 'block', padding: '4px 0', fontSize: 12, color: '#a1a1aa', textDecoration: 'none', transition: 'color 150ms',
                  }}
                  onMouseEnter={e => (e.target as HTMLElement).style.color = '#FF8C5A'}
                  onMouseLeave={e => (e.target as HTMLElement).style.color = '#a1a1aa'}
                  >GitHub</a>
                </div>
                <div>
                  <div style={{ fontSize: 11, fontWeight: 700, color: '#71717a', letterSpacing: '0.06em', marginBottom: 12 }}>CHAINS</div>
                  {[
                    { name: 'Base', color: '#3B82F6' },
                    { name: 'Avalanche', color: '#EF4444' },
                    { name: 'Arbitrum', color: '#28A0F0' },
                    { name: 'Polygon', color: '#8247E5' },
                  ].map(c => (
                    <div key={c.name} style={{ display: 'flex', alignItems: 'center', gap: 6, padding: '4px 0' }}>
                      <div style={{ width: 6, height: 6, borderRadius: '50%', backgroundColor: c.color }} />
                      <span style={{ fontSize: 12, color: '#a1a1aa' }}>{c.name}</span>
                    </div>
                  ))}
                </div>
                <div>
                  <div style={{ fontSize: 11, fontWeight: 700, color: '#71717a', letterSpacing: '0.06em', marginBottom: 12 }}>LEGAL</div>
                  {[
                    { label: 'Terms of Service', href: '/terms' },
                    { label: 'Privacy Policy', href: '/privacy' },
                    { label: 'Disclaimer', href: '/disclaimer' },
                    { label: 'Security', href: '/security' },
                  ].map(l => (
                    <a key={l.label} href={l.href} style={{
                      display: 'block', padding: '4px 0', fontSize: 12, color: '#a1a1aa', textDecoration: 'none', transition: 'color 150ms',
                    }}
                    onMouseEnter={e => (e.target as HTMLElement).style.color = '#FF8C5A'}
                    onMouseLeave={e => (e.target as HTMLElement).style.color = '#a1a1aa'}
                    >{l.label}</a>
                  ))}
                </div>
              </div>
            </div>

            {/* Divider */}
            <div style={{ height: 1, backgroundColor: 'rgba(255,255,255,0.04)', marginBottom: 24 }} />

            {/* Bottom row */}
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexWrap: 'wrap', gap: 12 }}>
              <div>
                {/* Alpha Badge */}
                <div style={{
                  display: 'inline-flex', alignItems: 'center', gap: 6,
                  padding: '4px 12px', borderRadius: 100, marginBottom: 8,
                  border: '1px solid rgba(234,179,8,0.2)',
                  backgroundColor: 'rgba(234,179,8,0.04)',
                }}>
                  <div style={{ width: 5, height: 5, borderRadius: '50%', backgroundColor: '#EAB308' }} />
                  <span style={{ fontSize: 10, fontWeight: 600, color: '#EAB308', letterSpacing: '0.05em' }}>
                    ALPHA — LIVE ON 4 MAINNET CHAINS
                  </span>
                </div>
                <p style={{ fontSize: 11, color: '#3f3f46' }}>
                  &copy; {new Date().getFullYear()} Vaultfire Protocol. The trust layer for the agentic web.
                </p>
              </div>
              <p className="mission-text" style={{ fontSize: 13, fontWeight: 600, fontStyle: 'italic' }}>
                &ldquo;ENS is for humans. VNS is for agents.&rdquo;
              </p>
            </div>
          </div>
        </footer>
      </div>
    </>
  );
}
