/* ============================================================
   VYRON App — Screens (part 1)
   Dashboard · Services · Routing · Settlement
   ============================================================ */
const { useState, useEffect, useRef } = React;

/* ---------------- DASHBOARD ---------------- */
function Dashboard({ state, actions, setRoute }) {
  const activeServices = state.services.filter(s => s.status === 'active').length;
  return (
    <div className="ap-page">
      <PageHead
        eyebrow="Overview"
        title={`Welcome back, ${state.user.name.split(' ')[0]}`}
        sub="Your autonomous infrastructure at a glance."
        actions={<div className="ap-live"><span className="ap-live-dot" /> Live · settling in realtime</div>}
      />

      <div className="ap-grid-4">
        <Stat label="VYRON Balance" value={VY.fmt(state.balance)} icon={I.stake} accent delta={2.4} />
        <Stat label="Requests served" value={VY.fmtInt(state.metrics.requestsServed)} icon={I.pulse} delta={6.1} />
        <Stat label="Total earned" value={VY.fmt(state.services.reduce((a, s) => a + s.earnings, 0))} unit="VYRON" icon={I.up} delta={4.8} />
        <Stat label="Uptime" value={state.metrics.uptime} unit="%" icon={I.check} delta={0.2} />
      </div>

      <div className="ap-grid-2-1">
        <div className="ap-card">
          <div className="ap-card-head">
            <h3>Request throughput</h3>
            <span className="ap-card-sub">last 24h · per hour</span>
          </div>
          <Bars data={state.sparkline} height={150} />
          <div className="ap-card-foot">
            <div><b>{VY.fmtInt(state.sparkline.reduce((a, b) => a + b, 0))}</b> requests routed</div>
            <div><b>{activeServices}</b> active services</div>
            <div><b>{VY.fmt(state.routing.latency)}</b>ms avg latency</div>
          </div>
        </div>

        <div className="ap-card">
          <div className="ap-card-head"><h3>Activity</h3></div>
          <div className="ap-feed">
            {state.activity.slice(0, 7).map(a => (
              <div key={a.id} className="ap-feed-row">
                <span className={"ap-feed-ic " + a.type}><Ic d={a.type === 'settle' ? I.settle : a.type === 'route' ? I.routing : a.type === 'stake' ? I.stake : a.type === 'call' ? I.bolt : I.plus} s={14} /></span>
                <div className="ap-feed-txt">
                  <div>{a.text}</div>
                  <span>{VY.ago(a.ts)}</span>
                </div>
                {a.amount !== 0 && <span className={"ap-feed-amt " + (a.amount > 0 ? 'pos' : 'neg')}>{a.amount > 0 ? '+' : ''}{VY.fmt(a.amount, 4)}</span>}
              </div>
            ))}
          </div>
        </div>
      </div>

      <div className="ap-card">
        <div className="ap-card-head">
          <h3>My services</h3>
          <button className="ap-link" onClick={() => setRoute('services')}>Manage <Ic d={I.arrow} s={14} /></button>
        </div>
        {state.services.length === 0 ? (
          <Empty text="No services yet — register your first capability." cta="Register service" onCta={() => setRoute('services')} />
        ) : (
          <table className="ap-table">
            <thead><tr><th>Capability</th><th>Price</th><th>Requests</th><th>Earned</th><th>Status</th></tr></thead>
            <tbody>
              {state.services.map(s => (
                <tr key={s.id}>
                  <td className="mono">{s.cap}</td>
                  <td className="mono">{VY.fmt(s.price, 4)}</td>
                  <td>{VY.fmtInt(s.requests)}</td>
                  <td className="mono pos">{VY.fmt(s.earnings, 3)}</td>
                  <td><Badge kind={s.status === 'active' ? 'green' : 'mute'}>{s.status}</Badge></td>
                </tr>
              ))}
            </tbody>
          </table>
        )}
      </div>
    </div>
  );
}

function Empty({ text, cta, onCta }) {
  return (
    <div className="ap-empty">
      <div className="ap-empty-ic"><Ic d={I.services} s={26} /></div>
      <p>{text}</p>
      {cta && <button className="btn btn-ghost btn-sm" onClick={onCta}>{cta}</button>}
    </div>
  );
}

