import { useEffect, useState } from 'react';
import Particles, { initParticlesEngine } from '@tsparticles/react';
import type { ISourceOptions } from '@tsparticles/engine';
import { loadSlim } from '@tsparticles/slim';
import { motion, useInView } from 'framer-motion';
import { useRef } from 'react';
import { Link } from 'react-router-dom';

function FeatureCard({ icon, title, description, delay = 0 }: {
  icon: React.ReactNode;
  title: string;
  description: string;
  delay?: number;
}) {
  const ref = useRef(null);
  const inView = useInView(ref, { once: true, margin: '-80px' });

  return (
    <motion.div
      ref={ref}
      initial={{ opacity: 0, y: 40 }}
      animate={inView ? { opacity: 1, y: 0 } : { opacity: 0, y: 40 }}
      transition={{ duration: 0.6, delay, ease: 'easeOut' }}
      className="bg-slate-800/50 backdrop-blur-sm border border-slate-700/50 rounded-2xl p-8 hover:border-sky-400/30 transition-colors duration-300"
    >
      <div className="text-4xl mb-4">{icon}</div>
      <h3 className="text-xl font-bold text-sky-400 mb-3">{title}</h3>
      <p className="text-slate-300 leading-relaxed text-sm">{description}</p>
    </motion.div>
  );
}

