/* ============================================================
   VYRON App — main: auth, store, actions, router, shell
   ============================================================ */
const { useState, useEffect, useRef } = React;

/* ---------- persistence ---------- */
const LS = {
  session: 'vyron_session',
  user: (e) => 'vyron_user_' + e,
  state: (e) => 'vyron_state_' + e,
};
const load = (k, d) => { try { const v = localStorage.getItem(k); return v ? JSON.parse(v) : d; } catch (e) { return d; } };
const save = (k, v) => { try { localStorage.setItem(k, JSON.stringify(v)); } catch (e) {} };

/* ============================================================
   AUTH SCREEN
   ============================================================ */
function Auth({ onAuth }) {
  const [mode, setMode] = useState('signin');
  const [f, setF] = useState({ name: '', email: '', password: '' });
  const [err, setErr] = useState('');

  const submit = () => {
    setErr('');
    const email = f.email.trim().toLowerCase();
    if (!email || !f.password) { setErr('Email and password are required.'); return; }
    if (mode === 'signup') {
      if (!f.name.trim()) { setErr('Please enter your name.'); return; }
      if (load(LS.user(email))) { setErr('An account with this email already exists.'); return; }
      const user = { name: f.name.trim(), email };
      save(LS.user(email), { password: f.password, name: user.name });
      save(LS.state(email), VY.seedState(user, false));
      onAuth(email);
    } else {
      const rec = load(LS.user(email));
      if (!rec) { setErr('No account found. Try signing up.'); return; }
      if (rec.password !== f.password) { setErr('Incorrect password.'); return; }
      onAuth(email);
    }
  };

  const demo = () => {
    const email = 'demo@vyron.network';
    const user = { name: 'Demo Builder', email };
    save(LS.user(email), { password: 'demo', name: user.name });
    if (!load(LS.state(email))) save(LS.state(email), VY.seedState(user, true));
    onAuth(email);
  };

  return (
    <div className="auth-wrap grid-bg noise">
      <div className="auth-glow" />
      <div className="auth-aside">
        <a className="ap-brand" href="index.html"><img src="assets/logo.png" style={{ width: 38, height: 38, borderRadius: 9 }} /><span className="ap-wordmark" style={{ fontSize: 24 }}>VYRON</span></a>
        <h1>Build the future.<br /><span className="grad-text">Own the infrastructure.</span></h1>
        <p>The autonomous infrastructure dashboard for AI services, programmable APIs and machine-native settlement.</p>
        <div className="auth-feat">
          <div><span className="ap-benefit-ic"><Ic d={I.services} s={16} /></span> Register monetizable services</div>
          <div><span className="ap-benefit-ic"><Ic d={I.routing} s={16} /></span> Tune intelligent routing</div>
          <div><span className="ap-benefit-ic"><Ic d={I.settle} s={16} /></span> Realtime Idle-powered settlement</div>
        </div>
        <div className="auth-tags">
          <span className="chip">◈ Decentralized</span><span className="chip">⚡ Scalable</span><span className="chip">⛨ Secure</span>
        </div>
      </div>

      <div className="auth-card">
        <div className="auth-card-inner">
          <div className="auth-tabs">
            <button className={mode === 'signin' ? 'active' : ''} onClick={() => { setMode('signin'); setErr(''); }}>Sign in</button>
            <button className={mode === 'signup' ? 'active' : ''} onClick={() => { setMode('signup'); setErr(''); }}>Sign up</button>
          </div>
          <h2>{mode === 'signin' ? 'Welcome back' : 'Create your account'}</h2>
          <p className="auth-sub">{mode === 'signin' ? 'Sign in to your VYRON dashboard.' : 'Start publishing machine-native services.'}</p>

          {mode === 'signup' && <Field label="Display name" placeholder="Jane Builder" value={f.name} onChange={e => setF({ ...f, name: e.target.value })} />}
          <Field label="Email" type="email" placeholder="you@machine.ai" value={f.email} onChange={e => setF({ ...f, email: e.target.value })} />
          <Field label="Password" type="password" placeholder="••••••••" value={f.password} onChange={e => setF({ ...f, password: e.target.value })}
            onKeyDown={e => e.key === 'Enter' && submit()} />

          {err && <div className="auth-err"><Ic d={I.x} s={14} /> {err}</div>}

          <button className="btn btn-primary" style={{ width: '100%', marginTop: 6 }} onClick={submit}>
            {mode === 'signin' ? 'Sign in' : 'Create account'} <Ic d={I.arrow} s={15} />
          </button>
          <div className="auth-or"><span>or</span></div>
          <button className="btn btn-ghost" style={{ width: '100%' }} onClick={demo}><Ic d={I.bolt} s={15} /> Continue with demo account</button>
          <p className="auth-fine">Mock authentication · data is stored locally on this device.</p>
        </div>
      </div>
    </div>
  );
}

