import React, { useState, useEffect } from 'react';
import { useNavigate, Link } from 'react-router-dom';
import { 
  Cpu, Sparkles, ArrowRight, Loader2, ChevronDown, 
  ShieldCheck, Globe, Activity, Layers, Database, Lock, Eye, Building2, BarChart3, Radio, RefreshCw,
  BrainCircuit, Network, Server, Fingerprint, Key, Wallet, FileText, Zap, 
  ChevronLeft, GitPullRequest, Box, Code, ChevronRight, Shield, MessageSquare, Plus, Info, 
  ArrowUpRight, FileCode, Terminal, ArrowRightLeft, Bitcoin
} from 'lucide-react';
import { apiClient } from '../services/api';

// Landing Page Components
import NexusNode from './landing/NexusNode';
import IntelligenceAlpha from './landing/IntelligenceAlpha';
import SystemFabric from './landing/SystemFabric';
import RegistryVault from './landing/RegistryVault';
import PrivacyManifesto from './landing/PrivacyManifesto';
import AssetFoundry from './landing/AssetFoundry';
import QuantumCompute from './landing/QuantumCompute';
import LiquidityMesh from './landing/LiquidityMesh';
import EncryptionProtocol from './landing/EncryptionProtocol';
import OracleAuthority from './landing/OracleAuthority';

const FEATURE_CARDS = [
  { id: 1, title: "Neural Parity", desc: "Real-time ledger consensus across 1,200 nodes with zero-drift synchronization.", icon: Fingerprint, color: "blue", img: "https://images.unsplash.com/photo-1639762681485-074b7f938ba0?q=80&w=2832&auto=format&fit=crop" },
  { id: 2, title: "Quantum Oracle", desc: "Predictive treasury drift detection using qubit-stabilized neural forecasting models.", icon: Cpu, color: "purple", img: "https://images.unsplash.com/photo-1451187580459-43490279c0fa?q=80&w=2872&auto=format&fit=crop" },
  { id: 3, title: "Liquidity Mesh", desc: "High-velocity disbursement fabrics optimized for sub-millisecond M2M settlement.", icon: Network, color: "emerald", img: "https://images.unsplash.com/photo-1614850523296-d8c1af93d400?q=80&w=2570&auto=format&fit=crop" },
  { id: 4, title: "Sovereign ID", desc: "Encapsulated identity vault utilizing RSA-OAEP-4096 and rotating high-entropy seeds.", icon: Lock, color: "rose", img: "https://images.unsplash.com/photo-1558494949-ef010cbdcc51?q=80&w=2546&auto=format&fit=crop" },
  { id: 5, title: "Foundry Sync", desc: "Global distribution node Map with proximity-optimized gateway handshakes.", icon: Globe, color: "cyan", img: "https://images.unsplash.com/photo-1484417894907-623942c8ee29?q=80&w=2832&auto=format&fit=crop" }
];

