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">
            Your AI agents forget everything between sessions. PULSE gives them a shared brain.
          </p>

          {/* Tagline */}
          <p className="text-sm sm:text-base text-sky-300/70 mb-12 leading-relaxed">
            Persistent memory for Claude, Gemini, Cursor, Copilot & any AI coding agent.
            <br />
            Every session learns. Every agent remembers. Zero manual notes.
          </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>

          {/* How it works */}
          <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">1</div>
              <h3 className="text-sky-300 font-semibold mb-2">pip install pulse-os</h3>
              <p className="text-slate-400 text-sm">One command. Works with Claude Code, Gemini, Copilot, Cursor, Codex, and any LLM.</p>
            </div>
            <div className="text-center">
              <div className="text-sky-400 text-3xl mb-2">2</div>
              <h3 className="text-sky-300 font-semibold mb-2">Agents learn automatically</h3>
              <p className="text-slate-400 text-sm">62+ patterns extract lessons, failures, and decisions automatically. Optional LLM synthesis deepens understanding — works with any provider or local Ollama.</p>
            </div>
            <div className="text-center">
              <div className="text-sky-400 text-3xl mb-2">3</div>
              <h3 className="text-sky-300 font-semibold mb-2">Knowledge persists forever</h3>
              <p className="text-slate-400 text-sm">Next session starts with a brain briefing — past lessons, failure warnings, and predictions. Claude learns it, Gemini inherits it. Switch tools freely.</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">What PULSE Does</h2>
            <p className="text-slate-400 max-w-2xl mx-auto">
              Your agents stop repeating mistakes, remember what works, and share knowledge across models.
            </p>
          </motion.div>

          {/* Feature Cards Grid */}
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-8">
            <FeatureCard
              icon={<span>🧠</span>}
              title="Persistent Memory"
              description="Every coding session is captured and distilled into lessons, failures, and patterns. Next time your agent boots, it already knows what worked and what didn't — no re-explaining, no lost context."
              delay={0}
            />
            <FeatureCard
              icon={<span>🐝</span>}
              title="Multi-Agent, One Brain"
              description="Claude, Gemini, Copilot, Codex — all reading and writing to the same shared memory. Claude discovers a fix at 2am, Gemini uses it at 9am. No copy-pasting between tools."
              delay={0.15}
            />
            <FeatureCard
              icon={<span>⚡</span>}
              title="Swarm Workers"
              description="Post tasks to a shared board and spin up multiple agents to work in parallel. PULSE handles coordination, deduplication, and quality control. You review the results."
              delay={0.3}
            />
            <FeatureCard
              icon={<span>🔓</span>}
              title="Zero Vendor Lock-in"
              description="Works with API keys, CLI subscriptions (Claude Code, Gemini CLI), or completely offline with Ollama. Your brain data stays local — JSONL files in your project, fully portable."
              delay={0.45}
            />
          </div>

          {/* Pain Points Section */}
          <div className="grid grid-cols-1 md:grid-cols-3 gap-8">
            {[
              {
                title: 'Your agent forgets everything',
                description: 'Every session starts from zero. Decisions, patterns, failures \u2014 all gone. You re-explain the same architecture to a blank-slate agent every morning.',
                stat: '100%',
                statLabel: 'context lost per session',
              },
              {
                title: 'Rules get ignored after line 100',
                description: 'CLAUDE.md rules compete with everything else in the context window for attention. After compaction, your carefully written guidelines are summarized into nothing.',
                stat: '40%',
                statLabel: 'rule compliance drop in long sessions',
              },
              {
                title: 'Zero visibility into what your agent learned',
                description: 'Your agent made 200 decisions today. Which ones were good? Without audit trails and knowledge tracking, you are flying blind.',
                stat: '0',
                statLabel: 'decisions tracked by default',
              },
            ].map((pain, idx) => (
              <motion.div
                key={idx}
                initial={{ opacity: 0, y: 30 }}
                whileInView={{ opacity: 1, y: 0 }}
                viewport={{ once: true, margin: '-60px' }}
                transition={{ duration: 0.5, delay: idx * 0.1 }}
                className="bg-red-500/5 border border-red-500/20 rounded-2xl p-8 hover:border-red-400/30 transition-colors"
              >
                <div className="text-4xl font-black text-red-400/80 mb-2">{pain.stat}</div>
                <div className="text-xs text-red-400/60 uppercase tracking-wider mb-4">{pain.statLabel}</div>
                <h3 className="text-lg font-bold text-slate-200 mb-3">{pain.title}</h3>
                <p className="text-slate-400 text-sm leading-relaxed">{pain.description}</p>
              </motion.div>
            ))}
          </div>

          {/* Stats Bar */}
          <motion.div
            initial={{ opacity: 0, y: 20 }}
            whileInView={{ opacity: 1, y: 0 }}
            viewport={{ once: true, margin: '-60px' }}
            transition={{ duration: 0.5 }}
            className="bg-sky-500/5 border border-sky-400/20 rounded-2xl p-6"
          >
            <div className="grid grid-cols-2 md:grid-cols-4 gap-6 text-center">
              {[
                { value: '62+', label: 'Extraction Patterns' },
                { value: '6', label: 'Scoring Dimensions' },
                { value: '17', label: 'Parallel Search Sources' },
                { value: '<2.5s', label: 'Brain Search Latency' },
              ].map((stat, idx) => (
                <div key={idx}>
                  <div className="text-3xl font-black text-sky-400">{stat.value}</div>
                  <div className="text-xs text-slate-400 uppercase tracking-wider mt-1">{stat.label}</div>
                </div>
              ))}
            </div>
          </motion.div>

          {/* Code Snippet */}
          <motion.div
            initial={{ opacity: 0, y: 30 }}
            whileInView={{ opacity: 1, y: 0 }}
            viewport={{ once: true, margin: '-60px' }}
            transition={{ duration: 0.5 }}
            className="text-center"
          >
            <h2 className="text-3xl sm:text-4xl font-bold text-sky-400 mb-4">Two commands. That's it.</h2>
            <p className="text-slate-400 mb-8 max-w-xl mx-auto">Install, initialize, and your agents have persistent memory. No config files, no vector database, no infrastructure.</p>
            <div className="bg-slate-900/80 border border-slate-700/50 rounded-2xl p-6 max-w-lg mx-auto text-left font-mono text-sm">
              <div className="text-slate-500 mb-2"># Install</div>
              <div className="text-sky-400 mb-4">pip install pulse-os</div>
              <div className="text-slate-500 mb-2"># Initialize your project brain</div>
              <div className="text-sky-400 mb-4">pulse init</div>
              <div className="text-slate-500 mb-2"># Start coding — memory is automatic</div>
              <div className="text-sky-400">pulse claude</div>
            </div>
          </motion.div>

          {/* Dashboard Preview */}
          <motion.div
            initial={{ opacity: 0, y: 30 }}
            whileInView={{ opacity: 1, y: 0 }}
            viewport={{ once: true, margin: '-60px' }}
            transition={{ duration: 0.5 }}
          >
            <h2 className="text-3xl sm:text-4xl font-bold text-sky-400 mb-4 text-center">See your agent's brain</h2>
            <p className="text-slate-400 mb-8 text-center max-w-2xl mx-auto">
              Real-time dashboard with knowledge graph visualization, agent monitoring, task tracking, and brain health metrics.
            </p>
            <div className="bg-slate-900/80 border border-slate-700/50 rounded-2xl p-8">
              <div className="grid grid-cols-2 md:grid-cols-4 gap-4 mb-6">
                {[
                  { label: 'Agents', value: '5', sub: '3 working' },
                  { label: 'Knowledge Items', value: '54,219', sub: '6 dimensions scored' },
                  { label: 'Brain Integrity', value: '94%', sub: 'consolidation healthy' },
                  { label: 'Search Sources', value: '13', sub: 'hot cache active' },
                ].map((stat, idx) => (
                  <div key={idx} className="bg-slate-800/50 border border-slate-700/30 rounded-xl p-4">
                    <div className="text-xs text-slate-500 uppercase tracking-wider">{stat.label}</div>
                    <div className="text-2xl font-bold text-sky-400 mt-1">{stat.value}</div>
                    <div className="text-xs text-slate-500 mt-1">{stat.sub}</div>
                  </div>
                ))}
              </div>
              <div className="flex flex-wrap gap-2 mb-6">
                {['Knowledge Graph', '3D Brain', 'Lessons', 'Failures', 'Patterns', 'Anti-Patterns', 'Predictions'].map((tab) => (
                  <span key={tab} className="bg-slate-800/80 border border-slate-600/30 rounded-lg px-3 py-1.5 text-xs text-slate-400">
                    {tab}
                  </span>
                ))}
              </div>
              <div className="text-center">
                <Link
                  to="/dashboard"
                  className="inline-block px-6 py-3 rounded-xl bg-gradient-to-r from-sky-500 to-cyan-500 text-slate-950 font-semibold text-sm shadow-lg shadow-sky-500/30 hover:shadow-sky-400/50 hover:-translate-y-1 transition-all duration-200"
                >
                  Explore Live Dashboard
                </Link>
              </div>
            </div>
          </motion.div>

          {/* Governance & Security */}
          <motion.div
            initial={{ opacity: 0, y: 30 }}
            whileInView={{ opacity: 1, y: 0 }}
            viewport={{ once: true, margin: '-60px' }}
            transition={{ duration: 0.5 }}
          >
            <h2 className="text-3xl sm:text-4xl font-bold text-sky-400 mb-4 text-center">Constitutional AI Governance</h2>
            <p className="text-slate-400 mb-8 text-center max-w-2xl mx-auto">
              Your agents operate under enforceable laws, not suggestions. 14 governance rules enforced by code, not prompts.
            </p>
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
              {[
                {
                  title: 'Agents cannot go rogue',
                  description: '4 immutable laws (non-harm, privacy, truth, human override) enforced at the code level. No prompt can override them. Constitutional hash lock kills the system if governance is tampered with.',
                  accent: 'emerald',
                },
                {
                  title: 'Your data stays private',
                  description: 'PII detection blocks sensitive data at system boundaries. All brain data is local — SQLite in your project directory. No cloud, no telemetry, no phone-home. Private knowledge is segregated and gitignored.',
                  accent: 'emerald',
                },
                {
                  title: 'Every decision is auditable',
                  description: 'Cryptographic provenance (HMAC-SHA256) on all knowledge items. Every fact traces back to the agent, session, and timestamp that created it. Full decision replay.',
                  accent: 'emerald',
                },
                {
                  title: 'Self-correcting code quality',
                  description: 'Mathematical SoC enforcement (300-line limit, 5-function cap per file). Anti-pattern detection blocks known bad patterns before they land. Pre-commit hooks enforce standards automatically.',
                  accent: 'emerald',
                },
              ].map((item, idx) => (
                <div key={idx} className="bg-emerald-500/5 border border-emerald-500/20 rounded-2xl p-6 hover:border-emerald-400/30 transition-colors">
                  <h3 className="text-emerald-400 font-bold mb-3">{item.title}</h3>
                  <p className="text-slate-400 text-sm leading-relaxed">{item.description}</p>
                </div>
              ))}
            </div>
          </motion.div>

          {/* Integration Logos */}
          <motion.div
            initial={{ opacity: 0 }}
            whileInView={{ opacity: 1 }}
            viewport={{ once: true, margin: '-60px' }}
            transition={{ duration: 0.5 }}
            className="text-center"
          >
            <h2 className="text-2xl font-bold text-sky-400 mb-2">Works with every agent</h2>
            <p className="text-slate-400 mb-8 text-sm">One brain, any model. Your agents share knowledge across tools.</p>
            <div className="flex flex-wrap justify-center gap-6">
              {[
                'Claude Code', 'Gemini CLI', 'Cursor', 'Copilot', 'Codex', 'Ollama',
              ].map((tool) => (
                <div key={tool} className="bg-slate-800/50 border border-slate-700/30 rounded-xl px-5 py-3 text-slate-300 text-sm font-medium hover:border-sky-400/30 transition-colors">
                  {tool}
                </div>
              ))}
            </div>
          </motion.div>

          {/* FAQ */}
          <motion.div
            initial={{ opacity: 0, y: 30 }}
            whileInView={{ opacity: 1, y: 0 }}
            viewport={{ once: true, margin: '-60px' }}
            transition={{ duration: 0.5 }}
          >
            <h2 className="text-3xl font-bold text-sky-400 mb-8 text-center">Common Questions</h2>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
              {[
                {
                  q: 'Does it work offline?',
                  a: 'Yes. PULSE runs 100% locally. Your brain data stays in your project directory. Optional LLM synthesis uses your own API keys or Ollama.',
                },
                {
                  q: 'What models does it support?',
                  a: 'Claude Code, Gemini CLI, Cursor, Copilot, Codex, Grok, and any model via Ollama. All agents read and write to the same shared brain.',
                },
                {
                  q: 'How is this different from CLAUDE.md memory?',
                  a: 'CLAUDE.md is a static file you maintain manually. PULSE automatically extracts knowledge, scores it by confidence and recency, decays stale information, and injects only what is relevant.',
                },
                {
                  q: 'What happens to my data?',
                  a: 'Everything stays on your machine. SQLite database in your project. No cloud, no phone-home, no telemetry. Export anytime.',
                },
              ].map((faq, idx) => (
                <div key={idx} className="bg-slate-800/30 border border-slate-700/30 rounded-xl p-6">
                  <h3 className="text-sky-300 font-semibold mb-2">{faq.q}</h3>
                  <p className="text-slate-400 text-sm leading-relaxed">{faq.a}</p>
                </div>
              ))}
            </div>
          </motion.div>

          {/* Final CTA */}
          <motion.div
            initial={{ opacity: 0, y: 30 }}
            whileInView={{ opacity: 1, y: 0 }}
            viewport={{ once: true, margin: '-60px' }}
            transition={{ duration: 0.5 }}
            className="text-center py-8"
          >
            <h2 className="text-3xl sm:text-4xl font-bold text-white mb-4">Stop re-explaining your project every session.</h2>
            <p className="text-slate-400 mb-8 max-w-xl mx-auto">
              7-day free trial. Your agents get smarter starting today.
            </p>
            <div className="flex flex-col sm:flex-row gap-4 justify-center items-center">
              <a
                href="/pricing"
                className="group px-8 py-4 rounded-xl bg-gradient-to-r from-sky-500 to-cyan-500 text-slate-950 font-semibold text-lg shadow-lg shadow-sky-500/50 hover:shadow-sky-400/75 hover:-translate-y-1 transition-all duration-200"
              >
                Start Free Trial
                <span className="inline-block ml-2 group-hover:translate-x-1 transition-transform">{'\u2192'}</span>
              </a>
              <Link
                to="/docs"
                className="px-8 py-4 rounded-xl border-2 border-sky-400/50 text-sky-400 font-semibold text-lg hover:bg-sky-400/10 hover:border-sky-400 transition-all duration-200"
              >
                Read the Docs
              </Link>
            </div>
            <p className="text-slate-500 text-xs mt-4">pip install pulse-os | Works on macOS, Linux, Windows</p>
          </motion.div>
        </div>
      </div>
    </div>
  );
}
