// NeuroForge — page sections
const { useEffect: useEffectP, useRef: useRefP, useState: useStateP } = React;
const { Counter, MiniAgentGraph, MiniRLChart, MiniCyberScope, MiniLLM, MiniHITL, MiniTelemetry, HeroNetwork } = window.NF;

function HomePage({ t, go }) {
  return (
    <div className="page active">
      {/* HERO */}
      <section className="hero">
        <div className="hero-grid"></div>
        <HeroNetwork/>
        <div className="container">
          <div className="hero-inner">
            <div className="reveal in">
              <span className="eyebrow"><span className="dot"></span>{t.hero.eyebrow}</span>
            </div>
            <h1 className="reveal in" data-d="1">
              <span className="gradient-text">{t.hero.title_lead}</span>{t.hero.title_rest}
            </h1>
            <p className="hero-tag reveal in" data-d="2">{t.hero.tag}</p>
            <div className="hero-actions reveal in" data-d="3">
              <button className="btn btn-plasma" onClick={() => go('contact')}>{t.cta.start}<span className="btn-arrow">→</span></button>
              <button className="btn btn-ghost" onClick={() => go('agents')}>{t.cta.explore}</button>
            </div>
            <div className="hero-stats reveal in" data-d="4">
              <div className="hero-stat"><div className="num gradient-text" style={{fontSize:'24px'}}>{t.hero.stat1_n}</div><div className="lbl">{t.hero.stat1_l}</div></div>
              <div className="hero-stat"><div className="num gradient-text" style={{fontSize:'24px'}}>{t.hero.stat2_n}</div><div className="lbl">{t.hero.stat2_l}</div></div>
              <div className="hero-stat"><div className="num gradient-text" style={{fontSize:'24px'}}>{t.hero.stat3_n}</div><div className="lbl">{t.hero.stat3_l}</div></div>
            </div>
          </div>
        </div>
      </section>

      {/* MARQUEE */}
      <div className="marquee">
        <div className="marquee-track">
          {[...Array(2)].flatMap((_,k) => [
            'MULTI-AGENT SYSTEMS','REINFORCEMENT LEARNING','AGENTIC AI','CYBER DEFENSE','POLICY OPTIMIZATION',
            'TOOL-USE','RLHF · RLAIF','RED-TEAM AGENTS','THREAT HUNTING','MODEL ROUTING'
          ].map((n,i) => <div className="logo" key={`${k}-${i}`}><span className="dot"></span>{n}</div>))}
        </div>
      </div>

      {/* WHAT WE BUILD */}
      <section className="section">
        <div className="container">
          <div className="sec-head reveal">
            <span className="eyebrow mono">{t.sec_what.eyebrow}</span>
            <h2>{t.sec_what.title}</h2>
            <p>{t.sec_what.tag}</p>
          </div>
          <div className="cap-grid">
            {[
              { vis: <MiniAgentGraph/>, t: t.cap.a_title, d: t.cap.a_desc, page: 'agents' },
              { vis: <MiniRLChart/>, t: t.cap.b_title, d: t.cap.b_desc, page: 'rl' },
              { vis: <MiniCyberScope/>, t: t.cap.c_title, d: t.cap.c_desc, page: 'cyber' },
              { vis: <MiniLLM/>, t: t.cap.d_title, d: t.cap.d_desc, page: 'agents' },
              { vis: <MiniHITL/>, t: t.cap.e_title, d: t.cap.e_desc, page: 'agents' },
              { vis: <MiniTelemetry/>, t: t.cap.f_title, d: t.cap.f_desc, page: 'rl' },
            ].map((c,i) => (
              <div key={i} className="cap-card reveal" data-d={(i%4)+1} onClick={() => go(c.page)}>
                <div className="visual">{c.vis}</div>
                <h3>{c.t}</h3>
                <p>{c.d}</p>
                <div className="more">{t.cap.more}</div>
              </div>
            ))}
          </div>
        </div>
      </section>

      {/* AGENT ARENA LIVE DEMO */}
      <section className="section" style={{paddingTop: 0}}>
        <div className="container">
          <div className="sec-head reveal">
            <span className="eyebrow mono">{t.arena.eyebrow}</span>
            <h2>{t.arena.title}</h2>
            <p>{t.arena.tag}</p>
          </div>
          <AgentArena t={t}/>
        </div>
      </section>

      {/* PROCESS */}
      <section className="section" style={{paddingTop: 0}}>
        <div className="container">
          <div className="sec-head reveal">
            <span className="eyebrow mono">{t.sec_proc.eyebrow}</span>
            <h2>{t.sec_proc.title}</h2>
          </div>
          <div className="process reveal">
            {[
              { n: '01', t: t.proc.s1_t, d: t.proc.s1_d },
              { n: '02', t: t.proc.s2_t, d: t.proc.s2_d },
              { n: '03', t: t.proc.s3_t, d: t.proc.s3_d },
              { n: '04', t: t.proc.s4_t, d: t.proc.s4_d },
            ].map(s => (
              <div className="proc-step" key={s.n}>
                <div className="num">{t.sec_proc.phase} {s.n}</div>
                <h3>{s.t}</h3>
                <p>{s.d}</p>
              </div>
            ))}
          </div>
        </div>
      </section>

      {/* CODE BLOCK */}
      <section className="section" style={{paddingTop: 0}}>
        <div className="container">
          <div className="feat-grid" style={{alignItems:'center'}}>
            <div className="col-6 reveal">
              <span className="eyebrow mono">{t.code.eyebrow}</span>
              <h2 style={{margin:'18px 0 18px'}}>{t.code.title}</h2>
              <p style={{fontSize:'17px', marginBottom:'24px'}}>{t.code.tag}</p>
              <button className="btn btn-ghost" onClick={() => go('agents')}>{t.code.btn}</button>
            </div>
            <div className="col-6 reveal" data-d="2">
              <CodeSample/>
            </div>
          </div>
        </div>
      </section>

      {/* CTA */}
      <section className="section" style={{paddingTop: 0}}>
        <div className="container">
          <div className="cta reveal">
            <h2>{t.cta_band.title}</h2>
            <p>{t.cta_band.tag}</p>
            <div className="cta-actions">
              <button className="btn btn-plasma" onClick={() => go('contact')}>{t.cta_band.btn}<span className="btn-arrow">→</span></button>
              <button className="btn btn-ghost" onClick={() => go('about')}>{t.cta.talk}</button>
            </div>
          </div>
        </div>
      </section>
    </div>
  );
}