export default function Landing() {
  const [engineReady, setEngineReady] = useState(false);

  useEffect(() => {
    initParticlesEngine(async (engine) => {
      await loadSlim(engine);
    }).then(() => {
      setEngineReady(true);
    });
  }, []);

  const particlesOptions: ISourceOptions = {
    background: {
      color: {
        value: '#0f172a',
      },
    },
    fullScreen: {
      enable: false,
    },
    fpsLimit: 60,
    particles: {
      color: {
        value: '#06b6d4',
      },
      links: {
        enable: true,
        distance: 150,
        color: '#06b6d4',
        opacity: 0.5,
        width: 1,
        triangles: {
          enable: false,
          frequency: 5,
        },
      },
      move: {
        enable: true,
        speed: 2,
        direction: 'none',
        random: true,
        straight: false,
        outModes: 'bounce',
      },
      number: {
        value: 120,
      },
      opacity: {
        value: {
          min: 0.3,
          max: 0.8,
        },
      },
      shape: {
        type: 'circle',
      },
      size: {
        value: {
          min: 1,
          max: 3,
        },
      },
      twinkle: {
        particles: {
          enable: true,
          frequency: 0.05,
          opacity: 1,
        },
      },
    },
    interactivity: {
      events: {
        onClick: {
          enable: true,
          mode: 'repulse',
        },
        onHover: {
          enable: true,
          mode: 'attract',
          parallax: {
            enable: true,
            force: 60,
            smooth: 10,
          },
        },
      },
      modes: {
        repulse: {
          distance: 200,
          duration: 0.4,
        },
        attract: {
          distance: 200,
          duration: 0.4,
        },
      },
    },
  };

  return (
    <div className="relative min-h-screen bg-slate-950 overflow-hidden">
      {/* Particles background */}
      {engineReady && (
        <Particles
          id="tsparticles"
          options={particlesOptions}
          className="absolute inset-0"
        />
      )}

      {/* Gradient overlay for depth */}
      <div className="absolute inset-0 bg-gradient-to-b from-slate-950/50 via-transparent to-slate-950/50 pointer-events-none" />

      {/* Content */}
      <div className="relative z-10 min-h-screen flex flex-col items-center justify-center px-4 sm:px-6 lg:px-8">
        {/* Hero Section */}
        <div className="text-center max-w-4xl mx-auto">
          {/* Logo/Title */}
          <div className="mb-8 inline-block">
            <h1 className="text-7xl sm:text-8xl font-black text-sky-400 tracking-tighter drop-shadow-[0_0_30px_rgba(6,182,212,0.6)]">
              PULSE
            </h1>
            <div className="h-1 w-32 mx-auto mt-4 bg-gradient-to-r from-sky-400 to-cyan-500" />
          </div>

          {/* Subtitle */}
          <p className="text-lg sm:text-2xl text-slate-300 font-light tracking-wide mb-4">
            Neural Operating System for AI Swarms
          </p>

          {/* Tagline */}
          <p className="text-sm sm:text-base text-sky-300/70 mb-12 leading-relaxed">
            Decentralized governance meets collective intelligence.
            <br />
            Your multi-agent infrastructure, unified by constitutional laws.
          </p>

          {/* CTA Buttons */}
          <div className="flex flex-col sm:flex-row gap-4 justify-center items-center">
            <a
              href="/pricing"
              className="group px-8 py-3 sm:py-4 rounded-xl bg-gradient-to-r from-sky-500 to-cyan-500 text-slate-950 font-semibold text-base sm:text-lg shadow-lg shadow-sky-500/50 hover:shadow-sky-400/75 hover:-translate-y-1 transition-all duration-200 focus:outline-none focus:ring-2 focus:ring-sky-400 focus:ring-offset-2 focus:ring-offset-slate-950"
            >
              Get Started
              <span className="inline-block ml-2 group-hover:translate-x-1 transition-transform">→</span>
            </a>

            <Link
              to="/install"
              className="px-8 py-3 sm:py-4 rounded-xl border-2 border-sky-400/50 text-sky-400 font-semibold text-base sm:text-lg hover:bg-sky-400/10 hover:border-sky-400 transition-all duration-200 focus:outline-none focus:ring-2 focus:ring-sky-400 focus:ring-offset-2 focus:ring-offset-slate-950"
            >
              Learn More
            </Link>
          </div>

          {/* Feature highlights */}
          <div className="mt-20 grid grid-cols-1 sm:grid-cols-3 gap-8 pt-12 border-t border-slate-700/50">
            <div className="text-center">
              <div className="text-sky-400 text-3xl mb-2">⚙️</div>
              <h3 className="text-sky-300 font-semibold mb-2">Autonomous Agents</h3>
              <p className="text-slate-400 text-sm">Multi-model coordination with zero handoff</p>
            </div>
            <div className="text-center">
              <div className="text-sky-400 text-3xl mb-2">🧠</div>
              <h3 className="text-sky-300 font-semibold mb-2">Collective Memory</h3>
              <p className="text-slate-400 text-sm">Hippocampus-inspired learning & reasoning</p>
            </div>
            <div className="text-center">
              <div className="text-sky-400 text-3xl mb-2">📜</div>
              <h3 className="text-sky-300 font-semibold mb-2">Constitutional</h3>
              <p className="text-slate-400 text-sm">Immutable laws for trustworthy AI</p>
            </div>
          </div>
        </div>
      </div>

      {/* Recovery link */}
      <div className="relative z-10 text-center pb-4">
        <Link to="/recover" className="text-slate-500 hover:text-slate-400 text-xs transition-colors">
          Lost your license key?
        </Link>
      </div>

      {/* Feature Sections */}
      <div id="features" className="relative z-10 px-4 sm:px-6 lg:px-8 pb-24">
        <div className="max-w-6xl mx-auto space-y-16">
          {/* Section Header */}
          <motion.div
            initial={{ opacity: 0 }}
            whileInView={{ opacity: 1 }}
            viewport={{ once: true, margin: '-80px' }}
            transition={{ duration: 0.5 }}
            className="text-center pt-8"
          >
            <h2 className="text-3xl sm:text-4xl font-bold text-sky-400 mb-4">Core Architecture</h2>
            <p className="text-slate-400 max-w-2xl mx-auto">
              Three pillars that make PULSE a self-governing neural operating system.
            </p>
          </motion.div>

          {/* Feature Cards Grid */}
          <div className="grid grid-cols-1 md:grid-cols-3 gap-8">
            <FeatureCard
              icon={<span>🧠</span>}
              title="Brain Pipeline"
              description="Every agent interaction is captured, bridged through salience scoring, and stored in a hippocampus-inspired memory system. At boot, agents receive a compressed briefing of lessons, failures, and proven patterns — so no insight is ever lost."
              delay={0}
            />
            <FeatureCard
              icon={<span>🐝</span>}
              title="Swarm Coordination"
              description="A shared task board lets multiple agents self-organize via the ASOP protocol. Tasks are auto-tiered by complexity, claimed atomically, and executed in parallel — from cheap flash models for simple work to premium models for architecture decisions."
              delay={0.15}
            />
            <FeatureCard
              icon={<span>⚖️</span>}
              title="Constitutional Governance"
              description="10 immutable laws enforced via HMAC-SHA256 signing and a compliance validator daemon. Every dispatch is cryptographically verified. No agent can bypass rules without explicit approval — governance is silent, automatic, and tamper-proof."
              delay={0.3}
            />
          </div>
        </div>
      </div>
    </div>
  );
}
