/* AUREN — App pages: Nodes, Workloads, Staking */
const AP = window.AURENData;

const statusColor = { computing: 'green', idle: 'amber', offline: 'gray', running: 'cyan', finalizing: 'violet', pending: 'amber', confirmed: 'green' };

/* ================= NODES ================= */
function Nodes() {
  const [nodes] = useState(AP.myNodes);
  const [sel, setSel] = useState(null);
  const online = nodes.filter(n => n.status !== 'offline');
  const totalTflops = nodes.reduce((a, n) => a + (n.status !== 'offline' ? n.tflops : 0), 0);
  const totalEarn = nodes.reduce((a, n) => a + n.earnings24h, 0);
  return (
    <div>
      <PageHead title="My Nodes" sub="GPU clusters you've connected to the mesh"
        actions={<Button variant="primary" size="sm" icon="plus">Onboard node</Button>} />
      <div className="dash-stats" style={{ display: 'grid', gridTemplateColumns: 'repeat(4,1fr)', gap: 16, marginBottom: 22 }}>
        <Stat label="Total nodes" value={nodes.length} icon="nodes" sub={{ text: online.length + ' online', color: 'var(--green)' }} />
        <Stat label="GPUs contributed" value={nodes.reduce((a, n) => a + n.gpus, 0)} icon="gpu" />
        <Stat label="Compute power" value={totalTflops} suffix=" TF" dec={0} icon="bolt" sub={{ text: 'aggregate', color: 'var(--text-2)' }} />
        <Stat label="24h earnings" value={totalEarn} suffix=" AUREN" dec={2} icon="staking" sub={{ text: 'across nodes', color: 'var(--cyan)' }} />
      </div>
      <Panel style={{ overflow: 'hidden' }}>
        <div className="node-table">
          <div className="node-row node-head" style={{ color: 'var(--text-3)', fontFamily: 'var(--font-mono)', fontSize: 11.5, letterSpacing: '.05em', textTransform: 'uppercase' }}>
            <span>Node</span><span>GPU</span><span>Region</span><span>Status</span><span>Util</span><span>Temp</span><span>24h</span><span></span>
          </div>
          {nodes.map(n => (
            <div key={n.id} className="node-row" onClick={() => setSel(n)} style={{ cursor: 'pointer', transition: 'background .2s' }}
              onMouseEnter={e => e.currentTarget.style.background = 'rgba(255,255,255,0.02)'} onMouseLeave={e => e.currentTarget.style.background = 'transparent'}>
              <span style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                <span style={{ width: 8, height: 8, borderRadius: 8, flexShrink: 0, background: n.status === 'offline' ? 'var(--text-3)' : n.status === 'idle' ? 'var(--amber)' : 'var(--green)', boxShadow: n.status !== 'offline' ? '0 0 8px currentColor' : 'none' }} />
                <span style={{ fontWeight: 600, color: '#fff', fontFamily: 'var(--font-mono)', fontSize: 13.5 }}>{n.name}</span>
              </span>
              <span style={{ color: 'var(--text-2)', fontSize: 13 }}>{n.gpus}× {n.model.replace('NVIDIA ', '').replace('AMD ', '')}</span>
              <span style={{ color: 'var(--text-2)', fontSize: 13 }}>{n.region}</span>
              <span><Badge color={statusColor[n.status]} dot={n.status !== 'offline'}>{n.status}</Badge></span>
              <span style={{ minWidth: 70 }}>{n.status !== 'offline' ? <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}><Progress value={n.util} h={5} /><span className="font-mono" style={{ fontSize: 12, color: 'var(--text-2)', width: 28 }}>{n.util}%</span></div> : <span style={{ color: 'var(--text-3)', fontSize: 12 }}>—</span>}</span>
              <span className="font-mono" style={{ fontSize: 13, color: n.temp > 70 ? 'var(--amber)' : 'var(--text-2)' }}>{n.temp ? n.temp + '°' : '—'}</span>
              <span className="font-mono" style={{ fontSize: 13, color: n.earnings24h ? 'var(--green)' : 'var(--text-3)' }}>{n.earnings24h ? '+' + n.earnings24h.toFixed(1) : '—'}</span>
              <span style={{ color: 'var(--text-3)', display: 'flex', justifyContent: 'flex-end' }}><Icon name="arrow" size={16} /></span>
            </div>
          ))}
        </div>
      </Panel>
      {sel && <NodeDrawer node={sel} onClose={() => setSel(null)} />}
    </div>
  );
}

