/* global React, Reveal, useReveal, SplitReveal */
const { useEffect, useState, useRef } = React;

function Features() {
  return (
    <section id="services" data-screen-label="03 Services" style={{ padding: '140px clamp(20px,4vw,48px) 120px', background: '#fff', position: 'relative', overflow: 'hidden' }}>
      {/* Subtle animated gradient blob */}
      <FloatingBlob top="5%" left="70%" size={480} color="rgba(91,169,163,0.08)" />
      <FloatingBlob top="55%" left="-10%" size={420} color="rgba(58,123,184,0.08)" delay={2000} />

      <div style={{ position: 'relative', maxWidth: 1200, margin: '0 auto' }}>
        {/* Section header */}
        <Reveal y={14}>
          <div style={{ fontFamily: 'var(--font-mono)', fontSize: 11.5, letterSpacing: '0.14em', textTransform: 'uppercase', color: '#3A7BB8', marginBottom: 20, display: 'flex', alignItems: 'center', gap: 10 }}>
            <AnimatedDash /> Services
          </div>
        </Reveal>
        <h2 style={{ fontSize: 'clamp(40px,5vw,72px)', fontWeight: 600, letterSpacing: '-0.035em', lineHeight: 1.0, margin: 0, maxWidth: 880, color: '#0B1220' }}>
          <div>
            <SplitReveal text="Backend and cloud," delay={200} step={45} />
          </div>
          <div>
            <SplitReveal text="done right." delay={450} step={45} style={{ color: '#8695A8', fontStyle: 'italic', fontWeight: 400 }} />
          </div>
        </h2>
        <Reveal y={12} delay={600}>
          <p style={{ fontSize: 18, lineHeight: 1.55, color: '#5F6E82', maxWidth: 620, marginTop: 24 }}>
            Three things we do deeply, not twelve things we do shallowly. Every engagement is led by a senior engineer who's shipped the thing you're asking for - not supervised someone else shipping it.
          </p>
        </Reveal>

        {/* Feature cards */}
        <div className="nal-feat-grid" style={{ marginTop: 72, display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 20 }}>
          <div style={{ gridColumn: 'span 2' }}>
            <FeatureCard
              n="01" tag="BACKEND"
              title="APIs and services that hold up"
              body="Type-safe, observable, and boringly reliable. We design the contract first, then the code. Every endpoint ships with tests, metrics, and the runbook you'd actually read."
              bullets={['TypeScript + Node.js', 'Python + FastAPI', 'Go + gRPC']}
              demo={<BackendDemo />}
              wide
            />
          </div>
          <FeatureCard
            n="02" tag="CLOUD"
            title="Production-grade cloud, provisioned as code"
            body="Terraform-first. Predictable bills. IAM that isn't a disaster. We set up AWS and GCP the way you wish someone had before."
            bullets={['AWS · ECS · Lambda · RDS', 'GCP · Cloud Run · GKE', 'Terraform · CI/CD · IAM']}
            demo={<CloudDemo />}
          />
          <FeatureCard
            n="03" tag="EXPERIENCE"
            title="10+ years. Senior hands only."
            body="No juniors we're quietly training on your project. Every line written and every review done by someone who's shipped this before."
            bullets={['Fixed-scope · retainer · staff aug', 'Architecture reviews', 'Migration & deprecation']}
            demo={<ExperienceDemo />}
          />
        </div>
      </div>
    </section>
  );
}

function AnimatedDash() {
  const [ref, inView] = useReveal({ threshold: 0.5 });
  return (
    <span ref={ref} style={{
      width: inView ? 22 : 0, height: 1, background: '#3A7BB8',
      transition: 'width 700ms cubic-bezier(.16,1,.3,1)',
      display: 'inline-block',
    }} />
  );
}

