@extends('layouts.app')
@section('title',"Router: {$router->name}")


@section('content')
  <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:10px">

  @php
  $resolvedHost = \App\Support\RouterHost::resolve($router);
  $path = ($router->connection_via === 'vpn' || $router->prefer_vpn) ? 'VPN' : ($router->ddns_host ? 'DDNS' : 'Public IP');
@endphp
<div class="muted">{{ $path }} → {{ $resolvedHost }} • Port {{ $router->api_port }} • {{ $router->use_tls ? 'TLS' : 'No TLS' }}</div>

    <div>
      <h1 style="margin:0 0 6px">{{ $router->name }}</h1>
      <div class="muted">{{ $router->host }} • {{ $router->model ?? '—' }} • {{ strtoupper($router->vendor) }}</div>
    </div>
    <div style="display:flex;gap:8px">

      @php $vpn = \App\Models\VpnClient::where('router_id',$router->id)->latest()->first(); @endphp
  @if($vpn && $vpn->status === 'active')
    <a class="btn-ghost" href="{{ route('vpn.show',$vpn) }}">OpenVPN</a>
  @else
    <a class="btn-ghost" href="{{ route('vpn.create',$router) }}">Create OpenVPN</a>
  @endif
      <button class="btn-ghost" onclick="pollNow()">Poll now</button>
      <a class="btn-ghost" href="{{ route('routers.edit',$router) }}">Edit</a>
      <a class="btn" href="{{ route('routers.index') }}">Back</a>
    </div>
  </div>

  <div class="cards">
    <div class="card wide">
      <strong>System</strong>
      <div class="muted" id="sys-sub" style="margin-bottom:8px">—</div>
      <div style="display:grid;grid-template-columns:repeat(4,1fr);gap:10px">
        <div><div class="label">Status</div><div id="r-status" class="value">—</div></div>
        <div><div class="label">CPU</div><div id="r-cpu" class="value">—%</div></div>
        <div><div class="label">RAM</div><div id="r-ram" class="value">—</div></div>
        <div><div class="label">HDD</div><div id="r-hdd" class="value">—</div></div>
      </div>
    </div>

    <div class="card wide">
      <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:6px">
        <strong>Live Traffic</strong>
        <span class="muted" id="iface-name">all-interfaces</span>
      </div>
      <svg id="traffic" viewBox="0 0 600 160"
           style="width:100%;height:160px;background:var(--bb-elev);border:1px solid var(--bb-border);border-radius:12px"></svg>
      <div class="muted" style="font-size:12px;margin-top:6px">Polling every 5s.</div>
    </div>

    <div class="card full">
      <strong>Interfaces</strong>
      <table id="iface-table" style="margin-top:8px">
        <thead><tr><th>Name</th><th>State</th><th>Rx (bps)</th><th>Tx (bps)</th></tr></thead>
        <tbody></tbody>
      </table>
    </div>
  </div>

  <script>
    const RID = {{ $router->id }};
    let trafficPts = []; // [{t, rx, tx}]; keep last 60

    function bytes(n){ if(!n) return '—'; const u=['B','KB','MB','GB']; let i=0; while(n>1024 && i<u.length-1){ n/=1024; i++ } return n.toFixed(1)+' '+u[i]; }
    function pct(free,total){ if(!total) return '—'; return Math.round((1 - (free/total))*100) + '% used'; }

    async function fetchMetrics(){
      const r = await fetch(`{{ route('routers.metrics',$router) }}`);
      const j = await r.json();
      document.getElementById('r-status').textContent = j.status;
      document.getElementById('r-cpu').textContent = (j.cpu_load ?? 0) + '%';
      document.getElementById('r-ram').textContent = pct(j.memory.free, j.memory.total);
      document.getElementById('r-hdd').textContent = pct(j.hdd.free, j.hdd.total);
      document.getElementById('sys-sub').textContent = `${j.model ?? '—'} • ${j.board_name ?? '—'} • SN:${j.serial ?? '—'} • Seen: ${j.last_seen ?? '—'}`;
    }

    async function fetchIfaces(){
      const r = await fetch(`{{ route('routers.interfaces',$router) }}`);
      const list = await r.json();
      const tb = document.querySelector('#iface-table tbody');
      tb.innerHTML = '';
      list.forEach(x=>{
        const tr = document.createElement('tr');
        tr.innerHTML = `<td>${x.name}</td>
                        <td>${x.running ? 'running' : 'down'}</td>
                        <td>${x.rx_bps ?? '—'}</td>
                        <td>${x.tx_bps ?? '—'}</td>`;
        tb.appendChild(tr);
      });
      // Fake aggregate traffic sample from sum (rx_bps/tx_bps)
      const rx = list.reduce((a,b)=> a + (b.rx_bps||0), 0);
      const tx = list.reduce((a,b)=> a + (b.tx_bps||0), 0);
      trafficPts.push({t:Date.now(), rx, tx});
      if(trafficPts.length>60) trafficPts.shift();
      drawTraffic();
    }

    function drawTraffic(){
      const svg = document.getElementById('traffic');
      const W=600,H=160,P=10;
      svg.innerHTML='';
      const ptsRx = trafficPts.map((p,i)=>[P + i*((W-2*P)/Math.max(1,(trafficPts.length-1))), H-P - (p.rx? Math.min(1, p.rx/1_000_000)*(H-2*P):0)]);
      const ptsTx = trafficPts.map((p,i)=>[P + i*((W-2*P)/Math.max(1,(trafficPts.length-1))), H-P - (p.tx? Math.min(1, p.tx/1_000_000)*(H-2*P):0)]);
      const toAttr = arr => arr.map(a=>a.join(',')).join(' ');
      const mk = (color)=> {
        const pl = document.createElementNS('http://www.w3.org/2000/svg','polyline');
        pl.setAttribute('fill','none'); pl.setAttribute('stroke', color); pl.setAttribute('stroke-width','2.5');
        return pl;
      };
      const rxPl = mk(getComputedStyle(document.body).getPropertyValue('--bb-primary-1').trim() || '#3b82f6');
      const txPl = mk(getComputedStyle(document.body).getPropertyValue('--bb-primary-2').trim() || '#0ea5e9');
      rxPl.setAttribute('points', toAttr(ptsRx)); txPl.setAttribute('points', toAttr(ptsTx));
      svg.appendChild(rxPl); svg.appendChild(txPl);
    }

    async function pollNow(){
      await fetch(`{{ route('routers.poll',$router) }}`, {method:'POST', headers:{'X-CSRF-TOKEN':'{{ csrf_token() }}'}});
      fetchMetrics(); fetchIfaces();
    }

    // start loops
    fetchMetrics(); fetchIfaces();
    setInterval(fetchMetrics, 10000);
    setInterval(fetchIfaces, 5000);
  </script>
@endsection