function NodeDrawer({ node, onClose }) {
  const ref = useThreeScene((c) => window.AURENThree.orbitNode(c), []);
  const specs = [['Model', node.model], ['GPUs', node.gpus + '×'], ['VRAM', node.vram + ' GB'], ['Region', node.region], ['Compute', node.tflops + ' TFLOPS'], ['Uptime', node.uptime + '%']];
  return (
    <>
      <div onClick={onClose} style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.6)', zIndex: 100, backdropFilter: 'blur(3px)', animation: 'fade-up .3s' }} />
      <div style={{ position: 'fixed', top: 0, right: 0, bottom: 0, width: 'min(440px, 92vw)', background: 'var(--bg-1)', borderLeft: '1px solid var(--line-cyan)', zIndex: 101, padding: 28, overflowY: 'auto', boxShadow: '-20px 0 60px rgba(0,0,0,0.5)', animation: 'slidein .35s var(--ease)' }}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 22 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
            <span style={{ width: 10, height: 10, borderRadius: 10, background: node.status === 'offline' ? 'var(--text-3)' : 'var(--green)', boxShadow: node.status !== 'offline' ? '0 0 10px var(--green)' : 'none' }} />
            <h2 className="font-display" style={{ fontSize: 22, fontWeight: 700, color: '#fff', fontFamily: 'var(--font-mono)' }}>{node.name}</h2>
          </div>
          <button onClick={onClose} style={{ background: 'var(--surface)', border: '1px solid var(--line)', borderRadius: 8, color: 'var(--text-2)', cursor: 'pointer', padding: 7, display: 'flex' }}><Icon name="x" size={18} /></button>
        </div>
        <Panel glow style={{ height: 160, marginBottom: 20, position: 'relative', overflow: 'hidden' }}>
          <div ref={ref} style={{ position: 'absolute', inset: 0 }} />
          <div style={{ position: 'absolute', bottom: 12, left: 16 }}><Badge color={statusColor[node.status]} dot={node.status !== 'offline'}>{node.status}</Badge></div>
        </Panel>
        {node.status !== 'offline' && (
          <div style={{ display: 'flex', justifyContent: 'space-around', marginBottom: 22 }}>
            <Gauge value={node.util} label="UTIL" size={84} />
            <Gauge value={node.temp} label="TEMP °C" size={84} color={node.temp > 70 ? 'var(--amber)' : 'var(--green)'} />
            <Gauge value={Math.round(node.power / 7)} label="POWER" size={84} color="var(--violet)" />
          </div>
        )}
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12, marginBottom: 22 }}>
          {specs.map(([k, v]) => (
            <div key={k} style={{ padding: '12px 14px', background: 'var(--surface)', borderRadius: 'var(--r-sm)', border: '1px solid var(--line)' }}>
              <div style={{ fontSize: 11, color: 'var(--text-3)', fontFamily: 'var(--font-mono)', marginBottom: 4, letterSpacing: '.04em' }}>{k}</div>
              <div style={{ fontSize: 14.5, color: '#fff', fontWeight: 600 }}>{v}</div>
            </div>
          ))}
        </div>
        <div style={{ padding: 16, background: 'rgba(24,224,255,0.05)', border: '1px solid var(--line-cyan)', borderRadius: 'var(--r-md)', marginBottom: 20 }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
            <span style={{ fontSize: 13, color: 'var(--text-2)' }}>24h earnings</span>
            <span className="font-display" style={{ fontSize: 22, fontWeight: 700, color: 'var(--green)' }}>+{node.earnings24h.toFixed(2)}</span>
          </div>
        </div>
        <div style={{ display: 'flex', gap: 10 }}>
          <Button variant="ghost" full icon="settings">Configure</Button>
          <Button variant={node.status === 'offline' ? 'primary' : 'danger'} full>{node.status === 'offline' ? 'Bring online' : 'Pause node'}</Button>
        </div>
      </div>
    </>
  );
}