function FloatingBlob({ top, left, size, color, delay = 0 }) {
  return (
    <div style={{
      position: 'absolute', top, left, width: size, height: size, borderRadius: '50%',
      background: `radial-gradient(circle, ${color} 0%, transparent 70%)`,
      filter: 'blur(24px)', pointerEvents: 'none',
      animation: `nal-float 14s ease-in-out ${delay}ms infinite`,
    }} />
  );
}

function FeatureCard({ n, tag, title, body, bullets, demo, wide }) {
  const [ref, inView] = useReveal();
  const [hover, setHover] = useState(false);
  return (
    <div
      ref={ref}
      data-nal="feat-card"
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => setHover(false)}
      style={{
        opacity: inView ? 1 : 0,
        transform: inView ? 'translate3d(0,0,0)' : 'translate3d(0,36px,0)',
        transition: 'opacity 900ms cubic-bezier(.16,1,.3,1), transform 900ms cubic-bezier(.16,1,.3,1), border-color 300ms, box-shadow 300ms',
        background: '#fff', border: `1px solid ${hover ? '#B6C2CF' : '#EEF2F6'}`,
        borderRadius: 20,
        boxShadow: hover ? '0 28px 64px rgba(14,22,38,0.10)' : '0 1px 0 rgba(14,22,38,0.02)',
        overflow: 'hidden', position: 'relative',
        display: wide ? 'grid' : 'flex',
        gridTemplateColumns: wide ? '1fr 1.15fr' : undefined,
        flexDirection: wide ? undefined : 'column',
      }}
    >
      {/* Subtle shimmer on hover */}
      <div style={{
        position: 'absolute', inset: 0, pointerEvents: 'none', borderRadius: 20,
        background: 'linear-gradient(120deg, transparent 40%, rgba(58,123,184,0.06) 50%, transparent 60%)',
        backgroundSize: '200% 100%',
        backgroundPosition: hover ? '-100% 0' : '100% 0',
        transition: 'background-position 1200ms cubic-bezier(.16,1,.3,1)',
      }} />

      <div style={{ padding: wide ? '44px' : '36px 32px 28px', display: 'flex', flexDirection: 'column', position: 'relative' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, fontFamily: 'var(--font-mono)', fontSize: 11, letterSpacing: '0.14em', color: '#8695A8', marginBottom: 22 }}>
          <span style={{ color: '#0B1220', fontWeight: 600 }}>{n}</span>
          <span style={{ width: 18, height: 1, background: '#D9E0E8' }} />
          <span>{tag}</span>
        </div>
        <div style={{ fontWeight: 600, fontSize: wide ? 32 : 24, lineHeight: 1.1, color: '#0B1220', letterSpacing: '-0.025em', marginBottom: 16 }}>{title}</div>
        <p style={{ fontSize: 15, lineHeight: 1.6, color: '#3E4B5E', margin: 0, marginBottom: 24, maxWidth: 440 }}>{body}</p>
        <ul style={{ listStyle: 'none', padding: 0, margin: 0, marginTop: 'auto', display: 'flex', flexDirection: 'column', gap: 8 }}>
          {bullets.map((b, i) => (
            <li key={i} style={{
              fontFamily: 'var(--font-mono)', fontSize: 13, color: '#3E4B5E', display: 'flex', alignItems: 'center', gap: 10,
              opacity: inView ? 1 : 0,
              transform: inView ? 'translateX(0)' : 'translateX(-10px)',
              transition: `opacity 500ms cubic-bezier(.16,1,.3,1) ${400 + i * 100}ms, transform 500ms cubic-bezier(.16,1,.3,1) ${400 + i * 100}ms`,
            }}>
              <span style={{ width: 5, height: 5, background: '#5BA9A3', borderRadius: 999 }} />
              {b}
            </li>
          ))}
        </ul>
      </div>
      <div style={{
        background: '#F7F9FB',
        borderLeft: wide ? '1px solid #EEF2F6' : 'none',
        borderTop: wide ? 'none' : '1px solid #EEF2F6',
        padding: wide ? 32 : 24,
        minHeight: wide ? 340 : 260,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        position: 'relative', overflow: 'hidden',
      }}>
        {/* Dot grid inside demo area */}
        <div style={{ position: 'absolute', inset: 0, backgroundImage: 'radial-gradient(circle, rgba(14,22,38,0.06) 1px, transparent 1.2px)', backgroundSize: '18px 18px', opacity: 0.6, pointerEvents: 'none' }} />
        <div style={{ position: 'relative', width: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          {React.cloneElement(demo, { active: true, inView })}
        </div>
      </div>
    </div>
  );
}

/* ---------- Mini demos ---------- */

// BACKEND — live request log with typing, method colors, moving latency bars
function BackendDemo({ inView }) {
  const [rows, setRows] = useState([
    { m: 'POST', p: '/api/orders',    s: 201, ms: 42 },
    { m: 'GET',  p: '/api/users/:id', s: 200, ms: 18 },
    { m: 'PUT',  p: '/api/cart',      s: 200, ms: 31 },
    { m: 'POST', p: '/api/payments',  s: 201, ms: 88 },
  ]);
  const [flash, setFlash] = useState(-1);

  useEffect(() => {
    if (!inView) return;
    const pool = [
      { m: 'GET',  p: '/api/health',       s: 200, ms: 4 },
      { m: 'GET',  p: '/api/products',     s: 200, ms: 22 },
      { m: 'POST', p: '/api/webhooks/stripe', s: 201, ms: 64 },
      { m: 'GET',  p: '/api/search?q=…',   s: 200, ms: 38 },
      { m: 'PUT',  p: '/api/users/:id',    s: 200, ms: 27 },
      { m: 'POST', p: '/api/orders',       s: 201, ms: 51 },
      { m: 'DELETE', p: '/api/sessions/:t', s: 204, ms: 11 },
    ];
    const id = setInterval(() => {
      const next = pool[Math.floor(Math.random() * pool.length)];
      setRows(r => [next, ...r.slice(0, 3)]);
      setFlash(0);
      setTimeout(() => setFlash(-1), 400);
    }, 1800);
    return () => clearInterval(id);
  }, [inView]);

  const methodColor = (m) => ({ GET: '#3A7BB8', POST: '#2E9D6E', PUT: '#D4A13A', DELETE: '#D14343' }[m] || '#5F6E82');

  return (
    <div data-nal="api-log" style={{
      width: '100%', maxWidth: 440,
      background: '#fff', border: '1px solid #EEF2F6', borderRadius: 14,
      overflow: 'hidden', fontFamily: 'var(--font-mono)', fontSize: 12,
      boxShadow: '0 12px 36px rgba(14,22,38,0.06)',
    }}>
      <div style={{ padding: '10px 14px', background: '#F7F9FB', borderBottom: '1px solid #EEF2F6', display: 'flex', alignItems: 'center', justifyContent: 'space-between', fontSize: 11, color: '#5F6E82', letterSpacing: '0.04em' }}>
        <span>api.acme.com · /api/*</span>
        <span style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
          <span style={{ width: 6, height: 6, background: '#2E9D6E', borderRadius: 999, animation: 'nal-pulse 1.4s ease-in-out infinite' }} />
          live
        </span>
      </div>
      <div style={{ position: 'relative', minHeight: 170 }}>
        {rows.map((l, i) => (
          <div key={`${l.p}-${i}-${rows[0].p}`} style={{
            padding: '10px 14px', display: 'grid',
            gridTemplateColumns: '52px 1fr auto auto',
            gap: 10, alignItems: 'center',
            borderBottom: i === rows.length - 1 ? 'none' : '1px solid #F7F9FB',
            background: flash === i ? '#E8F1F9' : 'transparent',
            transition: 'background 700ms',
            animation: flash === i ? 'nal-fade-up 420ms cubic-bezier(.16,1,.3,1)' : 'none',
          }}>
            <span style={{ color: methodColor(l.m), fontWeight: 600 }}>{l.m}</span>
            <span style={{ color: '#0B1220', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{l.p}</span>
            <span style={{ color: l.s < 300 ? '#2E9D6E' : '#D4A13A', fontWeight: 500 }}>{l.s}</span>
            <span style={{ color: '#8695A8' }}>{l.ms}ms</span>
          </div>
        ))}
      </div>
      <div style={{ padding: '10px 14px', background: '#F7F9FB', borderTop: '1px solid #EEF2F6', display: 'flex', justifyContent: 'space-between', fontSize: 11, color: '#5F6E82' }}>
        <span>p50 · 32ms</span><span>p99 · 118ms</span><span>err · 0.02%</span>
      </div>
    </div>
  );
}

// CLOUD — region map with continuous pulsing traffic arcs
function CloudDemo({ inView }) {
  const [phase, setPhase] = useState(0);
  useEffect(() => {
    if (!inView) return;
    const id = setInterval(() => setPhase(p => (p + 1) % 3), 1600);
    return () => clearInterval(id);
  }, [inView]);
  const regions = [
    { x: 68, y: 88, label: 'us-east-1' },
    { x: 165, y: 74, label: 'eu-west-1' },
    { x: 234, y: 96, label: 'ap-south-1' },
  ];
  return (
    <svg viewBox="0 0 300 180" style={{ width: '100%', height: 'auto', maxWidth: 360 }}>
      <defs>
        <linearGradient id="arc-grad" x1="0" y1="0" x2="1" y2="0">
          <stop offset="0%" stopColor="#3A7BB8" stopOpacity="0" />
          <stop offset="50%" stopColor="#3A7BB8" stopOpacity="1" />
          <stop offset="100%" stopColor="#3A7BB8" stopOpacity="0" />
        </linearGradient>
      </defs>

      {/* dotted world */}
      <g opacity="0.3">
        {Array.from({ length: 22 }).map((_, r) =>
          Array.from({ length: 36 }).map((__, c) => {
            const x = 20 + c * 7.5, y = 20 + r * 6;
            const noise = Math.sin((c * 7 + r * 13)) * Math.cos(c * 1.3 + r);
            if (noise < -0.2) return null;
            return <circle key={`${r}-${c}`} cx={x} cy={y} r={0.9} fill="#8695A8" />;
          })
        )}
      </g>

      {/* Arcs between regions */}
      {regions.map((r, i) => {
        const next = regions[(i + 1) % regions.length];
        const mx = (r.x + next.x) / 2;
        const my = Math.min(r.y, next.y) - 35;
        const d = `M ${r.x} ${r.y} Q ${mx} ${my} ${next.x} ${next.y}`;
        const activeArc = phase === i;
        return (
          <g key={i}>
            <path d={d} stroke="#D9E0E8" strokeWidth="1" fill="none" />
            <path d={d} stroke="url(#arc-grad)" strokeWidth="2" fill="none"
              strokeDasharray="60 400"
              strokeDashoffset={activeArc ? -400 : 60}
              style={{ transition: activeArc ? 'stroke-dashoffset 1500ms linear' : 'none' }}
            />
          </g>
        );
      })}

      {/* Region pins */}
      {regions.map((r, i) => (
        <g key={i}>
          <circle cx={r.x} cy={r.y} r="14" fill="#3A7BB8" opacity="0.08">
            <animate attributeName="r" values="10;18;10" dur="2.4s" repeatCount="indefinite" begin={`${i * 0.6}s`} />
            <animate attributeName="opacity" values="0.2;0;0.2" dur="2.4s" repeatCount="indefinite" begin={`${i * 0.6}s`} />
          </circle>
          <circle cx={r.x} cy={r.y} r="5" fill="#3A7BB8" />
          <circle cx={r.x} cy={r.y} r="2.2" fill="#fff" />
          <text x={r.x} y={r.y + 22} textAnchor="middle" fontSize="8" fontFamily="var(--font-mono)" fill="#5F6E82">{r.label}</text>
        </g>
      ))}

      {/* Rolling ticker at bottom */}
      <g transform="translate(14, 160)">
        <text fontSize="8" fontFamily="var(--font-mono)" fill="#8695A8">
          deploy/
          <tspan fill="#2E9D6E">
            ● all green
            <animate attributeName="opacity" values="1;0.3;1" dur="1.4s" repeatCount="indefinite" />
          </tspan>
          <tspan dx="10" fill="#5F6E82">· 3 regions · 12 services</tspan>
        </text>
      </g>
    </svg>
  );
}