function CodeSample() {
  const code = `<span class="kw">from</span> neuroforge <span class="kw">import</span> Agent, Tool, Policy

<span class="com"># Tier-1 SOC triage agent — runs in your VPC</span>
triage = Agent(
    name=<span class="str">"soc-tier1"</span>,
    model=<span class="str">"nf/forge-12b-cyber"</span>,
    policy=Policy.from_yaml(<span class="str">"policies/triage.yaml"</span>),
    tools=[
        Tool.siem(<span class="str">"splunk"</span>),
        Tool.threat_intel(<span class="str">"misp"</span>),
        Tool.notify(<span class="str">"pagerduty"</span>),
    ],
    rl=<span class="kw">True</span>,         <span class="com"># continuous policy improvement</span>
    audit=<span class="str">"compliance/iso27001"</span>,
)

<span class="kw">async for</span> alert <span class="kw">in</span> triage.stream():
    <span class="kw">if</span> alert.confidence > <span class="num">0.92</span>:
        <span class="kw">await</span> alert.contain()
    <span class="kw">elif</span> alert.severity == <span class="str">"critical"</span>:
        <span class="kw">await</span> alert.escalate(team=<span class="str">"L2"</span>)`;
  return (
    <div className="code-block">
      <div className="code-head">
        <div className="dots"><div className="dot"></div><div className="dot"></div><div className="dot"></div></div>
        <div className="file">soc_triage_agent.py</div>
      </div>
      <pre className="code-body" style={{margin:0}} dangerouslySetInnerHTML={{__html: code}} />
    </div>
  );
}

