import { useEffect, useRef, useState } from 'react';
import { gsap } from 'gsap';
import { ScrollTrigger } from 'gsap/dist/ScrollTrigger';
import { BookOpen, Clock, ArrowRight, Sparkles, Target, Lightbulb, TrendingUp } from 'lucide-react';

gsap.registerPlugin(ScrollTrigger);

const articles = [
  {
    id: 1,
    title: 'The Sub-Millisecond API: Architecture Patterns for Extreme Performance',
    excerpt: 'How we achieved 0.3ms p99 latency in a distributed system handling 10M RPS. Lessons from rethinking every layer of the stack.',
    readTime: '12 min',
    category: 'Architecture',
    featured: true,
    insights: ['Edge caching strategies', 'Protocol buffers optimization', 'Kernel bypass networking'],
  },
  {
    id: 2,
    title: 'Quantum-Resistant Cryptography: A Practical Migration Guide',
    excerpt: 'NIST has finalized post-quantum algorithms. Here is how to migrate your existing PKI infrastructure without downtime.',
    readTime: '8 min',
    category: 'Security',
    featured: false,
    insights: ['CRYSTALS-Kyber implementation', 'Hybrid key exchange', 'Certificate lifecycle'],
  },
  {
    id: 3,
    title: 'The Hidden Cost of JavaScript: Memory Profiling Deep Dive',
    excerpt: 'V8 internals exposed. Understanding hidden classes, shape transitions, and why your "simple" function allocates 2MB.',
    readTime: '15 min',
    category: 'Performance',
    featured: false,
    insights: ['V8 heap snapshots', 'Hidden class optimization', 'Memory leak patterns'],
  },
  {
    id: 4,
    title: 'Building Unstoppable Systems: Chaos Engineering in Production',
    excerpt: 'Netflix taught us to embrace failure. Here is the playbook for designing systems that thrive under extreme conditions.',
    readTime: '10 min',
    category: 'Reliability',
    featured: false,
    insights: ['Game day exercises', 'Fault injection', 'Circuit breaker patterns'],
  },
  {
    id: 5,
    title: 'The Compiler You Did Not Know You Had: SQL Query Planning',
    excerpt: 'PostgreSQL query planner demystified. How to read EXPLAIN ANALYZE output like a database engineer.',
    readTime: '11 min',
    category: 'Database',
    featured: false,
    insights: ['Cost-based optimization', 'Index selection', 'Join strategies'],
  },
  {
    id: 6,
    title: 'WebAssembly at Scale: Lessons from Figma and Shopify',
    excerpt: 'When to WASM, when to stay native. Real-world performance data from production deployments.',
    readTime: '9 min',
    category: 'WebAssembly',
    featured: false,
    insights: ['WASM vs JS benchmarks', 'Module loading', 'Memory management'],
  },
];

export default function LabNotes() {
  const sectionRef = useRef(null);
  const [activeFilter, setActiveFilter] = useState('All');
  const [hoveredCard, setHoveredCard] = useState(null);

  const categories = ['All', ...new Set(articles.map(a => a.category))];
  const filteredArticles = activeFilter === 'All' 
    ? articles 
    : articles.filter(a => a.category === activeFilter);

  useEffect(() => {
    const ctx = gsap.context(() => {
      gsap.from('.lab-note-card', {
        scrollTrigger: {
          trigger: '#lab-notes',
          start: 'top 80%',
        },
        y: 50,
        opacity: 0,
        duration: 0.6,
        stagger: 0.1,
        ease: 'power2.out'
      });
    }, sectionRef);

    return () => ctx.revert();
  }, [filteredArticles]);

  return (
    <section id="lab-notes" ref={sectionRef} className="py-24 relative bg-iron-900/50">
      {/* Background Pattern */}
      <div className="absolute inset-0 grid-pattern opacity-30" />

      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 relative z-10">
        {/* Section Header */}
        <div className="flex flex-col lg:flex-row lg:items-end lg:justify-between mb-12 gap-6">
          <div>
            <div className="inline-flex items-center gap-2 px-4 py-2 rounded-full bg-iron-800/80 border border-iron-600/50 mb-6">
              <BookOpen className="w-4 h-4 text-magma-500" />
              <span className="font-mono text-sm text-iron-300">LAB NOTES // KNOWLEDGE_BASE</span>
            </div>
            <h2 className="text-4xl sm:text-5xl font-bold mb-4">
              <span className="text-iron-100">Deep Dives & </span>
              <span className="text-gradient">Field Reports</span>
            </h2>
            <p className="max-w-xl text-iron-400 font-mono">
              Extended analysis from the trenches of production systems. 
              Theory meets battle-tested implementation.
            </p>
          </div>

          {/* Filter Tabs */}
          <div className="flex flex-wrap gap-2">
            {categories.map(cat => (
              <button
                key={cat}
                onClick={() => setActiveFilter(cat)}
                className={`px-4 py-2 rounded-lg font-mono text-sm transition-all ${activeFilter === cat ? 'bg-electric-500 text-iron-900' : 'bg-iron-800 text-iron-300 hover:bg-iron-700'}`}
              >
                {cat}
              </button>
            ))}
          </div>
        </div>

        {/* Featured Article */}
        {filteredArticles.find(a => a.featured) && (
          <div className="mb-8 p-8 rounded-2xl bg-gradient-to-br from-iron-800 to-iron-900 border border-iron-600/50 relative overflow-hidden group">
            <