// Hero with animated dot-grid canvas, parallax, floating tech panels
function HeroCanvas() {
  const ref = React.useRef(null);
  React.useEffect(() => {
    const canvas = ref.current;
    if (!canvas) return;
    const ctx = canvas.getContext('2d');
    let w,h,dpr = Math.min(window.devicePixelRatio || 1, 2);
    let mouse = { x: 0.5, y: 0.4, tx: 0.5, ty: 0.4 };
    let raf;

    function resize() {
      w = canvas.clientWidth;h = canvas.clientHeight;
      canvas.width = w * dpr;canvas.height = h * dpr;
      ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
    }
    resize();
    window.addEventListener('resize', resize);

    const onMove = (e) => {
      const r = canvas.getBoundingClientRect();
      mouse.tx = (e.clientX - r.left) / r.width;
      mouse.ty = (e.clientY - r.top) / r.height;
    };
    window.addEventListener('mousemove', onMove);

    const spacing = 40;
    let t = 0;
    function frame() {
      mouse.x += (mouse.tx - mouse.x) * 0.06;
      mouse.y += (mouse.ty - mouse.y) * 0.06;
      ctx.clearRect(0, 0, w, h);
      t += 0.012;

      const cols = Math.ceil(w / spacing) + 1;
      const rows = Math.ceil(h / spacing) + 1;
      const mx = mouse.x * w;
      const my = mouse.y * h;

      for (let i = 0; i < cols; i++) {
        for (let j = 0; j < rows; j++) {
          const x = i * spacing;
          const y = j * spacing;
          const dx = x - mx,dy = y - my;
          const dist = Math.sqrt(dx * dx + dy * dy);
          const wave = Math.sin(dist * 0.012 - t * 1.6) * 0.5 + 0.5;
          const falloff = Math.max(0, 1 - dist / 520);
          const alpha = 0.06 + wave * 0.18 * falloff;
          const size = 1 + falloff * 1.6;

          if (falloff > 0.05) {
            ctx.fillStyle = `rgba(255, 46, 77, ${alpha * 0.8})`;
          } else {
            ctx.fillStyle = `rgba(180, 180, 200, ${0.05 + wave * 0.04})`;
          }
          ctx.beginPath();
          ctx.arc(x, y, size, 0, Math.PI * 2);
          ctx.fill();
        }
      }

      ctx.save();
      const grad = ctx.createLinearGradient(0, 0, w, h);
      grad.addColorStop(0, 'rgba(255,46,77,0)');
      grad.addColorStop(0.5, 'rgba(255,46,77,0.10)');
      grad.addColorStop(1, 'rgba(92,240,255,0)');
      ctx.fillStyle = grad;
      ctx.globalCompositeOperation = 'lighter';
      ctx.fillRect(0, 0, w, h);
      ctx.restore();

      raf = requestAnimationFrame(frame);
    }
    frame();
    return () => {
      cancelAnimationFrame(raf);
      window.removeEventListener('resize', resize);
      window.removeEventListener('mousemove', onMove);
    };
  }, []);
  return <canvas id="hero-canvas" ref={ref} />;
}

function ScrambleWord({ text, delay = 0 }) {
  const [out, setOut] = React.useState(text);
  React.useEffect(() => {
    const chars = "ABCDEF0123456789#$&*";
    let frame = 0;
    const total = 18;
    const start = setTimeout(() => {
      const id = setInterval(() => {
        frame++;
        const reveal = Math.floor(frame / total * text.length);
        const next = text.split('').map((c, i) => {
          if (c === ' ') return ' ';
          if (i < reveal) return c;
          return chars[Math.floor(Math.random() * chars.length)];
        }).join('');
        setOut(next);
        if (frame >= total) {clearInterval(id);setOut(text);}
      }, 38);
    }, delay);
    return () => clearTimeout(start);
  }, [text, delay]);
  return <span className="mono" style={{ color: 'var(--cyan)', fontSize: '0.42em', letterSpacing: '0.06em', verticalAlign: 'middle', marginLeft: 14 }}>{out}</span>;
}

/* ===== HERO SIDE — animated, interactive tech panels ===== */