const Landing: React.FC = () => {
  const navigate = useNavigate();
  const [isDemoLoading, setIsDemoLoading] = useState(false);
  const [scrollY, setScrollY] = useState(0);
  const [activeFeatureIndex, setActiveFeatureIndex] = useState(0);

  useEffect(() => {
    const handleScroll = () => setScrollY(window.scrollY);
    window.addEventListener('scroll', handleScroll);
    return () => window.removeEventListener('scroll', handleScroll);
  }, []);

  const handleDemoAccess = async () => {
    if (isDemoLoading) return;
    setIsDemoLoading(true);
    try {
      const { success } = await apiClient.auth.login('alex', 'password123');
      if (success) {
        window.dispatchEvent(new Event('auth-update'));
        navigate('/overview');
      }
    } catch (err) {
      console.error("Handshake failed.");
    } finally {
      setIsDemoLoading(false);
    }
  };

  const nextFeature = () => setActiveFeatureIndex(p => (p + 1) % FEATURE_CARDS.length);
  const prevFeature = () => setActiveFeatureIndex(p => (p - 1 + FEATURE_CARDS.length) % FEATURE_CARDS.length);

  return (
    <div className="min-h-screen bg-[#020202] text-white font-sans overflow-x-hidden relative selection:bg-blue-600/30 selection:text-white">
      {/* Dynamic Backgrounds */}
      <div className="fixed inset-0 z-0 pointer-events-none">
        <div className="absolute inset-0 bg-[radial-gradient(circle_at_50%_0%,_#1e1b4b_0%,_transparent_60%)] opacity-40"></div>
        <div className="absolute inset-0 bg-[linear-gradient(to_right,#80808008_1px,transparent_1px),linear-gradient(to_bottom,#80808008_1px,transparent_1px)] bg-[size:60px_60px]"></div>
      </div>

      {/* FORTUNE 1200 MEGA HEADER */}
      <nav className={`fixed top-0 left-0 w-full z-[100] px-10 py-6 flex justify-between items-center transition-all duration-700 ${scrollY > 50 ? 'backdrop-blur-3xl bg-black/80 border-b border-white/5 py-4' : 'bg-transparent'}`}>
        <div className="flex items-center gap-12">
          <Link to="/" className="flex items-center gap-6 group">
            <div className="w-12 h-12 bg-white rounded-2xl flex items-center justify-center group-hover:rotate-12 transition-transform duration-700 shadow-2xl border border-zinc-900">
              <Cpu size={24} className="text-black" />
            </div>
            <div>
              <h1 className="text-xl font-black italic tracking-tighter text-white uppercase leading-none">AIBanking<span className="text-blue-500 not-italic">.dev</span></h1>
              <p className="text-[8px] uppercase tracking-[0.6em] font-black text-zinc-600 mt-1">Institutional Consensus</p>
            </div>
          </Link>

          <div className="hidden xl:flex items-center gap-8">
            <MegaNavItem label="Commercial" items={[
              { icon: Zap, title: "Treasury Nodes", desc: "Automated liquidity mesh.", to: "/protocol/treasury" },
              /* Fix: Use ArrowRightLeft which is now imported */
              { icon: ArrowRightLeft, title: "Disbursements", desc: "Real-time global routing.", to: "/payments" },
              { icon: Database, title: "Collections", desc: "Consolidated node intake.", to: "/protocol/collections" }
            ]} />
            <MegaNavItem label="Institutional" items={[
              { icon: Building2, title: "Prime Brokerage", desc: "HFT neural execution.", to: "/protocol/prime" },
              { icon: ShieldCheck, title: "Custody Layer", desc: "RSA-OAEP vaulting.", to: "/protocol/custody" },
              { icon: FileText, title: "Trust Services", desc: "Deterministic ledger audit.", to: "/protocol/trust" }
            ]} />
            <MegaNavItem label="Global Markets" items={[
              /* Fix: Use Bitcoin which is now imported */
              { icon: Bitcoin, title: "Asset Foundry", desc: "Relic synthesis node.", to: "/crypt" },
              { icon: Globe, title: "Forex Mesh", desc: "Sub-ms currency parity.", to: "/protocol/forex" }
            ]} />
            <MegaNavItem label="Tech Stack" items={[
              { icon: Code, title: "API Registry", desc: "FDX v6.5 native sync.", to: "/dcr" },
              { icon: Server, title: "Node Map", desc: "Global cluster health.", to: "/connectivity" },
              { icon: Terminal, title: "SDK Blueprint", desc: "M2M automation core.", to: "/documentation" }
            ]} />
          </div>
        </div>

        <div className="flex items-center gap-8">
          <button onClick={() => navigate('/login')} className="hidden md:block text-[10px] font-black uppercase tracking-[0.4em] text-zinc-500 hover:text-white transition-colors">Client Terminal</button>
          <button onClick={handleDemoAccess} className="px-8 py-4 bg-blue-600 text-white rounded-full font-black text-[10px] uppercase tracking-[0.4em] hover:bg-blue-500 transition-all flex items-center gap-4 shadow-[0_0_30px_rgba(37,99,235,0.3)] group active:scale-95">
            {isDemoLoading ? <Loader2 size={14} className="animate-spin" /> : <Sparkles size={14} className="group-hover:scale-125 transition-transform" />}
            Connect Node
          </button>
        </div>
      </nav>

      {/* HERO SECTION */}
      <section className="relative z-10 min-h-screen flex flex-col justify-center items-center px-10 pt-40 pb-20 text-center overflow-hidden">
        <div className="absolute inset-0 z-0 opacity-30">
           <img src="https://images.unsplash.com/photo-1639322537228-f710d846310a?q=80&w=2832&auto=format&fit=crop" className="w-full h-full object-cover blur-[140px] scale-110" alt="Liquid Space" />
        </div>

        <div className="relative z-10 space-y-16">
          <div className="inline-flex items-center gap-4 px-10 py-4 bg-blue-600/10 border border-blue-600/20 rounded-full animate-in zoom-in-95 duration-1000 relative overflow-hidden group">
            <div className="absolute inset-0 bg-gradient-to-r from-transparent via-white/5 to-transparent animate-[shimmer_2s_infinite]"></div>
            <Activity size={18} className="text-blue-500" />
            <span className="text-[12px] font-black uppercase tracking-[0.8em] text-blue-500">Subspace_Mesh_Stabilized</span>
          </div>

          <h1 className="text-[10rem] lg:text-[14rem] font-black italic tracking-tighter uppercase leading-[0.7] mb-12 drop-shadow-2xl">
            Sovereign <br /><span className="text-blue-600 not-italic decoration-blue-900/40 underline-offset-[30px] underline decoration-[20px]">Assets</span>
          </h1>

          <p className="text-zinc-500 text-3xl lg:text-4xl font-bold italic max-w-6xl mx-auto mb-16 leading-relaxed">
            "The definitive interface for <span className="text-white">high-velocity institutional liquidity</span>. Route neural signals through the mesh with absolute cryptographic parity."
          </p>

          <div className="flex flex-wrap justify-center gap-10 pt-10">
            <button 
              onClick={handleDemoAccess} 
              className="px-16 py-8 bg-white text-black rounded-[2.5rem] font-black text-sm uppercase tracking-[0.6em] flex items-center gap-8 hover:bg-blue-600 hover:text-white transition-all shadow-[0_40px_80px_rgba(255,255,255,0.1)] group active:scale-95"
            >
              {isDemoLoading ? <Loader2 size={24} className="animate-spin" /> : <span>Initialize Registry</span>}
              <ArrowRight size={24} className="group-hover:translate-x-4 transition-transform duration-700" />
            </button>
            <button onClick={() => navigate('/documentation')} className="px-16 py-8 bg-zinc-950 border border-zinc-900 text-white rounded-[2.5rem] font-black text-sm uppercase tracking-[0.6em] flex items-center gap-8 hover:border-blue-600 transition-all shadow-2xl group active:scale-95">
              <FileCode size={24} className="text-blue-500" />
              Manual_v6.5
            </button>
          </div>
        </div>
        <div className="mt-40 animate-bounce opacity-20"><ChevronDown size={64} /></div>
      </section>

      {/* FEATURE SHUFFLE */}
      <section className="relative z-10 py-60 px-10 bg-zinc-950/20">
         <div className="max-w-[1400px] mx-auto grid grid-cols-1 lg:grid-cols-2 gap-32 items-center">
            <div className="space-y-16">
               <div className="space-y-6">
                  <h3 className="text-blue-500 font-black text-xs uppercase tracking-[0.8em]">Endless Feature Stack</h3>
                  <h2 className="text-8xl lg:text-[10rem] font-black italic text-white tracking-tighter uppercase leading-[0.85]">Infinite <br /> <span className="text-blue-600 not-italic">Optimization</span></h2>
               </div>
               <p className="text-zinc-500 text-2xl font-bold leading-relaxed italic max-w-2xl">
                 "Our architectural layers are infinite. Swipe through the core protocols that define the future of sovereign digital wealth management."
               </p>
               <div className="flex gap-8">
                  <button onClick={prevFeature} className="p-8 bg-zinc-900 border border-zinc-800 rounded-3xl hover:bg-zinc-800 text-zinc-500 hover:text-white transition-all"><ChevronLeft size={32} /></button>
                  <button onClick={nextFeature} className="p-8 bg-zinc-900 border border-zinc-800 rounded-3xl hover:bg-zinc-800 text-zinc-500 hover:text-white transition-all"><ChevronRight size={32} /></button>
               </div>
            </div>

            <div className="relative h-[800px] flex items-center justify-center">
               {FEATURE_CARDS.map((card, i) => {
                 const isActive = activeFeatureIndex === i;
                 const isPrev = (activeFeatureIndex - 1 + FEATURE_CARDS.length) % FEATURE_CARDS.length === i;
                 const isNext = (activeFeatureIndex + 1) % FEATURE_CARDS.length === i;
                 let offset = isActive ? 0 : isNext ? 80 : isPrev ? -80 : 160;                 let opacity = isActive ? 1 : isNext || isPrev ? 0.4 : 0;
                 let scale = isActive ? 1 : 0.8;
                 let zIndex = isActive ? 50 : 30;

                 return (
                   <div 
                     key={card.id}
                     className="absolute inset-0 transition-all duration-1000 ease-[cubic-bezier(0.23,1,0.32,1)]"
                     style={{ transform: `translateX(${offset}px) scale(${scale})`, opacity, zIndex }}
                   >
                     <div className="w-full h-full bg-zinc-950 border border-zinc-900 rounded-[5rem] overflow-hidden shadow-[0_100px_200px_rgba(0,0,0,0.8)] relative group">
                        <img src={card.img} className="absolute inset-0 w-full h-full object-cover opacity-40 group-hover:opacity-60 transition-opacity duration-[3s]" alt={card.title} />
                        <div className="absolute inset-0 bg-gradient-to-t from-black via-black/20 to-transparent"></div>
                        <div className="absolute bottom-16 left-16 right-16 space-y-8">
                           <div className={`p-8 bg-white/10 text-white rounded-[2rem] flex items-center justify-center border border-white/20 shadow-2xl backdrop-blur-xl inline-block w-20 h-20`}>
                              <card.icon size={40} />
                           </div>
                           <div className="space-y-4">
                              <h4 className="text-6xl font-black italic uppercase tracking-tighter text-white leading-none">{card.title}</h4>
                              <p className="text-zinc-400 text-xl font-bold leading-relaxed italic pr-10">"{card.desc}"</p>
                           </div>
                        </div>
                     </div>
                   </div>
                 );
               })}
            </div>
         </div>
      </section>

      {/* FULL SUB-SECTIONS INTEGRATED */}
      <NexusNode />
      <IntelligenceAlpha />
      <SystemFabric />
      <RegistryVault />
      <PrivacyManifesto />
      <AssetFoundry />
      <QuantumCompute />
      <LiquidityMesh />
      <EncryptionProtocol />
      <OracleAuthority />

      {/* FAT INSTITUTIONAL FOOTER (THE 50+ LINKS) */}
      <footer className="relative z-10 bg-black pt-80 pb-40 px-10 border-t border-zinc-900">
         <div className="max-w-[1600px] mx-auto">
            <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-20 mb-60">
               <div className="col-span-2 space-y-12">
                  <div className="flex items-center gap-6">
                    <div className="w-16 h-16 bg-white rounded-3xl flex items-center justify-center border-4 border-zinc-900 shadow-2xl">
                      <Cpu size={40} className="text-black" />
                    </div>
                    <h2 className="text-4xl font-black italic tracking-tighter uppercase leading-none">AIBanking<span className="text-blue-500 not-italic">.dev</span></h2>
                  </div>
                  <p className="text-zinc-500 text-xl font-bold italic leading-relaxed max-w-md">
                    "The undisputed leader in neural treasury automation and institutional mesh fabrics. Verified 2025."
                  </p>
                  <div className="flex gap-8">
                     <SocialIcon icon={Globe} /><SocialIcon icon={Shield} /><SocialIcon icon={Zap} /><SocialIcon icon={MessageSquare} />
                  </div>
               </div>
               
               <FooterColumn title="Protocols" links={[
                 { l: 'FDX v6.5 Registry', to: '/protocol/fdx-registry' },
                 { l: 'RSA-OAEP-4096', to: '/protocol/rsa-oaep' },
                 { l: 'Subspace Handshake', to: '/protocol/subspace' },
                 { l: 'M2M Consensus', to: '/protocol/m2m' },
                 { l: 'Zero-Knowledge Vaults', to: '/protocol/zk-vaults' },
                 { l: 'Layer 2 Settlement', to: '/protocol/l2-settlement' },
                 { l: 'Cross-Node Parity', to: '/protocol/node-parity' },
                 { l: 'Entropy Rotation', to: '/protocol/entropy' }
               ]} />
               <FooterColumn title="Intelligence" links={[
                 { l: 'Lumina Oracle', to: '/intelligence/oracle' },
                 { l: 'Predictive Alpha', to: '/intelligence/alpha' },
                 { l: 'Drift Detection', to: '/intelligence/drift' },
                 { l: 'Machine Sentiment', to: '/intelligence/sentiment' },
                 { l: 'HFT Neural Pathing', to: '/intelligence/hft' },
                 { l: 'Simulation Core', to: '/oracle' },
                 { l: 'Risk Analysis v4', to: '/intelligence/risk' },
                 { l: 'Treasury Logic', to: '/intelligence/treasury-logic' }
               ]} />
               <FooterColumn title="Network" links={[
                 { l: 'Global Node Map', to: '/connectivity' },
                 { l: 'US-EAST Cluster', to: '/network/us-east' },
                 { l: 'EU-WEST Parity', to: '/network/eu-west' },
                 { l: 'APAC Dispersal', to: '/network/apac' },
                 { l: 'Latency Hubs', to: '/network/latency' },
                 { l: 'Bare Metal Clusters', to: '/network/bare-metal' },
                 { l: 'Edge Distribution', to: '/network/edge' },
                 { l: 'Node Health Polling', to: '/network/health' }
               ]} />
               <FooterColumn title="Institutional" links={[
                 { l: 'Vault Registry', to: '/vault' },
                 { l: 'Disbursements', to: '/payments' },
                 { l: 'Collections', to: '/institutional/collections' },
                 { l: 'Registry Settlement', to: '/institutional/settlement' },
                 { l: 'Partner CRM', to: '/partners' },
                 { l: 'KYC Handshake', to: '/institutional/kyc' },
                 { l: 'Compliance Node', to: '/institutional/compliance' },
                 { l: 'Asset Custody', to: '/institutional/custody' }
               ]} />
            </div>

            <div className="pt-20 border-t border-zinc-900 flex flex-col md:flex-row justify-between items-center gap-12">
               <div className="flex flex-wrap justify-center md:justify-start gap-12 text-[10px] font-black uppercase tracking-[0.4em] text-zinc-600">
                  <button onClick={() => navigate('/manifesto')} className="hover:text-white transition-colors">Manifesto</button>
                  <button onClick={() => navigate('/documentation')} className="hover:text-white transition-colors">System Manual</button>
                  <button onClick={() => navigate('/documentation')} className="hover:text-white transition-colors">API Registry</button>
                  <button onClick={() => navigate('/airdrop')} className="hover:text-white transition-colors">Genesis Airdrop</button>
                  <button onClick={() => navigate('/documentation')} className="hover:text-white transition-colors">SLA Standard</button>
               </div>
               <p className="text-[10px] font-black uppercase tracking-[1em] text-zinc-800">Citibank Demo Business Inc • aibanking.dev Protocol</p>
            </div>
         </div>
      </footer>
    </div>
  );
};