/* ============================================================
   APP SHELL
   ============================================================ */
function AppShell({ email, onLogout }) {
  const [state, setState] = useState(() => load(LS.state(email)));
  const [route, setRoute] = useState('dashboard');
  const [sideOpen, setSideOpen] = useState(false);
  const [toast, setToast] = useState(null);

  useEffect(() => { save(LS.state(email), state); }, [state, email]);
  const flash = (msg) => { setToast(msg); setTimeout(() => setToast(null), 2200); };

  /* ---- LIVE network simulation engine ---- */
  useEffect(() => {
    const id = setInterval(() => {
      setState(s => {
        const active = s.services.filter(x => x.status === 'active');
        let balance = s.balance, served = s.metrics.requestsServed;
        let services = s.services, settlements = s.settlements, activity = s.activity;
        const fresh = [];
        if (active.length) {
          const burst = 1 + Math.floor(Math.random() * 3);
          for (let i = 0; i < burst; i++) {
            const svc = active[Math.floor(Math.random() * active.length)];
            const consumer = VY.CONSUMERS[Math.floor(Math.random() * VY.CONSUMERS.length)];
            balance += svc.price; served += 1;
            services = services.map(x => x.id === svc.id ? { ...x, requests: x.requests + 1, earnings: x.earnings + svc.price } : x);
            fresh.push({ id: VY.uid(), ts: Date.now(), cap: svc.cap, consumer, cost: svc.price, status: 'settled' });
          }
          settlements = [...fresh.reverse(), ...s.settlements].slice(0, 60);
          if (Math.random() < 0.55) {
            const last = fresh[0];
            activity = [{ id: VY.uid(), type: 'settle', text: 'Served ' + last.cap, amount: last.cost, ts: Date.now() }, ...s.activity].slice(0, 40);
          }
        }
        const vol = active.length ? Math.round(70 + Math.random() * 170)
          : Math.max(0, Math.round((s.sparkline[s.sparkline.length - 1] || 0) + (Math.random() * 24 - 12)));
        const sparkline = [...s.sparkline.slice(1), vol];
        const rewards = s.rewards + s.staked * 0.0000045 * (0.6 + Math.random());
        const uptime = Math.min(100, Math.max(98.6, +(s.metrics.uptime + (Math.random() * 0.12 - 0.06)).toFixed(2)));
        return { ...s, balance, services, settlements, activity, rewards, sparkline, tick: (s.tick || 0) + 1, metrics: { requestsServed: served, uptime } };
      });
    }, 2000);
    return () => clearInterval(id);
  }, []);

  /* ---- actions ---- */
  const actions = {
    registerService: ({ cap, endpoint, price }) => {
      setState(s => ({
        ...s,
        services: [{ id: VY.uid(), cap, endpoint, price, status: 'active', requests: 0, earnings: 0 }, ...s.services],
        activity: [{ id: VY.uid(), type: 'register', text: 'Registered ' + cap, amount: 0, ts: Date.now() }, ...s.activity],
      }));
      flash('Service registered · ' + cap);
    },
    toggleService: (id) => setState(s => ({ ...s, services: s.services.map(x => x.id === id ? { ...x, status: x.status === 'active' ? 'paused' : 'active' } : x) })),
    removeService: (id) => setState(s => ({ ...s, services: s.services.filter(x => x.id !== id) })),
    updateRouting: (w) => setState(s => ({ ...s, routing: w })),
    callCapability: (c) => {
      setState(s => ({
        ...s,
        balance: Math.max(0, s.balance - c.price),
        settlements: [{ id: VY.uid(), ts: Date.now(), cap: c.cap, consumer: s.user.name.toLowerCase().replace(/\s/g, '-'), cost: c.price, status: 'settled' }, ...s.settlements].slice(0, 60),
        activity: [{ id: VY.uid(), type: 'call', text: 'Called ' + c.cap, amount: -c.price, ts: Date.now() }, ...s.activity].slice(0, 40),
      }));
      flash('Called ' + c.cap + ' · settled ' + VY.fmt(c.price, 4) + ' VYRON');
    },
    stake: (v) => { setState(s => v > s.balance ? s : ({ ...s, balance: s.balance - v, staked: s.staked + v, activity: [{ id: VY.uid(), type: 'stake', text: 'Staked ' + VY.fmt(v) + ' VYRON', amount: -v, ts: Date.now() }, ...s.activity] })); flash('Staked ' + VY.fmt(v) + ' VYRON'); },
    unstake: (v) => { setState(s => v > s.staked ? s : ({ ...s, balance: s.balance + v, staked: s.staked - v, activity: [{ id: VY.uid(), type: 'stake', text: 'Unstaked ' + VY.fmt(v) + ' VYRON', amount: v, ts: Date.now() }, ...s.activity] })); flash('Unstaked ' + VY.fmt(v) + ' VYRON'); },
    claimRewards: () => { setState(s => ({ ...s, balance: s.balance + s.rewards, rewards: 0, activity: [{ id: VY.uid(), type: 'settle', text: 'Claimed staking rewards', amount: s.rewards, ts: Date.now() }, ...s.activity] })); flash('Rewards claimed'); },
    vote: (id, dir) => {
      setState(s => ({ ...s, proposals: s.proposals.map(p => p.id === id ? { ...p, voted: dir, forVotes: p.forVotes + (dir === 'for' ? Math.round(s.staked) : 0), againstVotes: p.againstVotes + (dir === 'against' ? Math.round(s.staked) : 0) } : p) }));
      flash('Vote cast · ' + dir);
    },
    genApiKey: (label) => { setState(s => ({ ...s, apiKeys: [{ id: VY.uid(), key: VY.genKey(), label, created: Date.now() }, ...s.apiKeys] })); flash('API key generated'); },
    revokeKey: (id) => setState(s => ({ ...s, apiKeys: s.apiKeys.filter(k => k.id !== id) })),
    updateProfile: ({ name }) => { setState(s => ({ ...s, user: { ...s.user, name } })); flash('Profile updated'); },
  };

  const screens = {
    dashboard: <Dashboard state={state} actions={actions} setRoute={setRoute} />,
    services: <Services state={state} actions={actions} />,
    routing: <Routing state={state} actions={actions} />,
    settlement: <Settlement state={state} />,
    staking: <Staking state={state} actions={actions} />,
    discovery: <Discovery state={state} actions={actions} />,
    governance: <Governance state={state} actions={actions} />,
    settings: <Settings state={state} actions={actions} onLogout={onLogout} />,
  };

  return (
    <div className="ap-shell">
      <Sidebar route={route} setRoute={setRoute} open={sideOpen} onClose={() => setSideOpen(false)} />
      {sideOpen && <div className="ap-scrim" onClick={() => setSideOpen(false)} />}
      <div className="ap-main">
        <TopBar state={state} onMenu={() => setSideOpen(true)} onLogout={onLogout} setRoute={setRoute} />
        <div className="ap-content" key={route}>{screens[route]}</div>
      </div>
      {toast && <Toast msg={toast} />}
    </div>
  );
}

/* ============================================================
   ROOT
   ============================================================ */
function App() {
  const [session, setSession] = useState(() => load(LS.session, null));
  const onAuth = (email) => { save(LS.session, email); setSession(email); };
  const onLogout = () => { localStorage.removeItem(LS.session); setSession(null); };
  // guard: session must still have a state
  useEffect(() => { if (session && !load(LS.state(session))) onLogout(); }, []);
  return session ? <AppShell email={session} onLogout={onLogout} /> : <Auth onAuth={onAuth} />;
}

ReactDOM.createRoot(document.getElementById('root')).render(<App />);
