const { useState, useEffect, useRef, useLayoutEffect } = React;

// Register GSAP plugins
gsap.registerPlugin(ScrollTrigger);

// ============================================
// GLOBAL CONSTANTS
// ============================================
const BRAND_NAME = "DamanProjects";
const HERO_NOUN = "Engineering";
const HERO_POWER = "Foundation";
const PRIMARY_CTA = "Coming Soon";

const SHUFFLER_ITEMS = [
  {
    icon: <svg className="w-6 h-6" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect width="16" height="16" x="4" y="4" rx="2" /><rect width="6" height="6" x="9" y="9" rx="1" /><path d="M15 2v2" /><path d="M15 20v2" /><path d="M2 15h2" /><path d="M2 9h2" /><path d="M20 15h2" /><path d="M20 9h2" /><path d="M9 2v2" /><path d="M9 20v2" /></svg>,
    label: "React & Next.js Ecosystem", desc: "Component architecture"
  },
  {
    icon: <svg className="w-6 h-6" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><ellipse cx="12" cy="5" rx="9" ry="3" /><path d="M3 5V19A9 3 0 0 0 21 19V5" /><path d="M3 12A9 3 0 0 0 21 12" /></svg>,
    label: "Scalable Postgres/Redis", desc: "High-performance data"
  },
  {
    icon: <svg className="w-6 h-6" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect width="20" height="8" x="2" y="2" rx="2" /><rect width="20" height="8" x="2" y="14" rx="2" /><line x1="6" x2="6.01" y1="6" y2="6" /><line x1="6" x2="6.01" y1="18" y2="18" /></svg>,
    label: "Cloudflare Edge Workers", desc: "Global distribution"
  }
];

const TELEMETRY_LINES = [
  "> Initializing AI integration sequence...",
  "> Loading WebLLM context window...",
  "> Binding vector embeddings to application state...",
  "> Establishing WebSocket telemetry channel...",
  "> Synchronizing multi-modal pipelines...",
  "> System architecture optimized for latency."
];

const PROTOCOL_STEPS = [
  { id: "01", title: "Architectural Planning", desc: "Mapping the domain model, database schema, and infrastructure topology before writing a single line of code." },
  { id: "02", title: "Iterative Engineering", desc: "Building modular, type-safe components with automated testing and continuous integration pipelines." },
  { id: "03", title: "Edge Deployment", desc: "Deploying globally distributed applications via Cloudflare with built-in CDN, SSL, and DDoS protection." }
];

