import { useEffect, useRef, useState } from 'react';
import { gsap } from 'gsap';
import { ScrollTrigger } from 'gsap/dist/ScrollTrigger';
import { Terminal, Copy, Check, Zap, Shield, Rocket, Database, Wifi, Lock, Cpu, Globe, Code2 } from 'lucide-react';

gsap.registerPlugin(ScrollTrigger);

const tips = [
  {
    id: 1,
    category: 'Performance',
    icon: Rocket,
    color: 'electric',
    title: 'Memory Leak Detection Protocol',
    code: `// Use WeakRef for temporary caching
const cache = new Map();

function getData(key) {
  let ref = cache.get(key);
  if (ref) {
    const data = ref.deref();
    if (data) return data;
  }
  
  const newData = expensiveOperation(key);
  cache.set(key, new WeakRef(newData));
  return newData;
}`,
    description: 'Prevent memory leaks in long-running applications by using WeakRef for non-essential caching. The garbage collector can reclaim memory when needed.',
    tags: ['JavaScript', 'Memory Management', 'Advanced'],
  },
  {
    id: 2,
    category: 'Security',
    icon: Shield,
    color: 'magma',
    title: 'Zero-Knowledge API Authentication',
    code: `// Implement HMAC-based request signing
const crypto = require('crypto');

function signRequest(method, path, body, timestamp) {
  const payload = \`\${method}|\${path}|\${JSON.stringify(body)}|\${timestamp}\`;
  
  return crypto
    .createHmac('sha256', process.env.API_SECRET)
    .update(payload)
    .digest('hex');
}

// Verify on server
function verifyRequest(signature, ...args) {
  const expected = signRequest(...args);
  return crypto.timingSafeEqual(
    Buffer.from(signature),
    Buffer.from(expected)
  );
}`,
    description: 'Never send API keys over the wire. Use HMAC signatures with timestamp validation to prevent replay attacks.',
    tags: ['Security', 'API Design', 'Node.js'],
  },
  {
    id: 3,
    category: 'Database',
    icon: Database,
    color: 'gold',
    title: 'Query Optimization Matrix',
    code: `-- Composite index strategy
CREATE INDEX CONCURRENTLY idx_user_optimized 
ON users (last_active DESC, tier, region) 
INCLUDE (email, name) 
WHERE status = 'active';

-- Partial index for hot paths
CREATE INDEX idx_hot_products 
ON products (category, price) 
WHERE inventory > 0 AND featured = true;`,
    description: 'Use partial and covering indexes to reduce index size by 80% while improving hot query performance by 10x.',
    tags: ['PostgreSQL', 'Performance', 'Database'],
  },
  {
    id: 4,
    category: 'Network',
    icon: Wifi,
    color: 'electric',
    title: 'Adaptive Streaming Handler',
    code: `class AdaptiveStreamer {
  constructor() {
    this.quality = 'high';
    this.latencyHistory = [];
  }
  
  async fetchWithAdaptation(url) {
    const start = performance.now();
    
    try {
      const controller = new AbortController();
      const timeout = this.calculateTimeout();
      
      const response = await fetch(url, {
        signal: controller.signal,
        headers: { 'Accept-Encoding': 'br, gzip' }
      });
      
      const latency = performance.now() - start;
      this.adaptQuality(latency);
      
      return response;
    } catch (e) {
      this.quality = 'low';
      throw e;
    }
  }
}`,
    description: 'Automatically adjust request quality based on real-time network conditions. Essential for mobile-first applications.',
    tags: ['Network', 'PWA', 'Performance'],
  },
  {
    id: 5,
    category: 'Cryptography',
    icon: Lock,
    color: 'magma',
    title: 'Post-Quantum Key Exchange',
    code: `// Using Web Crypto API with ECDH
async function generateEphemeralKeys() {
  const keyPair = await crypto.subtle.generateKey(
    {
      name: 'ECDH',
      namedCurve: 'P-384' // NIST P-384 for quantum resistance
    },
    true, // extractable
    ['deriveBits', 'deriveKey']
  );
  
  // Derive shared secret
  const sharedSecret = await crypto.subtle.deriveBits(
    {
      name: 'ECDH',
      public: peerPublicKey
    },
    keyPair.privateKey,
    384
  );
  
  return hkdfExtract(sharedSecret, salt, 'SHA-384');
}`,
    description: 'Prepare for the quantum future. Use ECDH P-384 for key exchange with proper key derivation functions.',
    tags: ['Cryptography', 'Security', 'Web Crypto'],
  },
  {
    id: 6,
    category: 'System',
    icon: Cpu,
    color: 'gold',
    title: 'Web Worker Task Queue',
    code: `class WorkerPool {
  constructor(workerScript, poolSize = 4) {
    this.workers = Array(poolSize).fill(null)
      .map(() => new Worker(workerScript));
    this.queue = [];
    this.taskId = 0;
  }
  
  execute(data, priority = 0) {
    return new Promise((resolve, reject) => {
      const task = {
        id: ++this.taskId,
        data,
        priority,
        resolve,
        reject,
        timestamp: performance.now()
      };
      
      this.queue.push(task);
      this.queue.sort((a, b) => b.priority - a.priority);
      this.processQueue();
    });
  }
}`,
    description: 'Maintain 60fps by offloading heavy computations to a prioritized worker pool. Critical for data visualization apps.',
    tags: ['Web Workers', 'Performance', 'Architecture'],
  },
];

