const API_URL = '/api/location';
const POLL_INTERVAL_MS = 10000;
const FA_SVG_URL = 'https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@6.5.0/svgs/solid/truck-fast.svg';

async function ensureLeaflet() {
  if (window.L) return;
  await new Promise((resolve, reject) => {
    const check = () => (window.L ? resolve() : null);
    const existing = Array.from(document.scripts).find((s) => s.src.includes('leaflet'));
    if (existing) {
      existing.addEventListener('load', () => { check(); }, { once: true });
      existing.addEventListener('error', reject, { once: true });
      // fallback: tentar após pequeno atraso
      setTimeout(check, 300);
      return;
    }
    const s = document.createElement('script');
    s.src = 'https://cdn.jsdelivr.net/npm/leaflet@1.9.4/dist/leaflet.js';
    s.onload = () => { check(); };
    s.onerror = reject;
    document.head.appendChild(s);
  });
}

function setStatus(text, cls) {
  const el = document.getElementById('status');
  if (!el) return;
  el.textContent = text;
  el.className = cls || '';
}

function setLastUpdate(text) {
  const el = document.getElementById('last-update');
  el.textContent = text;
}

function formatTs(tsMillis) {
  try {
    const d = new Date(tsMillis);
    return d.toLocaleString('pt-BR');
  } catch { return ''; }
}

  function MapTracker() {
  const mapRef = React.useRef(null);
  const leafletRef = React.useRef({ map: null, marker: null, pinIcon: null, dotIcon: null, mode: 'bola' });
  const followRef = React.useRef(true);
  const faSvgRef = React.useRef(null);

  React.useEffect(() => {
    let intervalId;
    let disposed = false;

  async function init() {
      try {
        await ensureLeaflet();
      } catch (e) {
        console.error('Falha ao carregar Leaflet', e);
        setStatus('Falha ao carregar Leaflet.', 'status-error');
        return;
      }
      if (disposed) return;

      const div = document.createElement('div');
      div.className = 'map';
      mapRef.current.appendChild(div);

      let initPos = [-22.53505385437, -42.986899246802];
      try {
        if (!faSvgRef.current) {
          const rSvg = await fetch(FA_SVG_URL, { cache: 'force-cache' });
          if (rSvg.ok) {
            const txt = await rSvg.text();
            faSvgRef.current = txt;
          }
        }
      } catch {}
      try {
        const r = await fetch(API_URL, { cache: 'no-store' });
        const d = await r.json();
        if (typeof d.lat === 'number' && typeof d.lng === 'number') {
          initPos = [d.lat, d.lng];
        }
      } catch {}
      const map = L.map(div).setView(initPos, 17);
      const googleHybrid = L.tileLayer('https://{s}.google.com/vt/lyrs=s,h&x={x}&y={y}&z={z}', {
        maxZoom: 22,
        maxNativeZoom: 22,
        subdomains: ['mt0', 'mt1', 'mt2', 'mt3'],
        attribution: '© Google',
      });
      googleHybrid.addTo(map);

      leafletRef.current.map = map;

      // Sem controles de topo; seguir permanece ativo por padrão

      // Pin clássico (DivIcon com SVG), tamanho fixo em pixels
      function makePinIcon() {
        const size = 72; // px
        const half = size / 2;
        const svg = `
          <svg width="${size}" height="${size}" viewBox="0 0 64 64" xmlns="http://www.w3.org/2000/svg">
            <defs>
              <filter id="ds" x="-20%" y="-20%" width="140%" height="140%">
                <feDropShadow dx="0" dy="2" stdDeviation="2" flood-color="rgba(0,0,0,0.35)"/>
              </filter>
            </defs>
            <g filter="url(#ds)">
              <circle cx="32" cy="22" r="18" fill="#FFD400" stroke="#333" stroke-width="3" />
              <path d="M32 60 L22 38 L42 38 Z" fill="#FFD400" stroke="#333" stroke-width="3" stroke-linejoin="round" />
            </g>
          </svg>`;
        return L.divIcon({
          className: 'pin-icon',
          html: svg,
          iconSize: [size, size],
          iconAnchor: [half, size - 2],
          popupAnchor: [0, -(size - 2)],
        });
      }
      leafletRef.current.pinIcon = makePinIcon();
      function sizeForZoom(z) {
        const s = Math.round(48 + 4 * (z - 17));
        return Math.max(24, Math.min(72, s));
      }
      function colorizeSvg(svg, color) {
        if (!svg) return svg;
        let s = svg
          .replace(/fill="currentColor"/g, `fill="${color}"`)
          .replace(/stroke="currentColor"/g, `stroke="${color}"`)
          .replace(/fill:\s*currentColor/g, `fill:${color}`)
          .replace(/stroke:\s*currentColor/g, `stroke:${color}`)
          .replace(/<path([^>]*?)>/g, (m, attrs) => (attrs.includes('fill=') ? `<path${attrs}>` : `<path${attrs} fill="${color}">`));
        s = s.replace(/<svg([^>]*?)>/, (m, attrs) => `<svg${attrs} style="color:${color}">`);
        return s;
      }
      function makeTruckIconForZoom(z) {
        const size = sizeForZoom(z);
        const half = size / 2;
        const faSvg = faSvgRef.current ? colorizeSvg(faSvgRef.current, '#FFD43B') : null;
        const html = faSvg
          ? `<div style="display:inline-block;position:relative;width:${size}px;height:${size}px;color:#FFD43B;filter:drop-shadow(0 2px 2px rgba(0,0,0,0.35))">
               <div style="position:absolute;inset:0">${faSvg}</div>
             </div>`
          : `<div style="display:inline-block;position:relative;width:${size}px;height:${size}px;filter:drop-shadow(0 2px 2px rgba(0,0,0,0.35))">
               <i class="fa-solid fa-truck-fast" style="font-size:${size}px;line-height:${size}px;color:#FFD43B;position:absolute;inset:0;"></i>
             </div>`;
        return L.divIcon({
          className: 'truck-fast-icon',
          html,
          iconSize: [size, size],
          iconAnchor: [half, half],
          popupAnchor: [0, -half],
        });
      }
      leafletRef.current.dotIcon = makeTruckIconForZoom(map.getZoom());
      // Mantém função de atualização como no-op para compatibilidade com upload
      window.__updateTruckIcon = () => {};

      // Modo padrão: Bola (sem seletor na UI)
      const setMode = (m) => { leafletRef.current.mode = m; if (leafletRef.current.marker) { leafletRef.current.marker.setIcon(m === 'pin' ? leafletRef.current.pinIcon : leafletRef.current.dotIcon); } };
      setMode('bola');

      map.on('zoomend', () => {
        leafletRef.current.dotIcon = makeTruckIconForZoom(map.getZoom());
        if (leafletRef.current.marker && leafletRef.current.mode !== 'pin') {
          leafletRef.current.marker.setIcon(leafletRef.current.dotIcon);
        }
      });

      const updateFromApi = async () => {
        try {
          const res = await fetch(API_URL, { cache: 'no-store' });
          const data = await res.json();

          if (data && data.error === 'stale') {
            setStatus(`Sem dados recentes (TTL excedido). Atualizado: ${data.updated_at}`, 'status-stale');
            setLastUpdate('');
            if (leafletRef.current.marker) {
              leafletRef.current.marker.remove();
              leafletRef.current.marker = null;
            }
            return;
          }

          const { lat, lng, update_ts, updated_at } = data;
          if (typeof lat !== 'number' || typeof lng !== 'number') {
            setStatus('Resposta inválida: latitude/longitude ausentes.', 'status-error');
            return;
          }

          const pos = [lat, lng];
          const { marker, pinIcon, dotIcon, mode } = leafletRef.current;
          if (!marker) {
            leafletRef.current.marker = L.marker(pos, { icon: mode === 'pin' ? pinIcon : dotIcon }).addTo(map);
          } else {
            leafletRef.current.marker.setLatLng(pos);
            leafletRef.current.marker.setIcon(mode === 'pin' ? pinIcon : dotIcon);
          }

          if (followRef.current) {
            map.setView(pos, map.getZoom(), { animate: true });
          }

          setStatus('Dados atualizados.', 'status-ok');
          const tsText = update_ts ? formatTs(update_ts) : updated_at || '';
          setLastUpdate(tsText ? `Última atualização: ${tsText}` : '');
        } catch (err) {
          console.error(err);
          setStatus('Erro ao buscar localização.', 'status-error');
        }
      };

      // primeira atualização imediata
      updateFromApi();
      intervalId = setInterval(updateFromApi, POLL_INTERVAL_MS);
    }

    init();

    return () => {
      disposed = true;
      if (intervalId) clearInterval(intervalId);
      if (leafletRef.current.map) leafletRef.current.map.remove();
    };
  }, []);

  return <div ref={mapRef} style={{ height: '100%' }} />;
}

function App() {
  return (
    <React.StrictMode>
      <MapTracker />
    </React.StrictMode>
  );
}

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