<?php
declare(strict_types=1);

$token = trim((string) ($_GET['t'] ?? $_GET['token'] ?? ''));
?>
<!doctype html>
<html lang="pt-BR">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Bulo - Acompanhar corrida</title>
  <link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css">
  <style>
    :root {
      color-scheme: light;
      --blue: #1167d8;
      --ink: #111827;
      --muted: #667085;
      --line: #d9e2ef;
      --paper: #ffffff;
      --soft: #f4f7fb;
      --green: #17a76f;
      --red: #e5484d;
      --amber: #f6a609;
    }

    * { box-sizing: border-box; }
    body {
      margin: 0;
      min-height: 100vh;
      background: var(--soft);
      color: var(--ink);
      font-family: Inter, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
    }

    .shell {
      display: grid;
      grid-template-rows: auto 1fr;
      min-height: 100vh;
    }

    header {
      background: var(--paper);
      border-bottom: 1px solid var(--line);
      padding: 14px clamp(14px, 3vw, 28px);
      display: flex;
      align-items: center;
      justify-content: space-between;
      gap: 16px;
    }

    .brand strong {
      display: block;
      font-size: 22px;
      line-height: 1.1;
    }

    .brand span, .updated {
      color: var(--muted);
      font-size: 13px;
    }

    .status-pill {
      display: inline-flex;
      align-items: center;
      gap: 8px;
      border-radius: 999px;
      background: #eaf2ff;
      color: #0757bf;
      font-weight: 700;
      padding: 9px 13px;
      white-space: nowrap;
    }

    .dot {
      width: 9px;
      height: 9px;
      border-radius: 99px;
      background: var(--blue);
    }

    main {
      display: grid;
      grid-template-columns: minmax(0, 1fr) 360px;
      gap: 16px;
      padding: 16px;
      min-height: 0;
    }

    #map {
      min-height: calc(100vh - 102px);
      border-radius: 12px;
      border: 1px solid var(--line);
      overflow: hidden;
      background: #dce8f3;
    }

    aside {
      display: flex;
      flex-direction: column;
      gap: 12px;
      min-width: 0;
    }

    .card {
      background: var(--paper);
      border: 1px solid var(--line);
      border-radius: 12px;
      padding: 16px;
      box-shadow: 0 8px 24px rgba(15, 23, 42, .06);
    }

    h1, h2, p { margin: 0; }
    h2 { font-size: 17px; margin-bottom: 10px; }
    .hero p { color: var(--muted); margin-top: 8px; line-height: 1.35; }
    .grid {
      display: grid;
      grid-template-columns: 1fr 1fr;
      gap: 10px;
    }
    .metric {
      border-radius: 10px;
      background: var(--soft);
      padding: 10px;
    }
    .metric span {
      display: block;
      color: var(--muted);
      font-size: 12px;
      margin-bottom: 4px;
    }
    .metric strong { font-size: 16px; }

    .timeline {
      display: grid;
      gap: 12px;
      margin-top: 6px;
    }
    .point {
      display: grid;
      grid-template-columns: 24px 1fr;
      gap: 10px;
      align-items: start;
    }
    .pin-dot {
      width: 16px;
      height: 16px;
      border-radius: 99px;
      margin-top: 2px;
      border: 3px solid #fff;
      box-shadow: 0 0 0 2px var(--blue);
      background: var(--blue);
    }
    .pin-dot.green { background: var(--green); box-shadow: 0 0 0 2px var(--green); }
    .pin-dot.red { background: var(--red); box-shadow: 0 0 0 2px var(--red); }
    .pin-dot.amber { background: var(--amber); box-shadow: 0 0 0 2px var(--amber); }
    .point small { color: var(--muted); display: block; margin-bottom: 2px; }
    .point strong { line-height: 1.25; }

    .notice {
      display: none;
      align-items: center;
      justify-content: center;
      min-height: calc(100vh - 80px);
      padding: 24px;
      text-align: center;
    }
    .notice .card { max-width: 480px; }
    .notice p { color: var(--muted); margin-top: 8px; }

    .map-pin {
      width: 24px;
      height: 24px;
      border-radius: 16px 16px 16px 4px;
      transform: rotate(-45deg);
      border: 3px solid #fff;
      box-shadow: 0 4px 12px rgba(15, 23, 42, .25);
    }
    .map-pin::after {
      content: "";
      display: block;
      width: 7px;
      height: 7px;
      margin: 5px;
      border-radius: 50%;
      background: #fff;
    }
    .map-pin.green { background: var(--green); }
    .map-pin.red { background: var(--red); }
    .map-pin.amber { background: var(--amber); }
    .map-pin.blue { background: var(--blue); }
    .car-marker {
      display: grid;
      place-items: center;
      width: 32px;
      height: 32px;
      border-radius: 999px;
      background: #111827;
      color: white;
      border: 3px solid white;
      box-shadow: 0 4px 14px rgba(15, 23, 42, .25);
      font-size: 17px;
      transform-origin: center;
    }

    @media (max-width: 900px) {
      main {
        grid-template-columns: 1fr;
        grid-template-rows: 52vh auto;
        padding: 10px;
      }
      #map { min-height: 52vh; border-radius: 10px; }
      aside { display: grid; grid-template-columns: 1fr; }
      header { align-items: flex-start; }
      .status-pill { font-size: 13px; padding: 8px 10px; }
    }
  </style>