export default function Workbench() {
  const sectionRef = useRef(null);
  const cardsRef = useRef([]);
  const [copiedId, setCopiedId] = useState(null);

  useEffect(() => {
    const cards = cardsRef.current;
    const triggers = [];

    cards.forEach((card, index) => {
      const trigger = ScrollTrigger.create({
        trigger: card,
        start: 'top 85%',
        onEnter: () => {
          gsap.fromTo(card,
            { opacity: 0, y: 60, rotateX: 15 },
            { 
              opacity: 1, 
              y: 0, 
              rotateX: 0,
              duration: 0.8,
              delay: index * 0.1,
              ease: 'power3.out'
            }
          );
        },
        once: true
      });
      triggers.push(trigger);
    });

    return () => {
      triggers.forEach(t => t.kill());
    };
  }, []);

  const copyToClipboard = async (code, id) => {
    await navigator.clipboard.writeText(code);
    setCopiedId(id);
    setTimeout(() => setCopiedId(null), 2000);
  };

  const getColorClasses = (color) => {
    const colors = {
      electric: 'border-electric-500/30 hover:border-electric-500/60 text-electric-400 bg-electric-500/5',
      magma: 'border-magma-500/30 hover:border-magma-500/60 text-magma-400 bg-magma-500/5',
      gold: 'border-gold-500/30 hover:border-gold-500/60 text-gold-400 bg-gold-500/5',
    };
    return colors[color];
  };

  return (
    <section id="workbench" ref={sectionRef} className="py-24 relative">
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        {/* Section Header */}
        <div className="text-center mb-16">
          <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">
            <Terminal className="w-4 h-4 text-electric-500" />
            <span className="font-mono text-sm text-iron-300">WORKBENCH // ACTIVE_SESSIONS: 1,247</span>
          </div>
          <h2 className="text-4xl sm:text-5xl font-bold mb-4">
            <span className="text-iron-100">Production-Ready </span>
            <span className="text-gradient">Protocols</span>
          </h2>
          <p className="max-w-2xl mx-auto text-iron-400 font-mono">
            Battle-tested code snippets from the frontlines of high-performance systems. 
            Copy, adapt, deploy.
          </p>
        </div>

        {/* Tips Grid */}
        <div className="grid lg:grid-cols-2 gap-6">
          {tips.map((tip, index) => {
            const Icon = tip.icon;
            const colorClasses = getColorClasses(tip.color);
            
            return (
              <div
                key={tip.id}
                ref={el => cardsRef.current[index] = el}
                className={`group relative bg-iron-800/50 backdrop-blur-sm border rounded-xl overflow-hidden transition-all duration-500 hover:shadow-2xl ${colorClasses}`}
                style={{ perspective: '1000px' }}
              >
                {/* Glow Effect */}
                <div className={`absolute inset-0 opacity-0 group-hover:opacity-100 transition-opacity duration-500 bg-gradient-to-br ${tip.color === 'electric' ? 'from-electric-500/10' : tip.color === 'magma' ? 'from-magma-500/10' : 'from-gold-500/10'} to-transparent`} />

                <div className="relative p-6">
                  {/* Header */}
                  <div className="flex items-start justify-between mb-4">
                    <div className="flex items-center gap-3">
                      <div className={`p-2 rounded-lg ${colorClasses}`}>
                        <Icon className="w-5 h-5" />
                      </div>
                      <div>
                        <span className={`text-xs font-mono uppercase tracking-wider ${tip.color === 'electric' ? 'text-electric-400' : tip.color === 'magma' ? 'text-magma-400' : 'text-gold-400'}`}>
                          {tip.category}
                        </span>
                        <h3 className="text-lg font-semibold text-iron-100">{tip.title}</h3>
                      </div>
                    </div>
                    <button
                      onClick={() => copyToClipboard(tip.code, tip.id)}
                      className="p-2 rounded-lg bg-iron-700/50 hover:bg-iron-600/50 transition-colors"
                    >
                      {copiedId === tip.id ? (
                        <Check className="w-4 h-4 text-green-400" />
                      ) : (
                        <Copy className="w-4 h-4 text-iron-400" />
                      )}
                    </button>
                  </div>

                  {/* Code Block */}
                  <div className="relative mb-4 rounded-lg bg-iron-900/80 border border-iron-700/50 overflow-hidden">
                    <div className="flex items-center gap-1.5 px-3 py-2 border-b border-iron-700/50">
                      <div className="w-3 h-3 rounded-full bg-magma-500/80" />
                      <div className="w-3 h-3 rounded-full bg-gold-500/80" />
                      <div className="w-3 h-3 rounded-full bg-green-500/80" />
                      <span className="ml-auto text-xs text-iron-500 font-mono">{tip.tags[0]}</span>
                    </div>
                    <pre className="p-4 text-sm font-mono overflow-x-auto">
                      <code className="text-iron-300">{tip.code}</code>
                    </pre>
                  </div>

                  {/* Description */}
                  <p className="text-iron-400 text-sm leading-relaxed mb-4">
                    {tip.description}
                  </p>

                  {/* Tags */}
                  <div className="flex flex-wrap gap-2">
                    {tip.tags.map(tag => (
                      <span key={tag} className="px-2 py-1 text-xs font-mono rounded bg-iron-700/50 text-iron-300">
                        #{tag}
                      </span>
                    ))}
                  </div>
                </div>
              </div>
            );
          })}
        </div>
      </div>
    </section>
  );
}