// EXPERIENCE — timeline + count-up years + scrolling "shipped" items
function ExperienceDemo({ inView }) {
  const years = ['2014', '2016', '2018', '2020', '2022', '2024'];
  const shipped = [
    'payments gateway',
    'multi-region db migration',
    'observability platform',
    'k8s lift-and-shift',
    'event-driven rewrite',
    'zero-downtime cutover',
  ];
  const [idx, setIdx] = useState(0);
  useEffect(() => {
    if (!inView) return;
    const id = setInterval(() => setIdx(i => (i + 1) % shipped.length), 1800);
    return () => clearInterval(id);
  }, [inView]);
  return (
    <div style={{ width: '100%', padding: '10px 0' }}>
      {/* Timeline */}
      <div style={{ position: 'relative', height: 100, display: 'flex', alignItems: 'center', marginBottom: 14 }}>
        <div style={{ position: 'absolute', left: 0, right: 0, top: '50%', height: 1, background: '#D9E0E8' }} />
        <div style={{
          position: 'absolute', left: 0, top: '50%', height: 2, transform: 'translateY(-50%)',
          background: 'linear-gradient(90deg,#5BA9A3,#3A7BB8)',
          width: inView ? '100%' : '0%',
          transition: 'width 2200ms cubic-bezier(.16,1,.3,1) 200ms',
        }} />
        {years.map((y, i) => (
          <div key={y} style={{
            position: 'absolute', left: `${(i / (years.length - 1)) * 100}%`, top: '50%',
            transform: 'translate(-50%, -50%)',
            display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 8,
          }}>
            <span style={{ fontFamily: 'var(--font-mono)', fontSize: 10, color: '#8695A8', opacity: inView ? 1 : 0, transition: `opacity 400ms ${400 + i * 120}ms` }}>{y}</span>
            <span style={{
              width: 10, height: 10, background: '#fff',
              border: `2px solid ${inView ? '#3A7BB8' : '#D9E0E8'}`,
              borderRadius: 999,
              transition: `border-color 400ms ${400 + i * 120}ms, transform 400ms ${400 + i * 120}ms`,
              transform: inView ? 'scale(1)' : 'scale(0.6)',
            }} />
          </div>
        ))}
      </div>

      {/* Rotating "shipped" line */}
      <div style={{ background: '#fff', border: '1px solid #EEF2F6', borderRadius: 10, padding: '14px 16px', overflow: 'hidden' }}>
        <div style={{ fontFamily: 'var(--font-mono)', fontSize: 10.5, color: '#8695A8', letterSpacing: '0.12em', marginBottom: 8 }}>LAST SHIPPED</div>
        <div style={{ position: 'relative', height: 20, overflow: 'hidden' }}>
          {shipped.map((s, i) => (
            <div key={s} style={{
              position: 'absolute', inset: 0,
              fontSize: 14, color: '#0B1220', fontFamily: 'var(--font-mono)',
              transform: `translateY(${(i - idx) * 22}px)`,
              opacity: i === idx ? 1 : 0,
              transition: 'transform 600ms cubic-bezier(.16,1,.3,1), opacity 400ms',
            }}>
              <span style={{ color: '#2E9D6E' }}>✓</span> {s}
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

window.Features = Features;
