/* AUREN — App shell: sidebar, topbar, activity feed, gauges + Dashboard */
const AD = window.AURENData;

/* ---------- Radial gauge ---------- */
function Gauge({ value, size = 92, label, color = 'var(--cyan)' }) {
  const r = size / 2 - 8, c = 2 * Math.PI * r;
  const off = c - (value / 100) * c;
  return (
    <div style={{ position: 'relative', width: size, height: size }}>
      <svg width={size} height={size} style={{ transform: 'rotate(-90deg)' }}>
        <circle cx={size/2} cy={size/2} r={r} fill="none" stroke="rgba(255,255,255,0.07)" strokeWidth="6" />
        <circle cx={size/2} cy={size/2} r={r} fill="none" stroke={color} strokeWidth="6" strokeLinecap="round"
          strokeDasharray={c} strokeDashoffset={off} style={{ transition: 'stroke-dashoffset 1s var(--ease)', filter: 'drop-shadow(0 0 5px ' + color + ')' }} />
      </svg>
      <div style={{ position: 'absolute', inset: 0, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center' }}>
        <span className="font-display" style={{ fontSize: size > 80 ? 22 : 16, fontWeight: 700, color: '#fff' }}>{Math.round(value)}<span style={{ fontSize: 11, color: 'var(--text-3)' }}>%</span></span>
        {label && <span style={{ fontSize: 10, color: 'var(--text-3)', fontFamily: 'var(--font-mono)', letterSpacing: '.05em', marginTop: 2 }}>{label}</span>}
      </div>
    </div>
  );
}

/* ---------- Live activity feed ---------- */
function ActivityFeed({ rows = 7, compact = false }) {
  const [items, setItems] = useState(() => Array.from({ length: rows }, (_, i) => ({ id: i, text: AD.genFeed(), t: AD.rnd(1, 40) })));
  useEffect(() => {
    const iv = setInterval(() => {
      setItems(prev => [{ id: Date.now(), text: AD.genFeed(), t: 0, fresh: true }, ...prev.slice(0, rows - 1)]);
    }, 2600);
    return () => clearInterval(iv);
  }, [rows]);
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: compact ? 2 : 4 }}>
      {items.map((it, i) => (
        <div key={it.id} style={{
          display: 'flex', alignItems: 'center', gap: 12, padding: compact ? '9px 4px' : '11px 6px',
          borderBottom: i < items.length - 1 ? '1px solid var(--line)' : 'none',
          animation: it.fresh ? 'fade-up .5s var(--ease)' : 'none',
        }}>
          <span style={{ width: 7, height: 7, borderRadius: 7, background: 'var(--cyan)', boxShadow: '0 0 8px var(--cyan)', flexShrink: 0, animation: it.fresh ? 'pulse-glow 1.5s ease 2' : 'none' }} />
          <span style={{ flex: 1, fontSize: 13, color: 'var(--text-1)', fontFamily: 'var(--font-mono)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{it.text}</span>
          <span style={{ fontSize: 11.5, color: 'var(--text-3)', fontFamily: 'var(--font-mono)', flexShrink: 0 }}>{it.t === 0 ? 'now' : it.t + 'm'}</span>
        </div>
      ))}
    </div>
  );
}

/* ---------- Page header ---------- */
function PageHead({ title, sub, actions }) {
  return (
    <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', flexWrap: 'wrap', gap: 16, marginBottom: 28 }}>
      <div>
        <h1 className="font-display" style={{ fontSize: 28, fontWeight: 700, color: '#fff', letterSpacing: '-.01em' }}>{title}</h1>
        {sub && <p style={{ color: 'var(--text-2)', fontSize: 14.5, marginTop: 6 }}>{sub}</p>}
      </div>
      {actions && <div style={{ display: 'flex', gap: 10 }}>{actions}</div>}
    </div>
  );
}

/* ---------- Sidebar ---------- */
const NAV = [
  { id: 'dashboard', label: 'Dashboard', icon: 'dashboard' },
  { id: 'nodes', label: 'My Nodes', icon: 'nodes' },
  { id: 'workloads', label: 'Workloads', icon: 'workloads' },
  { id: 'staking', label: 'Staking', icon: 'staking' },
  { id: 'wallet', label: 'Wallet', icon: 'wallet' },
  { id: 'explorer', label: 'Network', icon: 'explorer' },
  { id: 'governance', label: 'Governance', icon: 'governance' },
  { id: 'settings', label: 'Settings', icon: 'settings' },
];
function Sidebar({ route, go, user, onLogout, open, setOpen }) {
  return (
    <>
      {open && <div onClick={() => setOpen(false)} style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.6)', zIndex: 90, backdropFilter: 'blur(2px)' }} className="side-overlay" />}
      <aside className={'app-sidebar' + (open ? ' open' : '')} style={{
        width: 'var(--side-w)', flexShrink: 0, background: 'var(--bg-1)', borderRight: '1px solid var(--line)',
        height: '100vh', position: 'sticky', top: 0, display: 'flex', flexDirection: 'column', padding: '22px 16px', zIndex: 95,
      }}>
        <button onClick={() => go('landing')} style={{ display: 'flex', alignItems: 'center', gap: 11, background: 'none', border: 'none', cursor: 'pointer', padding: '4px 8px', marginBottom: 26 }}>
          <img src="assets/auren-logo.png" alt="AUREN" style={{ height: 34, width: 34, filter: 'drop-shadow(0 0 8px rgba(24,224,255,0.4))' }} />
          <div style={{ textAlign: 'left' }}>
            <div className="font-display" style={{ fontSize: 17, fontWeight: 800, letterSpacing: '.14em', color: '#fff', lineHeight: 1 }}>AUREN</div>
            <div className="font-mono" style={{ fontSize: 8.5, color: 'var(--cyan)', letterSpacing: '.16em', marginTop: 3 }}>COMPUTE MESH</div>
          </div>
        </button>
        <nav style={{ display: 'flex', flexDirection: 'column', gap: 3, flex: 1 }}>
          {NAV.map(n => {
            const on = route === n.id;
            return (
              <button key={n.id} onClick={() => { go(n.id); setOpen(false); }} style={{
                display: 'flex', alignItems: 'center', gap: 12, padding: '11px 13px', borderRadius: 'var(--r-sm)',
                background: on ? 'rgba(24,224,255,0.09)' : 'transparent', border: '1px solid ' + (on ? 'var(--line-cyan)' : 'transparent'),
                color: on ? 'var(--cyan)' : 'var(--text-2)', cursor: 'pointer', fontSize: 14, fontWeight: 500, fontFamily: 'var(--font-body)',
                transition: 'all .2s', textAlign: 'left', position: 'relative',
              }} onMouseEnter={e => { if (!on) e.currentTarget.style.background = 'rgba(255,255,255,0.03)'; }}
                 onMouseLeave={e => { if (!on) e.currentTarget.style.background = 'transparent'; }}>
                {on && <span style={{ position: 'absolute', left: 0, top: '50%', transform: 'translateY(-50%)', width: 3, height: 18, background: 'var(--cyan)', borderRadius: 3, boxShadow: '0 0 8px var(--cyan)' }} />}
                <Icon name={n.icon} size={19} stroke={on ? 1.8 : 1.5} />{n.label}
              </button>
            );
          })}
        </nav>
        <div style={{ borderTop: '1px solid var(--line)', paddingTop: 14, marginTop: 8 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 11, padding: '8px 8px' }}>
            <div style={{ width: 36, height: 36, borderRadius: '50%', background: 'var(--grad-cyan)', display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#021018', fontWeight: 700, fontFamily: 'var(--font-display)', fontSize: 15, flexShrink: 0 }}>
              {(user?.name || 'A')[0].toUpperCase()}
            </div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 13.5, fontWeight: 600, color: '#fff', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{user?.name || 'demo'}</div>
              <div style={{ fontSize: 11.5, color: 'var(--text-3)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{user?.email || ''}</div>
            </div>
            <button onClick={onLogout} title="Sign out" style={{ background: 'none', border: 'none', color: 'var(--text-3)', cursor: 'pointer', padding: 6, display: 'flex' }}
              onMouseEnter={e => e.currentTarget.style.color = 'var(--red)'} onMouseLeave={e => e.currentTarget.style.color = 'var(--text-3)'}>
              <Icon name="logout" size={18} />
            </button>
          </div>
        </div>
      </aside>
    </>
  );
}

/* ---------- Topbar ---------- */
function Topbar({ onMenu, user }) {
  const t = AD.tokenInfo;
  return (
    <div style={{ height: 64, borderBottom: '1px solid var(--line)', display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '0 24px', position: 'sticky', top: 0, zIndex: 80, background: 'rgba(5,7,12,0.82)', backdropFilter: 'blur(12px)' }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
        <button className="app-burger" onClick={onMenu} style={{ display: 'none', background: 'none', border: 'none', color: '#fff', cursor: 'pointer' }}><Icon name="menu" size={22} /></button>
        <div className="top-search" style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '8px 14px', background: 'var(--surface)', border: '1px solid var(--line)', borderRadius: 'var(--r-sm)', width: 280 }}>
          <Icon name="explorer" size={16} style={{ color: 'var(--text-3)' }} />
          <input placeholder="Search nodes, jobs, tx…" style={{ background: 'none', border: 'none', outline: 'none', color: '#fff', fontSize: 13.5, width: '100%', fontFamily: 'var(--font-body)' }} />
        </div>
      </div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
        <div className="top-price" style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '7px 12px', background: 'var(--surface)', border: '1px solid var(--line)', borderRadius: 100 }}>
          <img src="assets/auren-logo.png" style={{ height: 18, width: 18 }} alt="" />
          <span className="font-mono" style={{ fontSize: 13, color: '#fff', fontWeight: 600 }}>${t.price.toFixed(3)}</span>
          <span style={{ fontSize: 12, color: t.change24h >= 0 ? 'var(--green)' : 'var(--red)', fontFamily: 'var(--font-mono)' }}>{t.change24h >= 0 ? '+' : ''}{t.change24h}%</span>
        </div>
        <Badge color="green" dot>Mesh online</Badge>
      </div>
    </div>
  );
}

/* ---------- Dashboard ---------- */
function Dashboard({ go }) {
  const s = AD.networkStats, w = AD.wallet, t = AD.tokenInfo;
  const earnSeries = useMemo(() => AD.priceSeries['30D'].map(v => v * 60 + AD.rnd(20, 90)), []);
  const myNodes = AD.myNodes;
  const online = myNodes.filter(n => n.status !== 'offline').length;
  const totalEarn = myNodes.reduce((a, n) => a + n.earnings24h, 0);
  return (
    <div>
      <PageHead title="Dashboard" sub="Your slice of the autonomous compute mesh"
        actions={<><Button variant="ghost" size="sm" icon="plus" onClick={() => go('nodes')}>Add node</Button><Button variant="primary" size="sm" icon="bolt" onClick={() => go('workloads')}>New workload</Button></>} />
      {/* top stats */}
      <div className="dash-stats" style={{ display: 'grid', gridTemplateColumns: 'repeat(4,1fr)', gap: 16, marginBottom: 18 }}>
        <Stat label="24h Earnings" value={totalEarn} prefix="" suffix=" AUREN" dec={2} icon="bolt" sub={{ text: '+12.4% vs yesterday', color: 'var(--green)' }} spark={earnSeries.slice(-16)} />
        <Stat label="Active nodes" value={online} suffix={' / ' + myNodes.length} icon="nodes" sub={{ text: 'computing now', color: 'var(--text-2)' }} />
        <Stat label="Wallet value" value={w.balance * t.price} prefix="$" dec={0} icon="wallet" sub={{ text: AD.fmt.compact(w.balance) + ' AUREN', color: 'var(--text-2)' }} />
        <Stat label="Pending rewards" value={w.pendingRewards} suffix=" AUREN" dec={2} icon="staking" sub={{ text: 'claimable', color: 'var(--cyan)' }} accent="var(--violet)" />
      </div>
      {/* main grid */}
      <div className="dash-main" style={{ display: 'grid', gridTemplateColumns: '1.6fr 1fr', gap: 18 }}>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
          {/* earnings chart */}
          <Panel style={{ padding: 24 }}>
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 18 }}>
              <div>
                <h3 className="font-display" style={{ fontSize: 17, fontWeight: 600, color: '#fff' }}>Earnings</h3>
                <span style={{ fontSize: 12.5, color: 'var(--text-3)', fontFamily: 'var(--font-mono)' }}>Last 30 days · AUREN</span>
              </div>
              <Badge color="green" dot>+18.6% APR</Badge>
            </div>
            <PriceChart data={earnSeries} h={200} />
          </Panel>
          {/* network mini stats */}
          <div className="dash-net" style={{ display: 'grid', gridTemplateColumns: 'repeat(4,1fr)', gap: 14 }}>
            {[['Network nodes', AD.fmt.compact(s.activeNodes)], ['GPUs', AD.fmt.compact(s.totalGpus)], ['PetaFLOPS', s.networkTflops.toFixed(1)], ['Workloads', AD.fmt.compact(s.activeWorkloads)]].map(([k, v]) => (
              <Panel key={k} style={{ padding: '16px 18px' }}>
                <div className="font-display" style={{ fontSize: 20, fontWeight: 700, color: '#fff' }}>{v}</div>
                <div style={{ fontSize: 11.5, color: 'var(--text-3)', fontFamily: 'var(--font-mono)', marginTop: 4, letterSpacing: '.03em' }}>{k}</div>
              </Panel>
            ))}
          </div>
          {/* utilization gauges */}
          <Panel style={{ padding: 24 }}>
            <h3 className="font-display" style={{ fontSize: 17, fontWeight: 600, color: '#fff', marginBottom: 20 }}>Live utilization</h3>
            <div style={{ display: 'flex', justifyContent: 'space-around', flexWrap: 'wrap', gap: 16 }}>
              <Gauge value={s.utilization} label="MESH" />
              <Gauge value={73} label="GPU" color="var(--green)" />
              <Gauge value={61} label="MEMORY" color="var(--violet)" />
              <Gauge value={88} label="NETWORK" color="var(--amber)" />
            </div>
          </Panel>
        </div>
        {/* right column */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
          <Panel style={{ padding: 22 }}>
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 8 }}>
              <h3 className="font-display" style={{ fontSize: 16, fontWeight: 600, color: '#fff' }}>Live activity</h3>
              <Badge color="cyan" dot>Streaming</Badge>
            </div>
            <ActivityFeed rows={8} compact />
          </Panel>
          <Panel glow style={{ padding: 22, position: 'relative', overflow: 'hidden' }}>
            <div style={{ position: 'absolute', top: -30, right: -30, width: 140, height: 140, background: 'radial-gradient(circle, rgba(24,224,255,0.16), transparent 70%)' }} />
            <h3 className="font-display" style={{ fontSize: 16, fontWeight: 600, color: '#fff', marginBottom: 6 }}>Claim rewards</h3>
            <p style={{ fontSize: 13, color: 'var(--text-2)', marginBottom: 16 }}>You have unclaimed routing & staking rewards.</p>
            <div className="font-display" style={{ fontSize: 30, fontWeight: 700, color: '#fff', marginBottom: 4 }}>{w.pendingRewards.toFixed(2)}</div>
            <div className="font-mono" style={{ fontSize: 12, color: 'var(--cyan)', marginBottom: 18 }}>AUREN ≈ ${(w.pendingRewards * t.price).toFixed(2)}</div>
            <Button variant="primary" full icon="bolt">Claim all rewards</Button>
          </Panel>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { Gauge, ActivityFeed, PageHead, Sidebar, Topbar, Dashboard, NAV });