// Live agent arena (canvas)
function AgentArena({ t }) {
  const ref = useRefP(null);
  useEffectP(() => {
    const canvas = ref.current;
    const ctx = canvas.getContext('2d');
    let raf, dpr = window.devicePixelRatio || 1;
    let W=0, H=0;
    const resize = () => {
      const r = canvas.getBoundingClientRect();
      W = r.width; H = r.height;
      canvas.width = W*dpr; canvas.height = H*dpr;
      ctx.setTransform(dpr,0,0,dpr,0,0);
    };
    resize();
    window.addEventListener('resize', resize);

    // central orchestrator
    const orch = { x: 0.5, y: 0.5 };
    // specialists (fixed ring)
    const specs = Array.from({length: 6}, (_,i) => ({
      angle: (i/6)*Math.PI*2,
      radius: 0.28,
      label: ['PLAN','SEARCH','CODE','VERIFY','EXEC','REPORT'][i],
    }));
    // worker swarm
    const workers = Array.from({length: 28}, () => ({
      x: 0.5 + (Math.random()-0.5)*0.7,
      y: 0.5 + (Math.random()-0.5)*0.7,
      vx: (Math.random()-0.5)*0.0008,
      vy: (Math.random()-0.5)*0.0008,
      assigned: Math.floor(Math.random()*6),
      pulse: Math.random()*Math.PI*2,
    }));
    const packets = [];

    const tick = () => {
      ctx.clearRect(0,0,W,H);

      // background grid
      ctx.strokeStyle = 'rgba(255,255,255,0.03)';
      ctx.lineWidth = 1;
      for (let x=0; x<W; x+=40) { ctx.beginPath(); ctx.moveTo(x,0); ctx.lineTo(x,H); ctx.stroke(); }
      for (let y=0; y<H; y+=40) { ctx.beginPath(); ctx.moveTo(0,y); ctx.lineTo(W,y); ctx.stroke(); }

      const ox = orch.x*W, oy = orch.y*H;

      // orchestrator -> specialist edges
      specs.forEach(s => {
        const sx = ox + Math.cos(s.angle)*s.radius*W;
        const sy = oy + Math.sin(s.angle)*s.radius*H;
        const grad = ctx.createLinearGradient(ox,oy,sx,sy);
        grad.addColorStop(0,'rgba(168,85,247,0.6)');
        grad.addColorStop(1,'rgba(0,224,255,0.4)');
        ctx.strokeStyle = grad;
        ctx.lineWidth = 1.2;
        ctx.beginPath(); ctx.moveTo(ox,oy); ctx.lineTo(sx,sy); ctx.stroke();
      });

      // workers update
      workers.forEach(w => {
        // attract to assigned specialist
        const s = specs[w.assigned];
        const tx = orch.x + Math.cos(s.angle)*s.radius;
        const ty = orch.y + Math.sin(s.angle)*s.radius;
        w.vx += (tx - w.x) * 0.0015;
        w.vy += (ty - w.y) * 0.0015;
        w.vx *= 0.96; w.vy *= 0.96;
        w.x += w.vx; w.y += w.vy;
        w.pulse += 0.08;

        // swap assignment occasionally
        if (Math.random() < 0.002) w.assigned = Math.floor(Math.random()*6);
      });

      // worker -> specialist edges
      workers.forEach(w => {
        const s = specs[w.assigned];
        const sx = ox + Math.cos(s.angle)*s.radius*W;
        const sy = oy + Math.sin(s.angle)*s.radius*H;
        ctx.strokeStyle = 'rgba(255,122,176,0.18)';
        ctx.lineWidth = 0.6;
        ctx.beginPath(); ctx.moveTo(w.x*W, w.y*H); ctx.lineTo(sx,sy); ctx.stroke();
      });

      // packet spawning
      if (Math.random() < 0.15) {
        const s = specs[Math.floor(Math.random()*6)];
        packets.push({
          x: ox, y: oy,
          tx: ox + Math.cos(s.angle)*s.radius*W,
          ty: oy + Math.sin(s.angle)*s.radius*H,
          t: 0, color: '#00e0ff',
        });
      }
      if (Math.random() < 0.12) {
        const s = specs[Math.floor(Math.random()*6)];
        packets.push({
          x: ox + Math.cos(s.angle)*s.radius*W,
          y: oy + Math.sin(s.angle)*s.radius*H,
          tx: ox, ty: oy,
          t: 0, color: '#a855f7',
        });
      }
      for (let i=packets.length-1; i>=0; i--) {
        const p = packets[i];
        p.t += 0.025;
        if (p.t >= 1) { packets.splice(i,1); continue; }
        const x = p.x + (p.tx - p.x)*p.t;
        const y = p.y + (p.ty - p.y)*p.t;
        ctx.beginPath();
        ctx.fillStyle = p.color;
        ctx.shadowColor = p.color; ctx.shadowBlur = 12;
        ctx.arc(x,y,2.2,0,Math.PI*2); ctx.fill();
        ctx.shadowBlur = 0;
      }

      // workers
      workers.forEach(w => {
        const glow = 0.6 + Math.sin(w.pulse)*0.4;
        // outer halo
        ctx.beginPath();
        ctx.fillStyle = 'rgba(255,122,176,0.18)';
        ctx.arc(w.x*W, w.y*H, 6, 0, Math.PI*2);
        ctx.fill();
        // core
        ctx.beginPath();
        ctx.fillStyle = '#ff7ab0';
        ctx.shadowColor = '#ff7ab0'; ctx.shadowBlur = 10*glow;
        ctx.arc(w.x*W, w.y*H, 2.2, 0, Math.PI*2);
        ctx.fill();
        ctx.shadowBlur = 0;
      });

      // specialists
      specs.forEach(s => {
        const sx = ox + Math.cos(s.angle)*s.radius*W;
        const sy = oy + Math.sin(s.angle)*s.radius*H;
        ctx.beginPath();
        ctx.fillStyle = '#00e0ff';
        ctx.shadowColor = '#00e0ff'; ctx.shadowBlur = 18;
        ctx.arc(sx,sy,7,0,Math.PI*2); ctx.fill();
        ctx.shadowBlur = 0;
        ctx.fillStyle = '#5b6080';
        ctx.font = '10px JetBrains Mono';
        ctx.textAlign = 'center';
        ctx.fillText(s.label, sx, sy + 22);
      });

      // orchestrator
      ctx.beginPath();
      ctx.fillStyle = '#a855f7';
      ctx.shadowColor = '#a855f7'; ctx.shadowBlur = 30;
      ctx.arc(ox, oy, 12, 0, Math.PI*2); ctx.fill();
      ctx.shadowBlur = 0;
      ctx.fillStyle = '#fff';
      ctx.font = '600 10px JetBrains Mono';
      ctx.textAlign = 'center';
      ctx.fillText('ORCH', ox, oy+3);

      raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);
    return () => { cancelAnimationFrame(raf); window.removeEventListener('resize', resize); };
  }, []);
  return (
    <div className="agent-arena reveal">
      <canvas ref={ref}></canvas>
      <div className="arena-overlay">{t.arena.overlay}</div>
      <div className="arena-legend">
        <div className="leg"><div className="swatch" style={{background:'#a855f7',boxShadow:'0 0 8px #a855f7'}}></div>{t.arena.legend_orch}</div>
        <div className="leg"><div className="swatch" style={{background:'#00e0ff',boxShadow:'0 0 8px #00e0ff'}}></div>{t.arena.legend_spec}</div>
        <div className="leg"><div className="swatch" style={{background:'#ff7ab0',boxShadow:'0 0 8px #ff7ab0'}}></div>{t.arena.legend_workers}</div>
      </div>
    </div>
  );
}

window.NF.HomePage = HomePage;
window.NF.AgentArena = AgentArena;
window.NF.CodeSample = CodeSample;