/* ================= WORKLOADS ================= */
function Workloads() {
  const [jobs, setJobs] = useState(AP.workloads);
  const [filter, setFilter] = useState('all');
  useEffect(() => {
    const iv = setInterval(() => setJobs(prev => prev.map(j => {
      if (j.status === 'finalizing') return j;
      const np = Math.min(100, j.progress + AP.rnd(1, 4));
      return { ...j, progress: np, status: np >= 99 ? 'finalizing' : 'running', eta: Math.max(0, j.eta - AP.rnd(1, 5)) };
    })), 1800);
    return () => clearInterval(iv);
  }, []);
  const shown = filter === 'all' ? jobs : jobs.filter(j => j.status === filter);
  return (
    <div>
      <PageHead title="Workloads" sub="Compute jobs routing across the mesh"
        actions={<Button variant="primary" size="sm" icon="bolt">Submit workload</Button>} />
      <div className="dash-stats" style={{ display: 'grid', gridTemplateColumns: 'repeat(4,1fr)', gap: 16, marginBottom: 22 }}>
        <Stat label="Active jobs" value={jobs.length} icon="workloads" sub={{ text: 'routing now', color: 'var(--cyan)' }} />
        <Stat label="GPUs allocated" value={jobs.reduce((a, j) => a + j.gpus, 0)} icon="gpu" />
        <Stat label="Avg latency" value={Math.round(jobs.reduce((a, j) => a + j.latency, 0) / jobs.length)} suffix=" ms" icon="route" />
        <Stat label="Spend rate" value={jobs.reduce((a, j) => a + j.rate, 0)} suffix=" /hr" dec={1} icon="bolt" sub={{ text: 'AUREN', color: 'var(--text-2)' }} />
      </div>
      <div style={{ display: 'flex', gap: 8, marginBottom: 16 }}>
        {[['all', 'All'], ['running', 'Running'], ['finalizing', 'Finalizing']].map(([k, l]) => (
          <button key={k} onClick={() => setFilter(k)} style={{ padding: '7px 16px', borderRadius: 100, fontSize: 13, fontWeight: 600, cursor: 'pointer', fontFamily: 'var(--font-body)', background: filter === k ? 'rgba(24,224,255,0.12)' : 'var(--surface)', border: '1px solid ' + (filter === k ? 'var(--line-cyan)' : 'var(--line)'), color: filter === k ? 'var(--cyan)' : 'var(--text-2)', transition: 'all .2s' }}>{l}</button>
        ))}
      </div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
        {shown.map(j => (
          <Panel key={j.id} hover style={{ padding: 20 }}>
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', flexWrap: 'wrap', gap: 14 }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 14, minWidth: 230 }}>
                <div style={{ width: 44, height: 44, borderRadius: 11, display: 'flex', alignItems: 'center', justifyContent: 'center', background: 'rgba(24,224,255,0.08)', border: '1px solid var(--line-cyan)', color: 'var(--cyan)', flexShrink: 0 }}><Icon name="workloads" size={20} /></div>
                <div>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                    <span className="font-display" style={{ fontSize: 15.5, fontWeight: 600, color: '#fff' }}>{j.type}</span>
                    <Badge color={statusColor[j.status]} dot>{j.status}</Badge>
                  </div>
                  <span className="font-mono" style={{ fontSize: 12, color: 'var(--text-3)' }}>{j.id} · {j.client}</span>
                </div>
              </div>
              <div style={{ display: 'flex', gap: 26, flexWrap: 'wrap', alignItems: 'center' }}>
                <Mini label="GPUs" value={j.gpus} />
                <Mini label="Region" value={j.region} mono />
                <Mini label="Latency" value={j.latency + 'ms'} mono />
                <Mini label="Rate" value={j.rate.toFixed(1) + '/hr'} mono accent="var(--cyan)" />
                <Mini label="ETA" value={j.eta + 'm'} mono />
              </div>
              <div style={{ minWidth: 160, flex: 1 }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 6 }}>
                  <span style={{ fontSize: 11.5, color: 'var(--text-3)', fontFamily: 'var(--font-mono)' }}>PROGRESS</span>
                  <span className="font-mono" style={{ fontSize: 12.5, color: '#fff' }}>{j.progress}%</span>
                </div>
                <Progress value={j.progress} color={j.status === 'finalizing' ? 'var(--violet)' : 'var(--cyan)'} />
              </div>
            </div>
          </Panel>
        ))}
      </div>
    </div>
  );
}
function Mini({ label, value, mono, accent }) {
  return (
    <div style={{ textAlign: 'center' }}>
      <div style={{ fontSize: 10.5, color: 'var(--text-3)', fontFamily: 'var(--font-mono)', letterSpacing: '.04em', marginBottom: 3 }}>{label}</div>
      <div className={mono ? 'font-mono' : 'font-display'} style={{ fontSize: 14, fontWeight: 600, color: accent || '#fff' }}>{value}</div>
    </div>
  );
}