const PROJECTS = [
  {
    name: 'StreamVault',
    subtitle: 'Streaming Platform',
    desc: 'A streaming platform leveraging Google Gemini AI for recommendations and content processing. Video/content streaming with AI-powered recommendations and user profiles.',
    features: ['Video/content streaming', 'AI-powered recommendations', 'User profiles & watchlists'],
    readiness: 'early',
    readinessLabel: 'Early Development',
    url: 'https://streaming.damanprojects.uk',
    color: '#E63B2E',
    icon: (
      <svg className="w-8 h-8 text-preset-accent" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
        <rect x="2" y="4" width="20" height="16" rx="2" ry="2" />
        <path d="M10 8l6 4-6 4V8z" fill="currentColor">
          <animate attributeName="opacity" values="0.4;1;0.4" dur="2s" repeatCount="indefinite" />
        </path>
      </svg>
    )
  },
  {
    name: 'CryptoPulse',
    subtitle: 'Crypto Portfolio Tracker',
    desc: 'Cryptocurrency portfolio tracker for monitoring coin holdings, prices, and market performance with real-time data feeds.',
    features: ['Real-time price tracking', 'Portfolio value calculation', 'Multi-currency support'],
    readiness: 'prototype',
    readinessLabel: 'Prototype',
    url: 'https://crypto.damanprojects.uk',
    color: '#CC5833',
    icon: (
      <svg className="w-8 h-8 text-preset-accent" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
        <polyline points="3 17 9 11 13 15 21 7" />
        <circle cx="21" cy="7" r="2" fill="currentColor">
          <animate attributeName="opacity" values="0;1;0" dur="2s" repeatCount="indefinite" />
          <animate attributeName="r" values="2;4;2" dur="2s" repeatCount="indefinite" />
        </circle>
      </svg>
    )
  },
  {
    name: 'FreshTrack',
    subtitle: 'Grocery Management',
    desc: 'A household grocery management app for tracking shopping lists, pantry inventory, and meal planning integration.',
    features: ['Shopping list management', 'Pantry/fridge inventory', 'Recipe & meal planning'],
    readiness: 'prototype',
    readinessLabel: 'Prototype',
    url: 'https://grocery.damanprojects.uk',
    color: '#CC5833',
    icon: (
      <svg className="w-8 h-8 text-preset-accent" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
        <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z" />
        <path d="M14 2v6h6" />
        <path d="M16 13H8" />
        <path d="M16 17H8" />
        <path d="M10 9H8" />
        <circle cx="9" cy="13" r="1.5" fill="currentColor">
          <animate attributeName="opacity" values="0;1;0" dur="1.5s" repeatCount="indefinite" />
        </circle>
      </svg>
    )
  },
  {
    name: 'Schedule 1',
    subtitle: 'Scheduling App',
    desc: 'A scheduling and calendar application for managing appointments, tasks, and events with reminders and notification support.',
    features: ['Event/task scheduling', 'Calendar view', 'Reminders & notifications'],
    readiness: 'prototype',
    readinessLabel: 'Prototype',
    url: 'https://schedule1.damanprojects.uk',
    color: '#CC5833',
    icon: (
      <svg className="w-8 h-8 text-preset-accent" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
        <rect x="3" y="4" width="18" height="18" rx="2" ry="2" />
        <line x1="16" y1="2" x2="16" y2="6" />
        <line x1="8" y1="2" x2="8" y2="6" />
        <line x1="3" y1="10" x2="21" y2="10" />
        <path d="M10 16l2 2 4-4" strokeDasharray="20">
          <animate attributeName="stroke-dashoffset" values="20;0" dur="2s" fill="freeze" repeatCount="indefinite" />
        </path>
      </svg>
    )
  },
  {
    name: 'FitForge',
    subtitle: 'Workout Tracker',
    desc: 'A fitness tracking application for logging and monitoring workout routines, exercises, and progress analytics over time.',
    features: ['Workout session logging', 'Sets/reps/weights tracking', 'Progress history & analytics'],
    readiness: 'prototype',
    readinessLabel: 'Prototype',
    url: 'https://workout.damanprojects.uk',
    color: '#CC5833',
    icon: (
      <svg className="w-8 h-8 text-preset-accent" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
        <g>
          <animateTransform attributeName="transform" type="translate" values="0,2; 0,-2; 0,2" dur="2s" repeatCount="indefinite" />
          <path d="M6 5v14M18 5v14M4 7h4M4 17h4M16 7h4M16 17h4M10 12h4" />
        </g>
      </svg>
    )
  },
  {
    name: 'BankManager',
    subtitle: 'Personal Finance',
    desc: 'A personal finance management tool for tracking bank accounts, transactions, and balances with AI-powered categorization.',
    features: ['Multi-account support', 'Transaction categorization', 'Balance tracking & reporting'],
    readiness: 'prototype',
    readinessLabel: 'Prototype',
    url: 'https://bankmanager.damanprojects.uk',
    color: '#CC5833',
    icon: (
      <svg className="w-8 h-8 text-preset-accent" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
        <rect x="3" y="11" width="18" height="11" rx="2" ry="2" />
        <path d="M7 11V7a5 5 0 0 1 10 0v4" />
        <circle cx="12" cy="16" r="1.5" fill="currentColor">
          <animate attributeName="opacity" values="0;1;0" dur="2s" repeatCount="indefinite" />
        </circle>
      </svg>
    )
  },
  {
    name: 'SopranoTTS',
    subtitle: 'Neural Text-to-Speech',
    desc: 'High-fidelity text-to-speech synthesis with emotional inflection, multi-voice support, and real-time audio generation.',
    features: ['Emotional inflection', 'Multi-voice support', 'Real-time generation'],
    readiness: 'prototype',
    readinessLabel: 'Prototype',
    url: 'https://soprano.damanprojects.uk',
    color: '#CC5833',
    icon: (
      <svg className="w-8 h-8 text-preset-accent" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
        <path d="M12 4v16">
          <animate attributeName="d" values="M12 4v16;M12 10v4;M12 4v16" dur="1s" repeatCount="indefinite" />
        </path>
        <path d="M8 8v8">
          <animate attributeName="d" values="M8 8v8;M8 4v16;M8 8v8" dur="1.2s" repeatCount="indefinite" />
        </path>
        <path d="M16 8v8">
          <animate attributeName="d" values="M16 8v8;M16 6v12;M16 8v8" dur="0.8s" repeatCount="indefinite" />
        </path>
      </svg>
    )
  },
];