/* ---------------- SERVICES ---------------- */
function Services({ state, actions }) {
  const [modal, setModal] = useState(false);
  const [form, setForm] = useState({ cap: '', endpoint: '', price: '0.0010' });
  const submit = () => {
    if (!form.cap || !form.endpoint) return;
    actions.registerService({ cap: form.cap, endpoint: form.endpoint, price: parseFloat(form.price) || 0.001 });
    setModal(false); setForm({ cap: '', endpoint: '', price: '0.0010' });
  };
  return (
    <div className="ap-page">
      <PageHead eyebrow="Provider" title="My Services" sub="Publish endpoints as monetizable, discoverable capabilities."
        actions={<button className="btn btn-primary btn-sm" onClick={() => setModal(true)}><Ic d={I.plus} s={15} /> Register service</button>} />

      <div className="ap-grid-3">
        <Stat label="Active services" value={state.services.filter(s => s.status === 'active').length} icon={I.services} accent />
        <Stat label="Total requests" value={VY.fmtInt(state.services.reduce((a, s) => a + s.requests, 0))} icon={I.pulse} />
        <Stat label="Lifetime earnings" value={VY.fmt(state.services.reduce((a, s) => a + s.earnings, 0))} unit="VYRON" icon={I.up} />
      </div>

      <div className="ap-card">
        <div className="ap-card-head"><h3>Registered capabilities</h3></div>
        {state.services.length === 0 ? (
          <Empty text="No services registered yet." cta="Register your first service" onCta={() => setModal(true)} />
        ) : (
          <table className="ap-table">
            <thead><tr><th>Capability</th><th>Endpoint</th><th>Price</th><th>Requests</th><th>Earned</th><th>Status</th><th></th></tr></thead>
            <tbody>
              {state.services.map(s => (
                <tr key={s.id}>
                  <td className="mono">{s.cap}</td>
                  <td className="mono dim">{s.endpoint}</td>
                  <td className="mono">{VY.fmt(s.price, 4)}</td>
                  <td>{VY.fmtInt(s.requests)}</td>
                  <td className="mono pos">{VY.fmt(s.earnings, 3)}</td>
                  <td><Badge kind={s.status === 'active' ? 'green' : 'mute'}>{s.status}</Badge></td>
                  <td className="ap-rowact">
                    <button onClick={() => actions.toggleService(s.id)} title={s.status === 'active' ? 'Pause' : 'Activate'}>
                      {s.status === 'active' ? 'Pause' : 'Activate'}
                    </button>
                    <button className="danger" onClick={() => actions.removeService(s.id)} title="Remove"><Ic d={I.x} s={14} /></button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        )}
      </div>

      {modal && (
        <Modal title="Register a service" onClose={() => setModal(false)}>
          <p className="ap-modal-lead">Publish an endpoint to the VYRON registry. It becomes discoverable and self-settling via Idle Protocol.</p>
          <label className="ap-field"><span>Capability</span>
            <select value={form.cap} onChange={e => setForm({ ...form, cap: e.target.value })}>
              <option value="">Select a capability…</option>
              {VY.CATALOG.map(c => <option key={c.cap} value={c.cap}>{c.cap}</option>)}
            </select>
          </label>
          <Field label="Endpoint URL" placeholder="https://my-node.ai/embed" value={form.endpoint} onChange={e => setForm({ ...form, endpoint: e.target.value })} />
          <Field label="Price (VYRON / request)" type="number" step="0.0001" value={form.price} onChange={e => setForm({ ...form, price: e.target.value })} />
          <button className="btn btn-primary" style={{ width: '100%', marginTop: 8 }} onClick={submit}>Register service</button>
        </Modal>
      )}
    </div>
  );
}

/* ---------------- ROUTING ---------------- */
function Routing({ state, actions }) {
  const w = state.routing;
  const sum = w.latency + w.price + w.reliability || 1;
  const tick = state.tick || 0;
  // score providers (with live latency jitter)
  const scored = VY.PROVIDERS.map((p, i) => {
    const liveLat = Math.max(20, p.latency + Math.round(Math.sin((tick + i * 2) * 0.55) * 5 + (Math.random() * 3 - 1.5)));
    const nl = 1 - (liveLat - 41) / 60;              // lower latency better
    const np = 1 - (p.price - 0.00031) / 0.0001;     // lower price better
    const nr = (p.reliability - 0.96) / 0.04;        // higher reliability better
    const score = (nl * w.latency + np * w.price + nr * w.reliability) / sum;
    return { ...p, liveLat, score: Math.max(0.01, score) };
  });
  const tot = scored.reduce((a, p) => a + p.score, 0);
  const ranked = scored.map(p => ({ ...p, share: p.score / tot })).sort((a, b) => b.share - a.share);
  const reqMin = 1180 + Math.round(Math.sin(tick * 0.4) * 220 + Math.random() * 120);

  const Slider = ({ k, label }) => (
    <div className="ap-slider">
      <div className="ap-slider-top"><span>{label}</span><b>{w[k]}%</b></div>
      <input type="range" min="0" max="100" value={w[k]}
        onChange={e => actions.updateRouting({ ...w, [k]: parseInt(e.target.value) })} />
    </div>
  );

  return (
    <div className="ap-page">
      <PageHead eyebrow="Network" title="Intelligent Routing" sub="Tune how requests are scored and dispatched to providers in realtime." />
      <div className="ap-grid-1-2">
        <div className="ap-card">
          <div className="ap-card-head"><h3>Routing weights</h3></div>
          <Slider k="latency" label="Latency" />
          <Slider k="price" label="Price" />
          <Slider k="reliability" label="Reliability" />
          <div className="ap-route-note"><Ic d={I.routing} s={15} /> Weights normalize automatically. Higher latency weight favors faster nodes.</div>
        </div>
        <div className="ap-card">
          <div className="ap-card-head"><h3>Provider distribution</h3><span className="ap-card-sub">{VY.fmtInt(reqMin)} req/min · {ranked.length} nodes</span></div>
          <table className="ap-table">
            <thead><tr><th>Provider</th><th>Region</th><th>Latency</th><th>Price</th><th>Reliability</th><th>Traffic share</th></tr></thead>
            <tbody>
              {ranked.map(p => (
                <tr key={p.id}>
                  <td className="mono">{p.id}</td>
                  <td className="dim">{p.region}</td>
                  <td className="mono">{p.liveLat}ms</td>
                  <td className="mono">{VY.fmt(p.price, 5)}</td>
                  <td className="mono">{(p.reliability * 100).toFixed(1)}%</td>
                  <td>
                    <div className="ap-share">
                      <div className="ap-share-bar"><div style={{ width: (p.share * 100) + '%' }} /></div>
                      <span className="mono">{(p.share * 100).toFixed(1)}%</span>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}

/* ---------------- SETTLEMENT ---------------- */
function Settlement({ state }) {
  const [filter, setFilter] = useState('');
  const rows = state.settlements.filter(s => !filter || s.cap.includes(filter) || s.consumer.includes(filter));
  const total = state.settlements.reduce((a, s) => a + s.cost, 0);
  return (
    <div className="ap-page">
      <PageHead eyebrow="Idle-powered" title="Settlement" sub="Realtime, per-request settlement history. No invoices, no batches." />
      <div className="ap-grid-3">
        <Stat label="Settled (lifetime)" value={VY.fmt(total, 4)} unit="VYRON" icon={I.settle} accent />
        <Stat label="Transactions" value={VY.fmtInt(state.settlements.length)} icon={I.pulse} />
        <Stat label="Avg / request" value={VY.fmt(state.settlements.length ? total / state.settlements.length : 0, 4)} unit="VYRON" icon={I.up} />
      </div>
      <div className="ap-card">
        <div className="ap-card-head">
          <h3>Settlement history</h3>
          <div className="ap-searchbox"><Ic d={I.search} s={15} /><input placeholder="Filter capability / consumer…" value={filter} onChange={e => setFilter(e.target.value)} /></div>
        </div>
        {rows.length === 0 ? <Empty text="No settlements match your filter." /> : (
          <table className="ap-table">
            <thead><tr><th>Time</th><th>Capability</th><th>Consumer</th><th>Cost</th><th>Status</th></tr></thead>
            <tbody>
              {rows.map(s => (
                <tr key={s.id}>
                  <td className="dim mono">{VY.ago(s.ts)}</td>
                  <td className="mono">{s.cap}</td>
                  <td className="mono dim">{s.consumer}</td>
                  <td className="mono pos">+{VY.fmt(s.cost, 4)}</td>
                  <td><Badge kind="green">{s.status}</Badge></td>
                </tr>
              ))}
            </tbody>
          </table>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { Dashboard, Services, Routing, Settlement, Empty });