// Typing code block — cycles through lines being written
function TypingCode() {
  const lines = React.useMemo(() => [
  { jsx: <><span className="tok-c">// 666/ws — production endpoint</span></>, plain: '// 666/ws — production endpoint' },
  { jsx: <><span className="tok-k">export const</span> <span className="tok-f">deploy</span> = <span className="tok-k">async</span> () =&gt; {'{'}</>, plain: "export const deploy = async () => {" },
  { jsx: <>&nbsp;&nbsp;<span className="tok-k">const</span> r = <span className="tok-k">await</span> <span className="tok-f">build</span>({'{'} <span className="tok-n">target</span>: <span className="tok-s">'edge'</span> {'}'});</>, plain: "  const r = await build({ target: 'edge' });" },
  { jsx: <>&nbsp;&nbsp;<span className="tok-k">await</span> <span className="tok-f">ship</span>(r, <span className="tok-s">'asia-southeast1'</span>);</>, plain: "  await ship(r, 'asia-southeast1');" },
  { jsx: <>&nbsp;&nbsp;<span className="tok-k">return</span> {'{'} <span className="tok-n">ok</span>: <span className="tok-k">true</span> {'}'};</>, plain: "  return { ok: true };" },
  { jsx: <>{'}'};</>, plain: "};" }],
  []);
  const [step, setStep] = React.useState(0);
  const [typed, setTyped] = React.useState(0); // chars typed of current line

  React.useEffect(() => {
    let cancelled = false;
    const lineLen = lines[step].plain.length;
    if (typed < lineLen) {
      const t = setTimeout(() => !cancelled && setTyped(typed + 1), 18 + Math.random() * 30);
      return () => {cancelled = true;clearTimeout(t);};
    }
    // line done; pause then advance
    const t = setTimeout(() => {
      if (cancelled) return;
      if (step < lines.length - 1) {
        setStep(step + 1);setTyped(0);
      } else {
        // restart after pause
        setStep(0);setTyped(0);
      }
    }, step === lines.length - 1 ? 2400 : 240);
    return () => {cancelled = true;clearTimeout(t);};
  }, [step, typed, lines]);

  return (
    <>
      {lines.map((ln, i) => {
        const fullyDone = i < step;
        const currentTyping = i === step;
        const future = i > step;
        if (future) return <div key={i} className="code-line" style={{ opacity: 0.15 }}>&nbsp;</div>;
        if (fullyDone) return <div key={i} className="code-line">{ln.jsx}</div>;
        // currentTyping — render plain prefix then caret
        const slice = ln.plain.slice(0, typed);
        return (
          <div key={i} className="code-line">
            <span style={{ whiteSpace: 'pre' }}>{slice}</span>
            <span className="caret">▎</span>
          </div>);

      })}
    </>);

}

// Lighthouse metrics — animate bars + score numbers wobble
function LiveMetrics() {
  const { t: tr } = useLang();
  const targets = [
  { lab: tr('hero.metric.performance'), t: 99, c: 'green' },
  { lab: tr('hero.metric.accessibility'), t: 100, c: 'green' },
  { lab: tr('hero.metric.bestpractices'), t: 100, c: 'green' },
  { lab: tr('hero.metric.seo'), t: 100, c: 'green' }];

  const [v, setV] = React.useState(targets.map(() => 0));
  React.useEffect(() => {
    let raf, start;
    const dur = 1600;
    const tick = (ts) => {
      if (!start) start = ts;
      const p = Math.min((ts - start) / dur, 1);
      const e = 1 - Math.pow(1 - p, 3);
      setV(targets.map((x) => x.t * e));
      if (p < 1) raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, []);
  return (
    <>
      {targets.map((x, i) =>
      <div key={x.lab} className="metric-row">
          <span className="lab">{x.lab}</span>
          <span className="val">
            <span className="b">{Math.round(v[i])}</span>
            <span style={{ color: 'var(--ink-mute)' }}> / 100</span>
          </span>
        </div>
      )}
      <div className="metric-bar">
        <div className="metric-bar-fill" />
        <div className="metric-bar-shine" />
      </div>
    </>);

}

// Deploy stages — cycle through running -> done, append new build
function DeployFeed() {
  const { t: tr } = useLang();
  const [tick, setTick] = React.useState(0);
  React.useEffect(() => {
    const id = setInterval(() => setTick((t) => t + 1), 1400);
    return () => clearInterval(id);
  }, []);
  // 4 stages with rotating "running" position
  const stages = [tr('hero.deploy.stage.build'), tr('hero.deploy.stage.tests'), tr('hero.deploy.stage.deploy'), tr('hero.deploy.stage.smoke')];
  const running = tick % (stages.length + 1); // sometimes "all done"
  const buildN = 4821 + Math.floor(tick / (stages.length + 1));
  return (
    <>
      <div className="panel-head">
        <div style={{ fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--ink-dim)' }}>DEPLOY #{buildN}</div>
        <div className="deploy-clock">
          <span className="live-dot" /> {tr('hero.panel.deploy.live')}
        </div>
      </div>
      {stages.map((s, i) => {
        const state = i < running ? 'done' : i === running ? 'running' : 'pending';
        return (
          <div key={i} className={'deploy-stage ' + (state === 'pending' ? 'pending' : state === 'running' ? 'running' : '')}>
            <span className="ck"></span>
            <span style={{ flex: 1 }}>{s}</span>
            {state === 'done' && <span className="deploy-time">✓</span>}
            {state === 'running' && <span className="deploy-time">…</span>}
          </div>);

      })}
    </>);

}

// 3D-tilt wrapper — tracks mouse over the hero-side container
function TiltStage({ children }) {
  const ref = React.useRef(null);
  React.useEffect(() => {
    const el = ref.current;
    if (!el) return;
    let target = { x: 0, y: 0 };
    let current = { x: 0, y: 0 };
    let raf;
    let inside = false;
    let floatT = 0;

    const onMove = (e) => {
      const r = el.getBoundingClientRect();
      const cx = r.left + r.width / 2;
      const cy = r.top + r.height / 2;
      // distance to center, clamped to a falloff radius
      const dx = (e.clientX - cx) / (r.width / 2);
      const dy = (e.clientY - cy) / (r.height / 2);
      target.x = Math.max(-1.2, Math.min(1.2, dx));
      target.y = Math.max(-1.2, Math.min(1.2, dy));
      inside = Math.abs(dx) < 1.6 && Math.abs(dy) < 1.6;
    };

    const tick = () => {
      current.x += (target.x - current.x) * 0.08;
      current.y += (target.y - current.y) * 0.08;
      floatT += 0.016;
      el.style.setProperty('--mx', current.x.toFixed(3));
      el.style.setProperty('--my', current.y.toFixed(3));
      el.style.setProperty('--ft', floatT.toFixed(3));
      el.style.setProperty('--active', inside ? 1 : 0);
      raf = requestAnimationFrame(tick);
    };
    window.addEventListener('mousemove', onMove);
    raf = requestAnimationFrame(tick);
    return () => {
      window.removeEventListener('mousemove', onMove);
      cancelAnimationFrame(raf);
    };
  }, []);
  return <div className="hero-side tilt-stage" ref={ref}>{children}</div>;
}

// Animated connection lines + circuit grid behind panels
function CircuitOverlay() {
  return (
    <svg className="circuit-bg" viewBox="0 0 500 520" preserveAspectRatio="none">
      <defs>
        <linearGradient id="line1" x1="0" x2="1" y1="0" y2="0">
          <stop offset="0" stopColor="rgba(255,46,77,0)" />
          <stop offset="0.5" stopColor="rgba(255,46,77,0.8)" />
          <stop offset="1" stopColor="rgba(255,46,77,0)" />
        </linearGradient>
        <linearGradient id="line2" x1="0" x2="1" y1="0" y2="0">
          <stop offset="0" stopColor="rgba(92,240,255,0)" />
          <stop offset="0.5" stopColor="rgba(92,240,255,0.7)" />
          <stop offset="1" stopColor="rgba(92,240,255,0)" />
        </linearGradient>
      </defs>
      {/* main circuit traces */}
      <path d="M 30 80 H 180 V 160 H 380 V 280 H 220 V 420 H 460"
      fill="none" stroke="rgba(255,255,255,0.08)" strokeWidth="1" />
      <path d="M 40 200 H 120 V 360 H 300 V 200 H 480"
      fill="none" stroke="rgba(255,255,255,0.06)" strokeWidth="1" />
      <path d="M 60 460 H 200 V 100 H 440"
      fill="none" stroke="rgba(255,255,255,0.05)" strokeWidth="1" />

      {/* animated energy along main trace */}
      <path id="trace1" d="M 30 80 H 180 V 160 H 380 V 280 H 220 V 420 H 460"
      fill="none" stroke="url(#line1)" strokeWidth="1.5" strokeDasharray="60 800"
      style={{ animation: 'dashRun 4s linear infinite' }} />
      <path id="trace2" d="M 40 200 H 120 V 360 H 300 V 200 H 480"
      fill="none" stroke="url(#line2)" strokeWidth="1.5" strokeDasharray="40 700"
      style={{ animation: 'dashRun 5.5s linear infinite reverse' }} />

      {/* nodes */}
      <circle cx="180" cy="80" r="3" fill="rgba(255,46,77,0.8)" />
      <circle cx="380" cy="160" r="3" fill="rgba(255,46,77,0.5)" />
      <circle cx="220" cy="280" r="3" fill="rgba(92,240,255,0.6)" />
      <circle cx="460" cy="420" r="3" fill="rgba(255,46,77,0.8)" />
      <circle cx="120" cy="200" r="2" fill="rgba(255,255,255,0.4)" />
      <circle cx="300" cy="360" r="2" fill="rgba(255,255,255,0.3)" />
    </svg>);

}

function Hero() {
  const { t } = useLang();
  return (
    <section className="hero" id="top">
      <HeroCanvas />
      <div className="hero-mark" aria-hidden="true">
        <img
          className="hero-mark-img"
          src="uploads/666-mark.png"
          alt="" />
        
        <span className="hero-mark-ring hero-mark-ring-1"></span>
        <span className="hero-mark-ring hero-mark-ring-2"></span>
        <span className="hero-mark-ring hero-mark-ring-3"></span>
        <span className="hero-mark-scan"></span>
      </div>
      <div className="hero-vignette" />
      <div className="wrap hero-inner">
        <div className="hero-grid">
          <div>
            <div className="hero-status">
              <span className="pulse"></span>
              <span>{t('hero.status.online')}</span>
              <span style={{ color: 'var(--ink-mute)' }}>·</span>
              <span>{t('hero.status.booking', window.nextQuarter())}</span>
            </div>
            <h1>
              <span className="line"><span className="word">{t('hero.headline.1')}</span> <span className="word">{t('hero.headline.2')}</span></span>
              <span className="line"><span className="word">{t('hero.headline.3')}</span> <span className="word accent">{t('hero.headline.4')}</span></span>
              <span className="line" style={{ fontSize: '0.45em', letterSpacing: '-0.01em', marginTop: 18, fontWeight: 500, color: 'var(--ink-dim)' }}>
                <ScrambleWord text={t('hero.tag.code')} delay={900} />
              </span>
            </h1>
            <p className="hero-sub" dangerouslySetInnerHTML={tHtml('hero.sub.html')} />
            <div className="hero-meta">
              <a href="/start-project/" className="btn btn-primary">
                {t('hero.cta.start')}
                <Icon.arrow className="ico" />
              </a>
              <a href="#work" className="btn btn-ghost">
                {t('hero.cta.skills')}
                <Icon.arrowUR className="ico" />
              </a>
            </div>
            <div className="stack-strip">
              {['NEXT.JS', 'LARAVEL', 'TAILWIND', 'POSTGRES', 'AWS', 'STRIPE', 'SUPABASE', 'FIGMA'].map((s) =>
              <span key={s} className="chip">{s}</span>
              )}
            </div>
            <div className="hero-foot">
              <div className="cell"><div className="v">80<span style={{ color: 'var(--red)' }}>+</span></div><div className="l">{t('hero.stat.projects')}</div></div>
              <div className="cell"><div className="v">4<span className="mono" style={{ fontSize: '0.5em' }}>{t('hero.years.suffix')}</span></div><div className="l">{t('hero.stat.years')}</div></div>
              <div className="cell"><div className="v">99.9<span style={{ color: 'var(--red)' }}>%</span></div><div className="l">{t('hero.stat.uptime')}</div></div>
              <div className="cell"><div className="v">KL<span style={{ color: 'var(--red)' }}>·</span>MY</div><div className="l">{t('hero.stat.local')}</div></div>
            </div>
          </div>

          <TiltStage>
            <CircuitOverlay />
            <div className="panel p-code" data-depth="1">
              <div className="panel-head">
                <div className="dots"><span></span><span></span><span></span></div>
                <div className="name">{t('hero.panel.code.name')}</div>
              </div>
              <div className="code-body">
                <TypingCode />
              </div>
            </div>
            <div className="panel p-perf" data-depth="2">
              <div className="panel-head">
                <div style={{ fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--ink-dim)' }}>{t('hero.panel.perf.title')}</div>
                <div style={{ fontFamily: 'var(--font-mono)', fontSize: 10, color: 'var(--green)', display: 'flex', alignItems: 'center', gap: 6 }}>
                  <span className="live-dot" /> {t('hero.panel.perf.healthy')}
                </div>
              </div>
              <LiveMetrics />
            </div>
            <div className="panel p-deploy" data-depth="1.5">
              <DeployFeed />
            </div>
          </TiltStage>
        </div>
      </div>
    </section>);

}
window.Hero = Hero;