// ============================================
// A. NAVBAR - "The Floating Island"
// ============================================
function Navbar() {
  const [scrolled, setScrolled] = useState(false);
  const navRef = useRef(null);

  useEffect(() => {
    const handleScroll = () => setScrolled(window.scrollY > 80);
    window.addEventListener('scroll', handleScroll);
    return () => window.removeEventListener('scroll', handleScroll);
  }, []);

  useLayoutEffect(() => {
    const ctx = gsap.context(() => {
      gsap.from(navRef.current, {
        y: -100,
        opacity: 0,
        duration: 1.2,
        ease: 'power3.out',
        delay: 0.2
      });
      gsap.from('.nav-item', {
        y: -20,
        opacity: 0,
        stagger: 0.1,
        duration: 0.8,
        ease: 'power3.out',
        delay: 0.5
      });
    });
    return () => ctx.revert();
  }, []);

  const scrollTo = (id) => document.getElementById(id)?.scrollIntoView({ behavior: 'smooth' });

  return (
    <nav
      ref={navRef}
      className={`fixed top-8 left-1/2 -translate-x-1/2 z-50 floating-island rounded-full px-6 py-4 flex items-center justify-between gap-8 md:gap-16 transition-colors duration-500
        ${scrolled ? 'scrolled bg-preset-bg/85 border-preset-primary/10 text-preset-primary' : 'bg-transparent border-transparent text-preset-bg'}`}
      style={{ width: 'min(90%, 800px)' }}
    >
      <div className="nav-item font-display font-bold text-xl tracking-tight-custom cursor-pointer" onClick={() => window.scrollTo(0, 0)}>
        {scrolled ? BRAND_NAME : <span className="text-preset-bg">{BRAND_NAME}</span>}
      </div>

      <div className="hidden md:flex items-center gap-8 font-mono text-sm uppercase tracking-widest">
        <button onClick={() => scrollTo('projects')} className="nav-item hover:text-preset-accent transition-colors">Projects</button>
        <button onClick={() => scrollTo('features')} className="nav-item hover:text-preset-accent transition-colors">Features</button>
        <button onClick={() => scrollTo('philosophy')} className="nav-item hover:text-preset-accent transition-colors">Philosophy</button>
      </div>

      <button onClick={() => scrollTo('contact')} className="nav-item magnetic-btn bg-preset-accent text-white px-6 py-2 rounded-full font-sans font-semibold text-sm hover:bg-[#A8492A] transition-colors">
        {PRIMARY_CTA}
      </button>
    </nav>
  );
}

// ============================================
// B. HERO - "The Opening Shot"
// ============================================
function Hero() {
  const heroRef = useRef(null);

  useLayoutEffect(() => {
    const ctx = gsap.context(() => {
      const tl = gsap.timeline({ delay: 0.3 });
      tl.from('.hero-line-1', { y: 60, opacity: 0, duration: 1, ease: 'power3.out' })
        .from('.hero-line-2', { y: 80, opacity: 0, duration: 1.2, ease: 'power3.out' }, '-=0.6')
        .from('.hero-desc', { y: 30, opacity: 0, duration: 0.8, ease: 'power3.out' }, '-=0.8')
        .from('.hero-cta', { y: 30, opacity: 0, scale: 0.95, duration: 0.8, ease: 'power3.out' }, '-=0.6');
    }, heroRef);
    return () => ctx.revert();
  }, []);

  return (
    <section ref={heroRef} className="relative h-[100dvh] bg-preset-text text-preset-bg overflow-hidden flex flex-col justify-end pb-16 md:pb-24 px-6 md:px-12 lg:px-24">
      {/* Background Image with Gradient Overlay */}
      <div
        className="absolute inset-0 z-0 opacity-40 mix-blend-luminosity"
        style={{
          backgroundImage: 'url("https://images.unsplash.com/photo-1542273917363-3b1817fac697?q=80&w=2074")', // Dark forest / organic texture
          backgroundSize: 'cover',
          backgroundPosition: 'center',
        }}
      />
      <div className="absolute inset-0 z-0 bg-gradient-to-t from-preset-text via-preset-text/80 to-transparent" />

      {/* Hero Content positioned bottom-left third */}
      <div className="relative z-10 max-w-4xl pt-32">
        <h1 className="flex flex-col gap-2">
          <span className="hero-line-1 font-sans font-semibold text-4xl md:text-5xl lg:text-6xl tracking-tight-custom text-preset-bg/90">
            {HERO_NOUN} is the
          </span>
          <span className="hero-line-2 font-drama italic text-7xl md:text-9xl lg:text-[11rem] leading-[0.85] text-preset-accent pr-10">
            {HERO_POWER}.
          </span>
        </h1>

        <p className="hero-desc mt-8 md:mt-12 text-lg md:text-xl font-mono text-preset-bg/70 max-w-lg leading-relaxed">
          Building production-grade applications that blend complex logic with cinematic execution.
        </p>

        <div className="hero-cta mt-10">
          <button
            onClick={() => document.getElementById('contact')?.scrollIntoView({ behavior: 'smooth' })}
            className="magnetic-btn bg-preset-bg text-preset-text px-8 py-4 rounded-full font-bold inline-flex items-center gap-2 group transition-all"
          >
            {PRIMARY_CTA}
            <svg className="w-5 h-5 group-hover:translate-x-1 transition-transform" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M5 12h14" /><path d="m12 5 7 7-7 7" /></svg>
          </button>
        </div>
      </div>
    </section>
  );
}

