import { useState, useEffect } from 'react';
import { motion, AnimatePresence } from 'framer-motion';

type Bullet = {
  heading: string;
  body: string;
  subpoints?: string[];
};

type Tab = {
  id: 'zero-os' | 'compute' | 'gpu' | 'data' | 'network';
  label: string;
  title: string;
  description: string;
  bullets: Bullet[];
  cardText: string;
};

const tabs: Tab[] = [
  {
    id: 'zero-os',
    label: 'Zero-OS',
    title: 'Zero-OS',
    description:
      'Minimal, self-healing bare-metal OS that powers autonomous nodes across the ThreeFold Grid.',
    cardText: 'Stateless architecture ensures every boot is secure and unmodified, eliminating configuration drift and security vulnerabilities.',
    bullets: [
      {
        heading: 'Immutable by Design',
        body: 'Boots statelessly from a signed image each time, removing drift and shrinking the attack surface.',
      },
      {
        heading: 'Autonomous Operations',
        body: 'Digital twin controllers redeploy workloads to healthy nodes and roll out updates with zero downtime.',
      },
      {
        heading: 'Zero-Trust Networking',
        body: 'Integrated WireGuard overlay and cryptographic identities secure every peer-to-peer connection.',
      },
      {
        heading: 'Unified Resource Fabric',
        body: 'Exposes compute, storage, and network primitives through a single API for edge, datacenter, or hybrid deployments.',
      },
    ],
  },
  {
    id: 'compute',
    label: 'Compute',
    title: 'Compute',
    description: 'A self-healing compute fabric designed for resilience, decentralization, and scale.',
    cardText: 'Autonomous workload orchestration across distributed nodes ensures maximum uptime and performance.',
    bullets: [
      {
        heading: 'Autonomous Workload Management',
        body: 'Workloads automatically migrate to healthy nodes to ensure fault tolerance and high availability.',
      },
      {
        heading: 'AI & Web3 Ready',
        body: 'Run LLMs, autonomous agents, blockchain nodes, and immersive metaverse apps at the edge.',
      },
      {
        heading: 'Zero-OS (ZOS)',
        body: 'Our custom-built, stateless, immutable OS that powers:',
        subpoints: [
          'MicroVMs & containerized environments (Kubernetes, Docker, Firecracker).',
          'AI inference and training workloads.',
          'Web3 infrastructure and federated learning models.',
        ],
      },
      {
        heading: 'No Hyperscalers',
        body: 'Fully independent infrastructure managed by intelligent agents on bare metal.',
      },
    ],
  },
  {
    id: 'data',
    label: 'Data',
    title: 'Data',
    description: 'Private, distributed, and AI-native storage with user sovereignty at its core.',
    cardText: 'Quantum-safe encryption and distributed redundancy protect your data while maintaining lightning-fast access.',
    bullets: [
      {
        heading: 'Privacy-First',
        body: 'End-to-end encryption and redundancy, with no central control.',
      },
      {
        heading: '10x Efficient',
        body: 'Optimized for performance and sustainability, far surpassing traditional cloud.',
      },
      {
        heading: 'Geo-Aware & Compliant',
        body: "Data stays where it's supposed to, satisfying regional policies and privacy standards.",
      },
    ],
  },
  {
    id: 'network',
    label: 'Network',
    title: 'Network',
    description:
      'A secure, peer-to-peer internet backbone, self-sustaining, censorship-resistant, and optimized for performance.',
    cardText: 'Mesh topology with intelligent routing creates a resilient network that adapts to changing conditions.',
    bullets: [
      {
        heading: 'End-to-End Encryption',
        body: 'All communications are secured by design.',
      },
      {
        heading: 'Shortest-Path Routing',
        body: 'Dynamically finds the most efficient path across the network, reducing latency and cost.',
      },
      {
        heading: 'No Middlemen',
        body: 'Fully peer-to-peer, removing reliance on centralized ISPs or DNS providers.',
      },
      {
        heading: 'Censorship Resistance',
        body: 'Built to thrive under pressure, even in restricted or controlled regions.',
      },
    ],
  },
  {
    id: 'gpu',
    label: 'GPU Fabric',
    title: 'Distributed GPU Fabric',
    description:
      'A sovereign mesh of GPU capacity that turns idle silicon into revenue while powering global AI workloads and collective intelligence.',
    cardText:
      'Autonomous allocation keeps GPUs saturated with high-value workloads, creating a lucrative marketplace for operators and builders alike.',
    bullets: [
      {
        heading: 'Global GPU Federation',
        body: 'Aggregates GPUs across homes, enterprises, and datacenters into a single pool so large-scale training and inference run close to data without hyperscaler dependence.',
      },
      {
        heading: 'Revenue Engine',
        body: 'Dynamic marketplace routes AI and rendering jobs to available GPUs, maximizing utilization and delivering steady cash flow to operators.',
      },
      {
        heading: 'Sovereign Collective Intelligence',
        body: 'Supports collaborative model training where communities contribute data and capacity, unlocking responsible AI networks governed by their stakeholders.',
      },
      {
        heading: 'Zero-OS Integration',
        body: 'Zero-OS provisions GPU-optimized microVMs with secure drivers, ensuring deterministic performance and remote attestation of every workload.',
      },
    ],
  },
];