/* ================= STAKING ================= */
function Staking() {
  const w = AP.wallet, t = AP.tokenInfo;
  const [pool, setPool] = useState(AP.stakingPools[1]);
  const [amount, setAmount] = useState('1000');
  const [staked, setStaked] = useState(w.stakedBalance);
  const apr = pool.apr;
  const yearly = (parseFloat(amount) || 0) * apr / 100;
  return (
    <div>
      <PageHead title="Staking" sub="Stake $AUREN to secure capacity and earn yield" />
      <div className="dash-stats" style={{ display: 'grid', gridTemplateColumns: 'repeat(4,1fr)', gap: 16, marginBottom: 22 }}>
        <Stat label="Your stake" value={staked} suffix=" AUREN" dec={0} icon="staking" sub={{ text: '≈ $' + AP.fmt.compact(staked * t.price), color: 'var(--text-2)' }} />
        <Stat label="Pending rewards" value={w.pendingRewards} suffix=" AUREN" dec={2} icon="bolt" accent="var(--violet)" sub={{ text: 'claimable', color: 'var(--cyan)' }} />
        <Stat label="Network staked" value={t.staked} prefix="" dec={0} icon="shield" sub={{ text: AP.fmt.compact(t.staked), color: 'var(--text-2)' }} />
        <Stat label="Best APR" value={38.9} suffix="%" dec={1} icon="trend" accent="var(--green)" sub={{ text: 'validator vault', color: 'var(--green)' }} />
      </div>
      <div className="stake-grid" style={{ display: 'grid', gridTemplateColumns: '1.3fr 1fr', gap: 18 }}>
        <div>
          <h3 className="font-display" style={{ fontSize: 16, fontWeight: 600, color: '#fff', marginBottom: 14 }}>Staking pools</h3>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
            {AP.stakingPools.map(p => (
              <Panel key={p.id} hover onClick={() => setPool(p)} style={{ padding: 20, cursor: 'pointer', borderColor: pool.id === p.id ? 'var(--line-cyan)' : 'var(--line)', boxShadow: pool.id === p.id ? 'var(--glow-soft)' : 'none' }}>
                <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
                    <div style={{ width: 44, height: 44, borderRadius: 11, display: 'flex', alignItems: 'center', justifyContent: 'center', background: 'rgba(24,224,255,0.08)', border: '1px solid var(--line-cyan)', color: 'var(--cyan)' }}><Icon name="shield" size={20} /></div>
                    <div>
                      <div className="font-display" style={{ fontSize: 16, fontWeight: 600, color: '#fff' }}>{p.name}</div>
                      <div style={{ fontSize: 12.5, color: 'var(--text-3)', fontFamily: 'var(--font-mono)' }}>Lock: {p.lock} · Min {p.min} AUREN</div>
                    </div>
                  </div>
                  <div style={{ textAlign: 'right' }}>
                    <div className="font-display text-cyan-grad" style={{ fontSize: 24, fontWeight: 700 }}>{p.apr}%</div>
                    <div style={{ fontSize: 11.5, color: 'var(--text-3)', fontFamily: 'var(--font-mono)' }}>TVL ${AP.fmt.compact(p.tvl)}</div>
                  </div>
                </div>
              </Panel>
            ))}
          </div>
        </div>
        <Panel glow style={{ padding: 24, height: 'fit-content', position: 'sticky', top: 80 }}>
          <h3 className="font-display" style={{ fontSize: 17, fontWeight: 600, color: '#fff', marginBottom: 4 }}>Stake into {pool.name}</h3>
          <p style={{ fontSize: 12.5, color: 'var(--text-3)', marginBottom: 20, fontFamily: 'var(--font-mono)' }}>{pool.lock} lock · {pool.apr}% APR</p>
          <div style={{ marginBottom: 16 }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 8 }}>
              <span style={{ fontSize: 12.5, color: 'var(--text-2)' }}>Amount</span>
              <span style={{ fontSize: 12.5, color: 'var(--text-3)', fontFamily: 'var(--font-mono)' }}>Bal: {AP.fmt.compact(w.balance)}</span>
            </div>
            <div style={{ position: 'relative' }}>
              <input value={amount} onChange={e => setAmount(e.target.value.replace(/[^0-9.]/g, ''))} style={{ width: '100%', padding: '14px 70px 14px 16px', borderRadius: 'var(--r-sm)', background: 'var(--surface)', border: '1px solid var(--line-2)', color: '#fff', fontSize: 18, fontFamily: 'var(--font-display)', fontWeight: 700, outline: 'none' }} />
              <button onClick={() => setAmount(String(Math.floor(w.balance)))} style={{ position: 'absolute', right: 12, top: '50%', transform: 'translateY(-50%)', background: 'rgba(24,224,255,0.1)', border: '1px solid var(--line-cyan)', borderRadius: 6, color: 'var(--cyan)', cursor: 'pointer', padding: '4px 10px', fontSize: 11.5, fontWeight: 600, fontFamily: 'var(--font-mono)' }}>MAX</button>
            </div>
          </div>
          <div style={{ padding: 16, background: 'var(--surface)', borderRadius: 'var(--r-md)', border: '1px solid var(--line)', marginBottom: 20, display: 'flex', flexDirection: 'column', gap: 10 }}>
            {[['Est. yearly yield', '+' + yearly.toFixed(1) + ' AUREN'], ['Est. monthly', '+' + (yearly / 12).toFixed(1) + ' AUREN'], ['Lock period', pool.lock]].map(([k, v]) => (
              <div key={k} style={{ display: 'flex', justifyContent: 'space-between' }}>
                <span style={{ fontSize: 13, color: 'var(--text-2)' }}>{k}</span>
                <span className="font-mono" style={{ fontSize: 13, color: k.includes('yield') || k.includes('monthly') ? 'var(--green)' : '#fff', fontWeight: 600 }}>{v}</span>
              </div>
            ))}
          </div>
          <Button variant="primary" full size="lg" icon="staking" onClick={() => { setStaked(s => s + (parseFloat(amount) || 0)); }}>Stake {amount || 0} AUREN</Button>
          <Button variant="ghost" full style={{ marginTop: 10 }}>Claim {w.pendingRewards.toFixed(2)} rewards</Button>
        </Panel>
      </div>
    </div>
  );
}

Object.assign(window, { Nodes, NodeDrawer, Workloads, Staking, statusColor });
