<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>OSM Roads Debug</title>
  <style>
    body {
      font-family: Arial, sans-serif;
      margin: 16px;
    }
    #meta {
      margin-bottom: 12px;
    }
    #map {
      width: 900px;
      height: 600px;
      border: 1px solid #ccc;
      display: block;
    }
    #empty {
      color: #aa0000;
      margin-top: 8px;
    }
  </style>
</head>
<body>
  <div id="meta">
    <div><strong>lat:</strong> {{ lat }} <strong>long:</strong> {{ long }} <strong>scale:</strong> {{ scale }}</div>
    <div><strong>segments:</strong> <span id="count">0</span></div>
  </div>
  <svg id="map" viewBox="0 0 900 600" xmlns="http://www.w3.org/2000/svg"></svg>
  <div id="empty" hidden>No road segments returned. This is a data issue.</div>

  <script>
    const roads = JSON.parse('{{ roads_json|escapejs }}');
    const svg = document.getElementById("map");
    const empty = document.getElementById("empty");
    document.getElementById("count").textContent = String(roads.length);

    if (!roads.length) {
      empty.hidden = false;
    } else {
      const pts = [];
      for (const r of roads) {
        const rad = (r.yaw || 0) * Math.PI / 180;
        const half = (r.length || 0) / 2;
        const dx = Math.cos(rad) * half;
        const dz = Math.sin(rad) * half;
        pts.push([r.x - dx, r.z - dz]);
        pts.push([r.x + dx, r.z + dz]);
      }

      let minX = Infinity, minZ = Infinity, maxX = -Infinity, maxZ = -Infinity;
      for (const [x, z] of pts) {
        if (x < minX) minX = x;
        if (z < minZ) minZ = z;
        if (x > maxX) maxX = x;
        if (z > maxZ) maxZ = z;
      }

      const width = maxX - minX || 1;
      const height = maxZ - minZ || 1;
      const pad = 10;
      const scaleX = (900 - pad * 2) / width;
      const scaleY = (600 - pad * 2) / height;
      const scale = Math.min(scaleX, scaleY);

      for (const r of roads) {
        const rad = (r.yaw || 0) * Math.PI / 180;
        const half = (r.length || 0) / 2;
        const dx = Math.cos(rad) * half;
        const dz = Math.sin(rad) * half;

        const x1 = (r.x - dx - minX) * scale + pad;
        const y1 = 600 - ((r.z - dz - minZ) * scale + pad);
        const x2 = (r.x + dx - minX) * scale + pad;
        const y2 = 600 - ((r.z + dz - minZ) * scale + pad);

        const line = document.createElementNS("http://www.w3.org/2000/svg", "line");
        line.setAttribute("x1", x1.toFixed(2));
        line.setAttribute("y1", y1.toFixed(2));
        line.setAttribute("x2", x2.toFixed(2));
        line.setAttribute("y2", y2.toFixed(2));
        line.setAttribute("stroke", r.color || "#666666");
        line.setAttribute("stroke-width", Math.max((r.width || 1) * scale * 0.1, 0.5));
        line.setAttribute("stroke-linecap", "round");
        svg.appendChild(line);
      }
    }
  </script>
</body>
</html>