// Floating particle component
const FloatingParticle = ({ delay, index }: { delay: number; index: number }) => {
  const startX = (index % 3) * 40 + 10;
  const startY = Math.floor(index / 3) * 60 + 20;
  
  return (
    <motion.div
      className="absolute h-3 w-3 rounded-full bg-blue-400"
      style={{ left: `${startX}%`, top: `${startY}%` }}
      initial={{ opacity: 0, scale: 0 }}
      animate={{
        y: [-10, -30, -10],
        x: [0, Math.sin(index) * 15, 0],
        opacity: [0, 0.7, 0],
        scale: [0, 1.2, 0],
      }}
      transition={{
        duration: 3,
        delay,
        repeat: Infinity,
        ease: 'easeInOut',
      }}
    />
  );
};

export const TechnologyArchitecture = () => {
  const [activeTab, setActiveTab] = useState<Tab['id']>('zero-os');
  const [particles, setParticles] = useState<number[]>([]);
  const current = tabs.find((tab) => tab.id === activeTab) ?? tabs[0];

  useEffect(() => {
    // Generate random particles on tab change
    setParticles(Array.from({ length: 6 }, (_, i) => i));
  }, [activeTab]);

  return (
    <section className="py-16 text-slate-100 lg:py-24">
      <div className="mx-auto max-w-4xl text-center">
        <div className="flex items-center justify-center gap-4">
          <span
            aria-hidden="true"
            className="hidden h-px w-16 bg-gradient-to-r from-transparent via-brand-500/40 to-brand-300/70 sm:block"
          />
          <p className="text-xs font-semibold uppercase tracking-[0.35em] text-brand-300">
            Software Primitives
          </p>
          <span
            aria-hidden="true"
            className="hidden h-px w-16 bg-gradient-to-l from-transparent via-brand-500/40 to-brand-300/70 sm:block"
          />
        </div>
        <h2 className="mt-4 text-3xl font-semibold text-white sm:text-4xl">Autonomous Software Stack</h2>
        <p className="mt-4 text-base text-slate-300 sm:text-lg">
          Seamlessly integrating compute, storage, and networking, GeoMind's architecture delivers secure,
          scalable, and efficient infrastructure for AI, cloud, and next-generation workloads from edge to
          planetary scale.
        </p>
      </div>
      <div className="mt-12 lg:mt-16">
        <div className="flex flex-wrap gap-3 pb-4">
          {tabs.map((tab) => (
            <button
              key={tab.id}
              type="button"
              onClick={() => setActiveTab(tab.id)}
              className={`rounded-full px-4 py-2 text-sm font-semibold transition-all duration-300 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand-300 focus-visible:ring-offset-2 focus-visible:ring-offset-neutral-950 ${
                activeTab === tab.id
                  ? 'bg-brand-600 text-white shadow-subtle hover:bg-brand-700'
                  : 'border border-white/10 bg-transparent text-slate-300 hover:border-brand-400/50 hover:bg-brand-500/10 hover:text-white hover:shadow-md'
              }`}
            >
              {tab.label}
            </button>
          ))}
        </div>
        <div className="mt-8">
          <AnimatePresence mode="wait">
            <motion.div
              key={current.id}
              initial={{ opacity: 0, y: 20 }}
              animate={{ opacity: 1, y: 0 }}
              exit={{ opacity: 0, y: -10 }}
              transition={{ duration: 0.4, ease: 'easeOut' }}
              className="grid gap-8 lg:grid-cols-[2fr,1fr]"
            >
              <div>
                <h3 className="text-xl font-semibold text-brand-200">{current.title}</h3>
                <p className="mt-2 text-base text-slate-300">{current.description}</p>
                <ul className="mt-6 space-y-4 text-sm text-slate-300">
                  {current.bullets.map((bullet) => (
                    <li
                      key={bullet.heading}
                      className="group rounded-2xl border border-white/10 bg-black p-4 transition-all duration-300 hover:-translate-y-1 hover:border-brand-400/50 hover:bg-white/5 hover:shadow-[0_24px_48px_-36px_rgba(56,189,248,0.45)]"
                    >
                      <p className="text-base font-semibold text-white">{bullet.heading}</p>
                      <p className="mt-2 text-sm text-slate-300">{bullet.body}</p>
                      {bullet.subpoints && (
                        <ul className="mt-3 space-y-2 text-sm text-slate-400">
                          {bullet.subpoints.map((point) => (
                            <li key={point} className="flex gap-3">
                              <span className="mt-1 inline-block h-1.5 w-1.5 flex-shrink-0 rounded-full bg-brand-400" />
                              <span>{point}</span>
                            </li>
                          ))}
                        </ul>
                      )}
                    </li>
                  ))}
                </ul>
              </div>
              <div className="hidden h-full rounded-3xl border border-white/10 bg-black p-6 transition-all duration-300 hover:-translate-y-1.5 hover:border-brand-400/50 hover:bg-white/5 hover:shadow-[0_30px_72px_-48px_rgba(56,189,248,0.45)] backdrop-blur lg:flex lg:flex-col lg:items-start lg:justify-between">
                <motion.p
                  key={`label-${current.id}`}
                  initial={{ opacity: 0, y: -10 }}
                  animate={{ opacity: 1, y: 0 }}
                  transition={{ duration: 0.3 }}
                  className="text-sm font-semibold uppercase tracking-[0.35em] text-brand-200"
                >
                  {current.label}
                </motion.p>
                <motion.p
                  key={`text-${current.id}`}
                  initial={{ opacity: 0 }}
                  animate={{ opacity: 1 }}
                  transition={{ duration: 0.5, delay: 0.2 }}
                  className="mt-6 text-sm text-slate-200"
                >
                  {current.cardText}
                </motion.p>
                <div className="relative mt-6 h-40 w-full overflow-hidden rounded-2xl bg-gradient-to-br from-blue-950/60 via-indigo-950/50 to-purple-900/40">
                  {/* Animated gradient overlay */}
                  <motion.div
                    className="absolute inset-0 bg-gradient-to-br from-blue-500/20 via-indigo-500/20 to-purple-500/20"
                    animate={{
                      opacity: [0.3, 0.6, 0.3],
                      scale: [1, 1.05, 1],
                    }}
                    transition={{
                      duration: 4,
                      repeat: Infinity,
                      ease: 'easeInOut',
                    }}
                  />
                  
                  {/* Floating particles */}
                  {particles.map((i) => (
                    <FloatingParticle key={`${current.id}-${i}`} delay={i * 0.4} index={i} />
                  ))}
                  
                  {/* Animated circles */}
                  <motion.div
                    className="absolute left-1/4 top-1/4 h-20 w-20 rounded-full bg-blue-300/30"
                    animate={{
                      scale: [1, 1.5, 1],
                      opacity: [0.3, 0.5, 0.3],
                      x: [0, 20, 0],
                      y: [0, -10, 0],
                    }}
                    transition={{
                      duration: 5,
                      repeat: Infinity,
                      ease: 'easeInOut',
                    }}
                  />
                  
                  <motion.div
                    className="absolute right-1/4 bottom-1/4 h-16 w-16 rounded-full bg-indigo-300/30"
                    animate={{
                      scale: [1, 1.3, 1],
                      opacity: [0.3, 0.6, 0.3],
                      x: [0, -15, 0],
                      y: [0, 10, 0],
                    }}
                    transition={{
                      duration: 4,
                      delay: 0.5,
                      repeat: Infinity,
                      ease: 'easeInOut',
                    }}
                  />
                  
                  {/* Central glowing orb */}
                  <motion.div
                    className="absolute left-1/2 top-1/2 h-24 w-24 -translate-x-1/2 -translate-y-1/2 rounded-full bg-gradient-to-br from-blue-400/40 to-purple-400/40 blur-2xl"
                    animate={{
                      scale: [1, 1.4, 1],
                      opacity: [0.4, 0.7, 0.4],
                    }}
                    transition={{
                      duration: 3,
                      repeat: Infinity,
                      ease: 'easeInOut',
                    }}
                  />
                  
                  {/* Animated lines */}
                  <svg className="absolute inset-0 h-full w-full opacity-30">
                    <motion.line
                      x1="10%"
                      y1="20%"
                      x2="90%"
                      y2="80%"
                      stroke="rgb(99, 102, 241)"
                      strokeWidth="2"
                      strokeDasharray="5,5"
                      animate={{
                        strokeDashoffset: [0, -20],
                        opacity: [0.3, 0.6, 0.3],
                      }}
                      transition={{
                        duration: 2,
                        repeat: Infinity,
                        ease: 'linear',
                      }}
                    />
                    <motion.line
                      x1="90%"
                      y1="20%"
                      x2="10%"
                      y2="80%"
                      stroke="rgb(147, 51, 234)"
                      strokeWidth="2"
                      strokeDasharray="5,5"
                      animate={{
                        strokeDashoffset: [0, 20],
                        opacity: [0.3, 0.6, 0.3],
                      }}
                      transition={{
                        duration: 2.5,
                        repeat: Infinity,
                        ease: 'linear',
                      }}
                    />
                  </svg>
                </div>
              </div>
            </motion.div>
          </AnimatePresence>
        </div>
      </div>
    </section>
  );
};
