<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <title>Building Twin — Random Stadium (Backend)</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <link href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css" rel="stylesheet" crossorigin="">
  <script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js" crossorigin=""></script>

  <style>
    html, body { height:100%; margin:0; background:#0b1220; }
    #map { position:fixed; inset:0; }
    #legend {
      position: fixed; top: 12px; left: 12px; z-index: 1000;
      background: #0f172a; color: #e5e7eb; padding: 10px 12px; border-radius: 10px;
      font-family: ui-sans-serif, system-ui, -apple-system, Segoe UI, Roboto, sans-serif;
      box-shadow: 0 10px 30px rgba(0,0,0,.35); font-size: 12px; line-height: 1.25;
    }
    .pill{display:inline-block; padding:2px 6px; border-radius:999px; margin-right:6px}
    .p-field{background:#16a34a;color:#052e16}
    .p-stands{background:#64748b;color:#0b1220}
    .p-conc{background:#94a3b8;color:#0b1220}
    .k-org{background:#0ea5e9} .k-rec{background:#10b981}
    .k-lf{background:#8b5cf6} .k-sp{background:#b45309}
    .k-dt{background:#7c3aed}

    .btn { background:#1f2937; border:1px solid #334155; color:#e5e7eb; 
       padding:6px 10px; border-radius:8px; cursor:pointer }
    .btn:hover { background:#111827; }

  </style>
</head>
<body>
  <div id="legend">
    <div style="font-weight:600; margin-bottom:6px;">Random Stadium (backend)</div>
    <div style="margin-bottom:6px">
      <span class="pill p-field">Field</span>
      <span class="pill p-stands">Stands</span>
      <span class="pill p-conc">Concourse</span>
    </div>
    <div>Bins:
      <span class="pill k-rec">recyclable</span>
      <span class="pill k-org">organic</span>
      <span class="pill k-lf">landfill</span>
      <span class="pill k-sp">special</span>
      <span class="pill k-dt">dry_toilet</span>
    </div>
    <div style="opacity:.7; margin-top:6px">
      Tip: add <code>?seed=123</code> to make it deterministic.
    </div>
    <div style="margin-top:8px">
        <button id="btnBabylon" class="btn">Open 3D Banorte Stadium</button>
    </div>

  </div>

  <div id="map"></div>

  <script>
    // Map (local flat plane)
    const map = L.map('map', { crs: L.CRS.Simple, minZoom:-5, maxZoom:5, zoomSnap:0.25 }).setView([0,0], 0);

    // Faint grid background
    const grid = L.gridLayer();
    grid.createTile = function(){
      const c = document.createElement('canvas'); c.width=256; c.height=256;
      const ctx=c.getContext('2d'); ctx.strokeStyle='#1f2937'; ctx.lineWidth=1;
      for(let i=0;i<=256;i+=32){ ctx.beginPath(); ctx.moveTo(i,0); ctx.lineTo(i,256); ctx.stroke();
                                 ctx.beginPath(); ctx.moveTo(0,i); ctx.lineTo(256,i); ctx.stroke(); }
      return c;
    };
    grid.addTo(map);

    const spacesLayer = L.geoJSON(null, {
      style: f => {
        const t = (f.properties?.type || "").toLowerCase();
        const fill =
          t === "field"     ? "#16a34a" :
          t === "concourse" ? "#94a3b8" :
          t === "stands"    ? "#64748b" : "#9ca3af";
        return { color:"#0b1220", weight:0.6, fillColor:fill, fillOpacity:0.35 };
      }
    }).addTo(map);

    const binsLayer = L.geoJSON(null, {
      pointToLayer: (f, ll) => {
        const k = (f.properties?.kind || "").toLowerCase();
        const fill =
          k==="organic"     ? "#0ea5e9" :
          k==="recyclable"  ? "#10b981" :
          k==="landfill"    ? "#8b5cf6" :
          k==="special"     ? "#b45309" :
          k==="dry_toilet"  ? "#7c3aed" :
                              "#e5e7eb";
        return L.circleMarker(ll, { radius:6, color:"#0b1220", weight:1, fillColor:fill, fillOpacity:0.95 });
      },
      onEachFeature: (f, layer) => {
        const p = f.properties || {};
        layer.bindPopup(`<b>${p.kind || "bin"}</b><br/>id: ${p.id || "-"}<br/>capacity: ${p.capacity_l ?? "-"} L`);
      }
    }).addTo(map);

    function fetchStadium() {
      const seed = new URLSearchParams(location.search).get("seed") || Date.now();
      fetch(`/building/api/random/stadium/?seed=${seed}`)
        .then(r => r.json())
        .then(data => {
          spacesLayer.clearLayers().addData(data.spaces);
          binsLayer.clearLayers().addData(data.bins);
          const group = L.featureGroup([spacesLayer, binsLayer]);
          try { map.fitBounds(group.getBounds().pad(0.12)); } catch(e){}
        })
        .catch(err => console.error("Failed to fetch stadium:", err));
    }

    // Auto-generate on load
    fetchStadium();

    // Open Babylon 3D viewer, preserving current query params
    document.getElementById('btnBabylon').onclick = () => {
    const params = new URLSearchParams(location.search);
    if (!params.has('seed')) params.set('seed', Date.now());   // keep deterministic if you passed one
    // Change the path below if your Babylon route differs
    location.href = `/building/twin/wire/babylon/?${params.toString()}`;
    };


  </script>
</body>
</html>