</head>
<body>
  <div class="shell" id="app">
    <header>
      <div class="brand">
        <strong>Bulo</strong>
        <span>Acompanhamento seguro de corrida</span>
      </div>
      <div class="status-pill"><i class="dot"></i><span id="status">Carregando</span></div>
    </header>

    <main>
      <div id="map"></div>
      <aside>
        <section class="card hero">
          <h1>Corrida compartilhada</h1>
          <p>Esta tela mostra em tempo real o andamento da corrida pelo Bulo.</p>
          <p class="updated" id="updated">Atualizando...</p>
        </section>

        <section class="card">
          <h2>Informacoes</h2>
          <div class="grid">
            <div class="metric"><span>Motorista</span><strong id="motorista">Aguardando</strong></div>
            <div class="metric"><span>Passageiro</span><strong id="passageiro">-</strong></div>
            <div class="metric"><span>Categoria</span><strong id="categoria">-</strong></div>
            <div class="metric"><span>Paradas</span><strong id="paradas-count">0</strong></div>
          </div>
        </section>

        <section class="card">
          <h2>Trajeto</h2>
          <div class="timeline" id="timeline"></div>
        </section>
      </aside>
    </main>
  </div>

  <div class="notice" id="notice">
    <div class="card">
      <h1>Link indisponivel</h1>
      <p>Este acompanhamento expirou, foi encerrado ou o link esta incorreto.</p>
    </div>
  </div>

  <script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>
  <script>
    const token = <?= json_encode($token, JSON_UNESCAPED_SLASHES) ?>;
    const map = L.map('map', { zoomControl: true }).setView([-15.78, -47.93], 5);
    L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
      maxZoom: 19,
      attribution: '&copy; OpenStreetMap'
    }).addTo(map);

    const layers = {
      markers: L.layerGroup().addTo(map),
      planned: null,
      real: null
    };
    let fitted = false;

    function money(value) {
      const n = Number(value || 0);
      return n > 0 ? n.toLocaleString('pt-BR', { style: 'currency', currency: 'BRL' }) : '-';
    }

    function point(lat, lng) {
      if (lat === null || lng === null || lat === undefined || lng === undefined) return null;
      const a = Number(lat), b = Number(lng);
      if (!Number.isFinite(a) || !Number.isFinite(b)) return null;
      return [a, b];
    }

    function pin(color) {
      return L.divIcon({
        html: `<div class="map-pin ${color}"></div>`,
        className: '',
        iconSize: [24, 24],
        iconAnchor: [12, 24]
      });
    }

    function car(heading) {
      const deg = Number(heading || 0);
      return L.divIcon({
        html: `<div class="car-marker" style="transform: rotate(${deg}deg)">▲</div>`,
        className: '',
        iconSize: [32, 32],
        iconAnchor: [16, 16]
      });
    }

    function addMarker(label, pos, icon) {
      if (!pos) return;
      L.marker(pos, { icon }).bindPopup(label).addTo(layers.markers);
    }

    function timelineItem(color, label, text) {
      return `<div class="point"><i class="pin-dot ${color}"></i><div><small>${label}</small><strong>${text || '-'}</strong></div></div>`;
    }

    function draw(data) {
      const c = data.corrida;
      document.getElementById('status').textContent = c.status_label || c.status || 'Atualizando';
      document.getElementById('updated').textContent = `Atualizado em ${c.atualizado_em_servidor || ''}`;
      document.getElementById('motorista').textContent = c.motorista_nome || 'Aguardando';
      document.getElementById('passageiro').textContent = c.passageiro_nome || '-';
      document.getElementById('categoria').textContent = (c.categoria_veiculo || '-').toString();
      document.getElementById('paradas-count').textContent = (c.paradas || []).length;

      const timeline = [];
      timeline.push(timelineItem('green', 'Inicio', c.origem_endereco));
      (c.paradas || []).forEach((p, i) => timeline.push(timelineItem('amber', `Parada ${i + 1}`, p.endereco)));
      timeline.push(timelineItem('red', 'Destino', c.destino_endereco));
      document.getElementById('timeline').innerHTML = timeline.join('');

      layers.markers.clearLayers();
      if (layers.planned) map.removeLayer(layers.planned);
      if (layers.real) map.removeLayer(layers.real);

      const origem = point(c.origem_lat, c.origem_lng);
      const destino = point(c.destino_lat, c.destino_lng);
      const paradas = (c.paradas || []).map(p => point(p.lat, p.lng)).filter(Boolean);
      const passageiro = point(c.passageiro_lat, c.passageiro_lng) || origem;
      const motorista = point(c.motorista_lat, c.motorista_lng);
      const planejada = [origem, ...paradas, destino].filter(Boolean);
      const real = (c.pontos_rota || []).map(p => point(p.lat, p.lng)).filter(Boolean);

      addMarker('Inicio da corrida', origem, pin('green'));
      paradas.forEach((p, i) => addMarker(`Parada ${i + 1}`, p, pin('amber')));
      addMarker('Destino final', destino, pin('red'));
      addMarker('Passageiro', passageiro, pin('blue'));
      addMarker('Motorista', motorista, car(c.motorista_rumo));

      if (planejada.length > 1) {
        layers.planned = L.polyline(planejada, {
          color: '#697586',
          dashArray: '8 8',
          weight: 4,
          opacity: .75
        }).addTo(map);
      }
      if (real.length > 1) {
        layers.real = L.polyline(real, {
          color: '#1167d8',
          weight: 5,
          opacity: .92
        }).addTo(map);
      }

      if (!fitted) {
        const all = [...planejada, ...real, passageiro, motorista].filter(Boolean);
        if (all.length) {
          map.fitBounds(L.latLngBounds(all).pad(.25));
          fitted = true;
        }
      }
    }

    async function load() {
      try {
        const res = await fetch(`dados.php?t=${encodeURIComponent(token)}`, { cache: 'no-store' });
        const data = await res.json();
        if (!data.success) throw new Error(data.message || 'Link indisponivel');
        draw(data);
      } catch (_) {
        document.getElementById('app').style.display = 'none';
        document.getElementById('notice').style.display = 'flex';
      }
    }

    load();
    setInterval(load, 5000);
  </script>
</body>
</html>