// ============================================
// C. FEATURES - "Interactive Functional Artifacts"
// ============================================

// C1. Diagnostic Shuffler
function DiagnosticShuffler() {
  const [items, setItems] = useState(SHUFFLER_ITEMS);
  const containerRef = useRef(null);

  useEffect(() => {
    const interval = setInterval(() => {
      setItems(prev => {
        const newArr = [...prev];
        const last = newArr.pop();
        newArr.unshift(last);
        return newArr;
      });
    }, 3000);
    return () => clearInterval(interval);
  }, []);

  useLayoutEffect(() => {
    const ctx = gsap.context(() => {
      gsap.from(containerRef.current, { y: 50, opacity: 0, duration: 1, ease: 'power3.out', scrollTrigger: { trigger: containerRef.current, start: 'top 80%' } });
    });
    return () => ctx.revert();
  }, []);

  return (
    <div ref={containerRef} className="surface-card rounded-[2rem] p-8 h-96 relative overflow-hidden flex flex-col">
      <div className="mb-8">
        <h3 className="font-sans font-bold text-2xl text-preset-text">Full-Stack Architecture</h3>
        <p className="font-mono text-sm text-preset-text/60 mt-2">Modern infrastructure loop</p>
      </div>

      <div className="relative flex-1 mt-4">
        {items.map((item, index) => {
          // Normalize position based on array index to handle visual stacking
          const isTop = index === 0;
          const isMiddle = index === 1;
          const isBottom = index === 2;

          let yOffset = isTop ? 0 : isMiddle ? 60 : 120;
          let scale = isTop ? 1 : isMiddle ? 0.95 : 0.9;
          let opacity = isTop ? 1 : isMiddle ? 0.6 : 0.3;
          let zIndex = isTop ? 30 : isMiddle ? 20 : 10;

          return (
            <div
              key={item.label}
              className="shuffler-card bg-white rounded-2xl p-6 border border-preset-primary/10 flex items-center gap-4 shadow-sm"
              style={{
                transform: `translateY(${yOffset}px) scale(${scale})`,
                opacity,
                zIndex
              }}
            >
              <div className="p-3 bg-preset-bg rounded-xl text-preset-accent">
                {item.icon}
              </div>
              <div>
                <h4 className="font-bold text-preset-text font-sans">{item.label}</h4>
                <p className="text-sm font-mono text-preset-text/60 mt-1">{item.desc}</p>
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

// C2. Telemetry Typewriter
function TelemetryTypewriter() {
  const [displayText, setDisplayText] = useState('');
  const [lineIndex, setLineIndex] = useState(0);
  const [charIndex, setCharIndex] = useState(0);
  const containerRef = useRef(null);

  useEffect(() => {
    const currentLine = TELEMETRY_LINES[lineIndex];
    let typingTimeout;

    if (charIndex < currentLine.length) {
      typingTimeout = setTimeout(() => {
        setDisplayText(currentLine.substring(0, charIndex + 1));
        setCharIndex(charIndex + 1);
      }, Math.random() * 30 + 30); // Fast chaotic tech typing
    } else {
      typingTimeout = setTimeout(() => {
        setCharIndex(0);
        setDisplayText('');
        setLineIndex((prev) => (prev + 1) % TELEMETRY_LINES.length);
      }, 2500); // Wait at end of line
    }

    return () => clearTimeout(typingTimeout);
  }, [charIndex, lineIndex]);

  useLayoutEffect(() => {
    const ctx = gsap.context(() => {
      gsap.from(containerRef.current, { y: 50, opacity: 0, duration: 1, ease: 'power3.out', delay: 0.1, scrollTrigger: { trigger: containerRef.current, start: 'top 80%' } });
    });
    return () => ctx.revert();
  }, []);

  return (
    <div ref={containerRef} className="surface-card rounded-[2rem] p-8 h-96 flex flex-col bg-preset-text text-preset-bg">
      <div className="flex justify-between items-start mb-auto">
        <div>
          <h3 className="font-sans font-bold text-2xl text-preset-bg">AI Integration</h3>
          <p className="font-mono text-sm text-preset-bg/60 mt-2">Vector embeddings & LLMs</p>
        </div>
        <div className="flex items-center gap-2 border border-preset-bg/20 rounded-full px-3 py-1">
          <div className="status-dot w-2 h-2"></div>
          <span className="font-mono text-xs uppercase pt-0.5 text-preset-bg/80">Live Feed</span>
        </div>
      </div>

      <div className="font-mono text-sm leading-relaxed text-preset-bg/80 mt-8 h-32 flex items-end">
        <div>
          <span className="text-preset-accent">{displayText}</span><span className="typewriter-cursor"></span>
        </div>
      </div>
    </div>
  );
}

// C3. Cursor Protocol Scheduler
function CursorProtocolScheduler() {
  const [activeCell, setActiveCell] = useState(null);
  const containerRef = useRef(null);
  const cursorRef = useRef(null);
  const saveBtnRef = useRef(null);

  const cells = [0, 1, 2, 3, 4, 5, 6, 7, 8];

  useEffect(() => {
    const tickTime = 3000;

    const interval = setInterval(() => {
      // 1. Pick a random cell
      const targetIndex = Math.floor(Math.random() * cells.length);
      const cellId = `grid-cell-${targetIndex}`;
      const cellEl = document.getElementById(cellId);

      if (!cellEl || !cursorRef.current || !saveBtnRef.current) return;

      const cellRect = cellEl.getBoundingClientRect();
      const saveRect = saveBtnRef.current.getBoundingClientRect();
      const containerRect = containerRef.current.getBoundingClientRect();

      // Calculate relative positions
      const cX = cellRect.left - containerRect.left + (cellRect.width / 2);
      const cY = cellRect.top - containerRect.top + (cellRect.height / 2);

      const sX = saveRect.left - containerRect.left + (saveRect.width / 2);
      const sY = saveRect.top - containerRect.top + (saveRect.height / 2);

      const tl = gsap.timeline();

      // Reset cursor position far off
      tl.set(cursorRef.current, { x: cX + 100, y: cY + 100, opacity: 0, scale: 1 });

      // Move to cell
      tl.to(cursorRef.current, { x: cX, y: cY, opacity: 1, duration: 0.6, ease: 'power2.out' })
        // "Click" animation
        .to(cursorRef.current, { scale: 0.8, duration: 0.1, yoyo: true, repeat: 1, onComplete: () => setActiveCell(targetIndex) })
        // Pause
        .to(cursorRef.current, { duration: 0.4 })
        // Move to save
        .to(cursorRef.current, { x: sX, y: sY, duration: 0.5, ease: 'power2.inOut' })
        // Click save
        .to(cursorRef.current, { scale: 0.8, duration: 0.1, yoyo: true, repeat: 1 })
        // Fade out
        .to(cursorRef.current, { opacity: 0, duration: 0.3, onComplete: () => setActiveCell(null) });

    }, tickTime);

    return () => clearInterval(interval);
  }, []);

  useLayoutEffect(() => {
    const ctx = gsap.context(() => {
      gsap.from(containerRef.current, { y: 50, opacity: 0, duration: 1, ease: 'power3.out', delay: 0.2, scrollTrigger: { trigger: containerRef.current, start: 'top 80%' } });
    });
    return () => ctx.revert();
  }, []);

  return (
    <div ref={containerRef} className="surface-card rounded-[2rem] p-8 h-96 relative">
      <h3 className="font-sans font-bold text-2xl text-preset-text">Cloud Protocol</h3>
      <p className="font-mono text-sm text-preset-text/60 mt-2 mb-8">Automated deployments</p>

      <div className="grid grid-cols-3 gap-3 mb-6">
        {cells.map((i) => (
          <div
            id={`grid-cell-${i}`}
            key={i}
            className={`h-12 rounded-xl transition-colors duration-300 border border-preset-primary/10 flex items-center justify-center
              ${activeCell === i ? 'bg-preset-accent text-white' : 'bg-white text-preset-text/30'}`}
          >
            <svg className="w-4 h-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M22 12h-4l-3 9L9 3l-3 9H2" /></svg>
          </div>
        ))}
      </div>

      <div className="flex justify-end mt-auto absolute bottom-8 right-8">
        <button ref={saveBtnRef} className="bg-preset-primary text-preset-bg text-xs font-mono px-4 py-2 rounded-lg">DEPLOY</button>
      </div>

      {/* SVG Fake Cursor */}
      <svg
        ref={cursorRef}
        className="absolute z-20 pointer-events-none opacity-0 drop-shadow-md"
        width="24" height="24" viewBox="0 0 24 24" fill="none"
        style={{ transformOrigin: 'top left' }}
      >
        <path d="M4 4L11.5 21L13.5 13.5L21 11.5L4 4Z" fill="#1A1A1A" stroke="#FFFFFF" strokeWidth="1.5" strokeLinejoin="round" />
      </svg>
    </div>
  );
}

function Features() {
  return (
    <section id="features" className="py-24 md:py-32 px-6 md:px-12 lg:px-24">
      <div className="max-w-7xl mx-auto">
        <div className="grid md:grid-cols-3 gap-6 md:gap-8">
          <DiagnosticShuffler />
          <TelemetryTypewriter />
          <CursorProtocolScheduler />
        </div>
      </div>
    </section>
  );
}

// ============================================
// PROJECT SHOWCASE
// ============================================
function ProjectShowcase() {
  const sectionRef = useRef(null);

  useLayoutEffect(() => {
    const ctx = gsap.context(() => {
      gsap.from('.project-heading', {
        y: 40,
        opacity: 0,
        duration: 0.8,
        ease: 'power3.out',
        scrollTrigger: { trigger: sectionRef.current, start: 'top 80%' }
      });
      gsap.from('.project-card-item', {
        y: 60,
        opacity: 0,
        stagger: 0.12,
        duration: 0.8,
        ease: 'power3.out',
        scrollTrigger: { trigger: '.project-grid', start: 'top 85%' }
      });
    }, sectionRef);
    return () => ctx.revert();
  }, []);

  const readinessConfig = {
    early: { dot: 'bg-red-500', ring: 'ring-red-500/30', text: 'text-red-600' },
    prototype: { dot: 'bg-yellow-500', ring: 'ring-yellow-500/30', text: 'text-yellow-600' },
    production: { dot: 'bg-green-500', ring: 'ring-green-500/30', text: 'text-green-600' },
  };

  return (
    <section ref={sectionRef} id="projects" className="py-24 md:py-32 px-6 md:px-12 lg:px-24 bg-preset-text">
      <div className="max-w-7xl mx-auto">
        {/* Section Header */}
        <div className="project-heading mb-16">
          <p className="font-mono uppercase tracking-widest text-preset-bg/40 text-sm mb-4">Live Portfolio</p>
          <h2 className="font-sans font-bold text-4xl md:text-6xl text-preset-bg tracking-tight-custom">
            7 Projects. <span className="font-drama italic font-normal text-preset-accent">All Live.</span>
          </h2>
          <p className="font-mono text-preset-bg/50 text-sm mt-4 max-w-lg">
            Each project runs on its own subdomain via Cloudflare Tunnel with global edge distribution.
          </p>
        </div>

        {/* Project Grid */}
        <div className="project-grid grid md:grid-cols-2 lg:grid-cols-3 gap-6">
          {PROJECTS.map((project, index) => {
            const rc = readinessConfig[project.readiness] || readinessConfig.prototype;
            return (
              <a
                key={project.name}
                href={project.url}
                target="_blank"
                rel="noopener noreferrer"
                className="project-card-item group block bg-preset-bg rounded-[2rem] p-8 border border-preset-primary/5 transition-all duration-500 hover:shadow-2xl hover:-translate-y-2 hover:border-preset-accent/20"
              >
                {/* Top Row: Icon + Readiness */}
                <div className="flex items-start justify-between mb-6">
                  <div className="w-12 h-12 rounded-2xl bg-preset-text/5 flex items-center justify-center group-hover:bg-preset-accent/10 transition-colors">
                    {project.icon}
                  </div>
                  <div className={`flex items-center gap-1.5 px-2.5 py-1 rounded-full ring-1 ${rc.ring}`}>
                    <div className={`w-2 h-2 rounded-full ${rc.dot}`} />
                    <span className={`font-mono text-[10px] uppercase tracking-wider ${rc.text}`}>{project.readinessLabel}</span>
                  </div>
                </div>

                <div className="mb-4">
                  <h3 className="font-sans font-bold text-2xl text-preset-text group-hover:text-preset-accent transition-colors">
                    {project.name}
                  </h3>
                  <span className="font-mono text-xs text-preset-text/50 uppercase tracking-wider">{project.subtitle}</span>
                </div>

                {/* Description */}
                <p className="text-preset-text/60 text-sm leading-relaxed mb-6">{project.desc}</p>

                {/* Features List */}
                <div className="space-y-2 mb-6">
                  {project.features.map((feat, i) => (
                    <div key={i} className="flex items-center gap-2 text-preset-text/70 text-xs font-mono">
                      <span className="text-preset-accent">▸</span>
                      {feat}
                    </div>
                  ))}
                </div>

                {/* Launch Link */}
                <div className="flex items-center gap-2 font-mono text-sm text-preset-accent group-hover:gap-3 transition-all">
                  {project.url !== '#' ? 'Launch App' : 'Local Only'}
                  <svg className="w-4 h-4 group-hover:translate-x-1 transition-transform" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M5 12h14" /><path d="m12 5 7 7-7 7" /></svg>
                </div>
              </a>
            );
          })}
        </div>
      </div>
    </section>
  );
}

// ============================================
// D. PHILOSOPHY - "The Manifesto"
// ============================================
function Philosophy() {
  const sectionRef = useRef(null);

  useLayoutEffect(() => {
    const ctx = gsap.context(() => {
      // Parallax Background
      gsap.to('.philosophy-bg', {
        yPercent: 30,
        ease: 'none',
        scrollTrigger: {
          trigger: sectionRef.current,
          start: 'top bottom',
          end: 'bottom top',
          scrub: true
        }
      });

      // SplitText style reveal (using stagger on wrapped lines)
      gsap.from('.ph-line', {
        y: 40,
        opacity: 0,
        stagger: 0.15,
        duration: 1,
        ease: 'power3.out',
        scrollTrigger: {
          trigger: '.ph-content',
          start: 'top 75%'
        }
      });
    }, sectionRef);
    return () => ctx.revert();
  }, []);

  return (
    <section ref={sectionRef} id="philosophy" className="relative py-40 px-6 md:px-12 lg:px-24 bg-preset-text overflow-hidden">
      {/* Organic Texture Parallax Background */}
      <div
        className="philosophy-bg absolute inset-0 opacity-15 mix-blend-luminosity scale-110"
        style={{
          backgroundImage: 'url("https://images.unsplash.com/photo-1542273917363-3b1817fac697?q=80&w=2074")',
          backgroundSize: 'cover',
          backgroundPosition: 'center',
          height: '130%' // Extra height for parallax travel
        }}
      />

      <div className="relative z-10 ph-content max-w-4xl mx-auto text-preset-bg">
        <div className="overflow-hidden mb-4">
          <p className="ph-line font-mono uppercase tracking-widest text-preset-bg/60 text-sm mb-8">The Manifesto</p>
        </div>

        <div className="overflow-hidden mb-8">
          <p className="ph-line font-sans text-xl md:text-3xl text-preset-bg/70 leading-relaxed font-light">
            Most digital agencies focus on: <span className="text-preset-bg font-normal">static deliverables.</span>
          </p>
        </div>

        <div className="overflow-hidden">
          <p className="ph-line font-drama italic text-4xl md:text-6xl lg:text-8xl leading-none">
            We focus on: <br />
            <span className="text-preset-accent not-italic font-sans font-bold tracking-tight-custom pr-4">intelligent</span>
            infrastructure.
          </p>
        </div>
      </div>
    </section>
  );
}

// ============================================
// E. PROTOCOL - "Sticky Stacking Archive"
// ============================================
function Protocol() {
  const containerRef = useRef(null);

  useLayoutEffect(() => {
    // We delay the ScrollTrigger setup slightly to ensure React has fully rendered the DOM and Tailwind CSS is applied.
    const timer = setTimeout(() => {
      const ctx = gsap.context(() => {
        const cards = gsap.utils.toArray('.protocol-card');

        cards.forEach((card, i) => {
          ScrollTrigger.create({
            trigger: card,
            start: 'top top',
            end: '+=100%',
            pin: true,
            pinSpacing: false,
            scrub: true,
            animation: gsap.to(card, {
              scale: 0.9,
              opacity: 0.5,
              filter: 'blur(20px)',
              ease: 'none'
            })
          });
        });
        ScrollTrigger.refresh();
      }, containerRef);
      return () => ctx.revert();
    }, 100);
    return () => clearTimeout(timer);
  }, []);

  return (
    <section ref={containerRef} id="protocol" className="relative bg-preset-bg pb-24">
      {PROTOCOL_STEPS.map((step, index) => (
        <div key={step.id} className="protocol-card h-[100dvh] w-full flex items-center justify-center sticky top-0 px-6" style={{ zIndex: index }}>
          <div className="bg-preset-bg border border-preset-primary/10 w-full max-w-5xl rounded-[3rem] p-12 md:p-24 shadow-2xl flex flex-col md:flex-row gap-12 items-center">

            {/* Visual Abstract side based on step */}
            <div className="w-full md:w-1/2 aspect-square bg-preset-text/5 rounded-3xl flex items-center justify-center relative overflow-hidden">
              {index === 0 && <svg className="w-32 h-32 text-preset-accent opacity-50 stroke-1" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1" strokeLinecap="round" strokeLinejoin="round"><polyline points="4 17 10 11 4 5" /><line x1="12" x2="20" y1="19" y2="19" /></svg>}
              {index === 1 && <svg className="w-32 h-32 text-preset-accent opacity-50 stroke-1" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1" strokeLinecap="round" strokeLinejoin="round"><rect width="16" height="16" x="4" y="4" rx="2" /><rect width="6" height="6" x="9" y="9" rx="1" /><path d="M15 2v2" /><path d="M15 20v2" /><path d="M2 15h2" /><path d="M2 9h2" /><path d="M20 15h2" /><path d="M20 9h2" /><path d="M9 2v2" /><path d="M9 20v2" /></svg>}
              {index === 2 && <svg className="w-32 h-32 text-preset-accent opacity-50 stroke-1" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1" strokeLinecap="round" strokeLinejoin="round"><rect width="18" height="11" x="3" y="11" rx="2" ry="2" /><path d="M7 11V7a5 5 0 0 1 10 0v4" /></svg>}

              {/* Minimal geometric decoration */}
              <div className="absolute top-8 left-8 text-preset-primary/20 font-mono text-xs">SYS.REQ.{step.id}</div>
            </div>

            {/* Content side */}
            <div className="w-full md:w-1/2">
              <span className="font-mono text-preset-accent text-lg mb-6 block">Phase {step.id}</span>
              <h2 className="font-serif font-bold font-sans text-4xl md:text-5xl text-preset-text mb-6">{step.title}</h2>
              <p className="text-preset-text/70 text-lg leading-relaxed font-sans">{step.desc}</p>
            </div>

          </div>
        </div>
      ))}
    </section>
  );
}

// ============================================
// F. MEMBERSHIP / CALL TO ACTION
// ============================================
function Engagement() {
  const sectionRef = useRef(null);

  useLayoutEffect(() => {
    const ctx = gsap.context(() => {
      gsap.from('.cta-content', {
        y: 50,
        opacity: 0,
        duration: 1,
        ease: 'power3.out',
        scrollTrigger: {
          trigger: sectionRef.current,
          start: 'top 75%'
        }
      });
    }, sectionRef);
    return () => ctx.revert();
  }, []);

  return (
    <section ref={sectionRef} id="contact" className="py-40 px-6 md:px-12 lg:px-24 flex items-center justify-center">
      <div className="cta-content text-center max-w-2xl">
        <h2 className="font-drama italic text-6xl md:text-8xl text-preset-text mb-8">
          The Future is <br /><span className="font-sans font-bold not-italic text-preset-accent">Now.</span>
        </h2>
        <div className="mt-12">
          <button className="magnetic-btn bg-preset-text text-preset-bg px-10 py-5 rounded-full font-bold text-xl inline-flex items-center gap-3 group">
            <svg className="w-5 h-5" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect width="18" height="11" x="3" y="11" rx="2" ry="2" /><path d="M7 11V7a5 5 0 0 1 10 0v4" /></svg>
            {PRIMARY_CTA}
          </button>
        </div>
        <p className="font-mono text-sm text-preset-text/50 mt-8 uppercase tracking-widest">Client intake currently closed.</p>
      </div>
    </section>
  );
}

// ============================================
// G. FOOTER
// ============================================
function Footer() {
  return (
    <footer className="bg-preset-text rounded-t-[4rem] px-6 md:px-12 lg:px-24 pt-24 pb-12 mt-12 text-preset-bg">
      <div className="max-w-7xl mx-auto flex flex-col md:flex-row justify-between items-start md:items-end gap-12 border-b border-preset-bg/10 pb-12 mb-8">

        <div>
          <h3 className="font-sans font-bold text-3xl mb-4 tracking-tight-custom">{BRAND_NAME}</h3>
          <p className="font-mono text-preset-bg/50 text-sm max-w-sm leading-relaxed">
            Engineering digital experiences with cinematic precision and robust infrastructure.
          </p>
        </div>

        <div className="flex border border-preset-bg/20 rounded-full px-4 py-2 bg-preset-text/50 items-center justify-center gap-3 backdrop-blur-sm">
          <div className="status-dot"></div>
          <span className="font-mono text-xs uppercase text-preset-bg font-semibold pt-0.5">System Operational</span>
        </div>

      </div>

      <div className="max-w-7xl mx-auto flex flex-col md:flex-row justify-between items-center text-preset-bg/40 font-mono text-xs gap-4">
        <p>© {new Date().getFullYear()} {BRAND_NAME}. All rights reserved.</p>
        <div className="flex gap-6">
          <a href="#" className="hover:text-preset-bg transition-colors">Privacy</a>
          <a href="#" className="hover:text-preset-bg transition-colors">Terms</a>
          <a href="#" className="hover:text-preset-bg transition-colors">Contact</a>
        </div>
      </div>
    </footer>
  );
}

// ============================================
// MAIN APP MOUNT
// ============================================
function App() {
  useEffect(() => {
    // Global ScrollTrigger refresh to handle image loads and Font loading shifts
    const timer = setTimeout(() => {
      ScrollTrigger.refresh();
      // Force scroll to top on load for best experience
      window.scrollTo(0, 0);
    }, 1000);
    return () => clearTimeout(timer);
  }, []);

  return (
    <div className="font-sans">
      <Navbar />
      <main>
        <Hero />
        <Features />
        <ProjectShowcase />
        <Philosophy />
        <Protocol />
        <Engagement />
      </main>
      <Footer />
    </div>
  );
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);