const MegaNavItem = ({ label, items }: { label: string, items: any[] }) => (
  <div className="group relative py-4">
    <button className="text-[10px] font-black uppercase tracking-[0.4em] text-zinc-400 group-hover:text-white transition-colors flex items-center gap-2">
      {label} <ChevronDown size={10} />
    </button>
    <div className="absolute top-full left-0 w-[480px] bg-zinc-950 border border-zinc-900 rounded-[2.5rem] p-10 opacity-0 pointer-events-none group-hover:opacity-100 group-hover:translate-y-2 transition-all shadow-2xl space-y-6 z-[110]">
      {items.map((item, i) => (
        <Link key={i} to={item.to} className="flex gap-6 items-start hover:translate-x-2 transition-transform group/link">
          <div className="p-3 bg-zinc-900 rounded-xl text-zinc-600 group-hover/link:text-blue-500 group-hover/link:bg-blue-500/10 transition-all">
            <item.icon size={20} />
          </div>
          <div>
            <h4 className="text-sm font-black text-white uppercase italic tracking-widest">{item.title}</h4>
            <p className="text-[9px] text-zinc-500 font-bold leading-relaxed">{item.desc}</p>
          </div>
        </Link>
      ))}
    </div>
  </div>
);

const FooterColumn = ({ title, links }: { title: string, links: {l: string, to: string}[] }) => (
  <div className="space-y-12">
     <h4 className="text-[12px] font-black uppercase tracking-[0.6em] text-white italic">{title}</h4>
     <ul className="space-y-6">
        {links.map((link, i) => (
          <li key={i}>
            <Link to={link.to} className="text-[10px] font-bold text-zinc-600 hover:text-blue-400 transition-colors uppercase tracking-widest">{link.l}</Link>
          </li>
        ))}
     </ul>
  </div>
);

const SocialIcon = ({ icon: Icon }: any) => (
  <div className="p-4 bg-zinc-900 border border-zinc-800 rounded-2xl text-zinc-500 hover:text-white hover:border-blue-500 transition-all cursor-pointer shadow-xl">
    <Icon size={24} />
  </div>
);

export default Landing;