<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head th:replace="~{fragments/layout :: head('Live Tracking')}"></head>
<body>
<nav th:replace="~{fragments/layout :: adminbar}"></nav>

<!-- Leaflet (OpenStreetMap) -->
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css"/>
<script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>

<section>
    <div class="container">
        <div class="page-header">
            <h1>Live Fleet Tracking</h1>
            <span style="display:flex;gap:10px;align-items:center">
                <span id="trkCount" style="color:#888;font-size:13px"></span>
                <button class="btn btn-outline btn-sm" type="button" onclick="refresh()">&#8635; Refresh</button>
            </span>
        </div>

        <div class="tracking-layout">
            <div id="map" class="tracking-map"></div>
            <aside class="tracking-side">
                <h3>Vehicles</h3>
                <div id="trkList"><p style="color:#888;font-size:13px">Loading…</p></div>
            </aside>
        </div>
        <p style="color:#aaa;font-size:12px;margin-top:10px">
            Devices post positions to <code>POST /api/telematics/ingest</code> (header <code>X-API-KEY</code>). Map auto-refreshes every 15s.
        </p>
    </div>
</section>

<script>
let map, markers={};
function initMap(){
  map=L.map('map').setView([10.5276, 76.2144], 7); // Kerala
  L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
    {maxZoom:19, attribution:'&copy; OpenStreetMap'}).addTo(map);
}
function esc(s){return (s==null?'':String(s)).replace(/[&<>"]/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;'}[c]));}
function fmt(ts){ if(!ts)return '—'; const d=new Date(ts); return d.toLocaleString(); }

function refresh(){
  fetch('/admin/tracking/data').then(r=>r.json()).then(list=>{
    document.getElementById('trkCount').textContent=list.length+' tracked vehicle'+(list.length===1?'':'s');
    const side=document.getElementById('trkList');
    if(!list.length){ side.innerHTML='<p style="color:#888;font-size:13px">No vehicles are reporting a location yet.</p>'; return; }
    const bounds=[];
    side.innerHTML=list.map(v=>`
      <div class="trk-item" onclick="focusCar(${v.carId})">
        <div class="trk-dot ${v.live?'on':'off'}"></div>
        <div>
          <div class="trk-name">${esc(v.carName)} <small style="color:#888">${esc(v.regNo)}</small></div>
          <div class="trk-meta">${v.speedKph!=null?Math.round(v.speedKph)+' km/h':'parked'} · ${v.live?'live':'stale'}</div>
        </div>
      </div>`).join('');
    list.forEach(v=>{
      const ll=[v.latitude, v.longitude]; bounds.push(ll);
      const popup=`<b>${esc(v.carName)}</b><br>${esc(v.regNo)}<br>
        Speed: ${v.speedKph!=null?Math.round(v.speedKph)+' km/h':'—'}<br>
        Odometer: ${v.odometer!=null?v.odometer+' km':'—'}<br>
        Ignition: ${v.ignitionOn==null?'—':(v.ignitionOn?'ON':'OFF')}<br>
        <small>Updated ${fmt(v.updatedAt)}</small>`;
      if(markers[v.carId]){ markers[v.carId].setLatLng(ll).setPopupContent(popup); }
      else { markers[v.carId]=L.marker(ll).addTo(map).bindPopup(popup); }
      markers[v.carId]._live=v.live;
    });
    if(bounds.length && !window._fitted){ map.fitBounds(bounds,{padding:[40,40],maxZoom:12}); window._fitted=true; }
  }).catch(()=>{document.getElementById('trkList').innerHTML='<p style="color:#c00;font-size:13px">Failed to load locations.</p>';});
}
function focusCar(id){ const m=markers[id]; if(m){ map.setView(m.getLatLng(),14); m.openPopup(); } }

initMap();
refresh();
setInterval(refresh, 15000);
</script>

<footer th:replace="~{fragments/layout :: footer}"></footer>
</body>
</html>
