<div class="row">

  <!-- Left Card: Route Activity by Zone -->
  <div class="col-xl-7">
    <div class="card">
      <div class="d-flex card-header justify-content-between align-items-center">
        <h4 class="header-title mb-0">Route Activity by Zone</h4>

        <div class="d-flex align-items-center gap-2">
          <a href="{% url 'pxy_building_digital_twins:viewer' %}"
             class="btn btn-sm btn-outline-primary" target="_blank" rel="noopener">
            Open Twin Viewer
          </a>
          <div class="dropdown">
            <a href="#" class="dropdown-toggle arrow-none card-drop" data-bs-toggle="dropdown" aria-expanded="false">
              <i class="ri-more-2-fill"></i>
            </a>
            <div class="dropdown-menu dropdown-menu-animated dropdown-menu-end">
              <a href="javascript:void(0);" class="dropdown-item">Live Status</a>
              <a href="javascript:void(0);" class="dropdown-item">Route Density</a>
              <a href="javascript:void(0);" class="dropdown-item">Export KML</a>
              <a href="javascript:void(0);" class="dropdown-item">Show Anomalies</a>
            </div>
          </div>
        </div>
      </div>

      <div class="card-body">
        <div class="row g-3">
          <div class="col-lg-8">
            <div id="stadium-map" class="mt-1" style="height:317px;"></div>
            <!-- keep this hidden so theme scripts targeting it won't explode -->
            <div id="world-map-markers" class="d-none"></div>
          </div>
          <div class="col-lg-4" dir="ltr">
            <div class="zone-chart-wrap">
              <div id="zone-chart" class="apex-charts"></div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>

  <!-- Right Card: Material Volume Breakdown -->
  <div class="col-xl-5">
    <div class="card">
      <div class="d-flex card-header justify-content-between align-items-center">
        <h4 class="header-title">Material Volume Breakdown</h4>
        <a href="javascript:void(0);" class="btn btn-sm btn-info">Export <i class="ri-download-line ms-1"></i></a>
      </div>

      <div class="card-body p-0">
        <div class="table-responsive">
          <table class="table table-borderless table-hover table-nowrap table-centered m-0">
            <thead class="border-top border-bottom bg-light-subtle border-light">
              <tr>
                <th class="py-1">Material</th>
                <th class="py-1">Avg. Weight</th>
                <th class="py-1">Pickups</th>
                <th class="py-1">Total Collected</th>
                <th class="py-1">Source</th>
              </tr>
            </thead>
            <tbody>
              <tr><td>Organic</td><td>14.2 kg</td><td>214</td><td>3,452 kg</td><td>AR App</td></tr>
              <tr><td>Plastics</td><td>7.9 kg</td><td>182</td><td>1,436 kg</td><td>WhatsApp Bot</td></tr>
              <tr><td>Paper</td><td>6.1 kg</td><td>98</td><td>689 kg</td><td>Manual Entry</td></tr>
              <tr><td>Glass</td><td>9.4 kg</td><td>47</td><td>442 kg</td><td>Telegram Bot</td></tr>
              <tr><td>Metal</td><td>4.5 kg</td><td>36</td><td>162 kg</td><td>Facebook Pages</td></tr>
              <tr><td>Textiles</td><td>3.1 kg</td><td>22</td><td>68 kg</td><td>AR App</td></tr>
            </tbody>
          </table>
        </div>
        <div class="text-center">
          <a href="#!" class="text-primary text-decoration-underline fw-bold btn mb-2">View All</a>
        </div>
      </div>
    </div>
  </div>

</div>

<style>
  #stadium-map {
    background:#0b0f19;
    border-radius:.5rem;
    overflow:hidden;
  }
  .stadium-svg { width:100%; height:100%; display:block; }
  .stadium-svg .bin { transition: transform .12s ease; cursor:pointer; }
  .stadium-svg .bin:hover { transform: scale(1.12); }

  /* donut container: center + cap size so it doesn't spill */
  .zone-chart-wrap{
    min-height:317px;
    display:flex; align-items:center; justify-content:center;
  }
  #zone-chart{ width:100%; max-width:340px; height:280px; }
</style>

<script>
/* Patch ApexCharts so "Element not found" never hard-errors */
(function(){
  function patch(){
    if (!window.ApexCharts || window.__ApexSafe__) return;
    const Orig = window.ApexCharts;
    function ensure(el){
      if (typeof el === "string") el = document.querySelector(el);
      if (el) return el;
      let sink = document.getElementById("__apx_sink__");
      if (!sink){
        sink = document.createElement("div");
        sink.id="__apx_sink__";
        sink.style.cssText="position:absolute;left:-9999px;top:-9999px;width:1px;height:1px;overflow:hidden;";
        document.body.appendChild(sink);
      }
      return sink;
    }
    function Safe(el, opts){ return new Orig(ensure(el), opts); }
    Object.getOwnPropertyNames(Orig).forEach(k=>{ try{ Safe[k]=Orig[k]; }catch(_){} });
    Safe.prototype = Orig.prototype;
    window.ApexCharts = Safe;
    window.__ApexSafe__ = true;
  }
  patch(); document.addEventListener("DOMContentLoaded", patch);
})();
</script>

<script>
/* ----------------------- Stadium renderer (pure SVG) + Zone donut ----------------------- */
(function(){
  const macroColors = {
    "Cabecera Norte":"#60a5fa",
    "Cabecera Sur":"#34d399",
    "Lateral Oriente":"#fbbf24",
    "Lateral Poniente":"#f87171"
  };

  function buildExampleBins(){
    const bins = [];
    const count = 56, cx = 1000, cy = 700, rx = 720, ry = 500;
    for (let i=0;i<count;i++){
      const a = (i/count) * Math.PI * 2;
      const x = cx + rx * Math.cos(a);
      const y = cy + ry * Math.sin(a);
      let macro;
      if (a >= 7*Math.PI/4 || a < Math.PI/4) macro = "Lateral Oriente";
      else if (a < 3*Math.PI/4)               macro = "Cabecera Norte";
      else if (a < 5*Math.PI/4)               macro = "Lateral Poniente";
      else                                     macro = "Cabecera Sur";
      const kg = Math.round(8 + 10*Math.abs(Math.cos(a)) + (Math.random()*3|0));
      bins.push({ id:`SEC-${i+101}`, x, y, kg, macro });
    }
    return bins;
  }

  function drawStadium(host, bins){
    host.innerHTML = "";
    const NS = "http://www.w3.org/2000/svg";
    const svg = document.createElementNS(NS,"svg");
    svg.setAttribute("viewBox","0 0 2000 1400");
    svg.setAttribute("preserveAspectRatio","xMidYMid meet");
    svg.classList.add("stadium-svg");

    const defs = document.createElementNS(NS,"defs");
    defs.innerHTML = `
      <radialGradient id="bgGrad">
        <stop offset="0%"  stop-color="#0b0f19"/>
        <stop offset="70%" stop-color="#0b0f19"/>
        <stop offset="100%" stop-color="#0a0e18"/>
      </radialGradient>`;
    svg.appendChild(defs);

    const bg = document.createElementNS(NS,"rect");
    bg.setAttribute("width","2000"); bg.setAttribute("height","1400");
    bg.setAttribute("fill","url(#bgGrad)");
    svg.appendChild(bg);

    // Field
    const field = document.createElementNS(NS,"rect");
    field.setAttribute("x", 1000-550);
    field.setAttribute("y", 700-360);
    field.setAttribute("width", 1100);
    field.setAttribute("height", 720);
    field.setAttribute("rx", 26);
    field.setAttribute("fill", "#0d7d3b");
    field.setAttribute("stroke", "#b8f7c0");
    field.setAttribute("stroke-width", "8");
    svg.appendChild(field);

    // Mid line + center circle
    const mid = document.createElementNS(NS,"line");
    mid.setAttribute("x1","1000"); mid.setAttribute("y1", 700-360);
    mid.setAttribute("x2","1000"); mid.setAttribute("y2", 700+360);
    mid.setAttribute("stroke","#b8f7c0"); mid.setAttribute("stroke-width","6"); mid.setAttribute("opacity","0.8");
    svg.appendChild(mid);
    const cc = document.createElementNS(NS,"circle");
    cc.setAttribute("cx","1000"); cc.setAttribute("cy","700"); cc.setAttribute("r","110");
    cc.setAttribute("fill","none"); cc.setAttribute("stroke","#b8f7c0"); cc.setAttribute("stroke-width","6"); cc.setAttribute("opacity","0.8");
    svg.appendChild(cc);

    // Stands rings
    function ellipse(cx, cy, rx, ry, stroke, sw){
      const e = document.createElementNS(NS,"ellipse");
      e.setAttribute("cx", cx); e.setAttribute("cy", cy);
      e.setAttribute("rx", rx); e.setAttribute("ry", ry);
      e.setAttribute("fill","none"); e.setAttribute("stroke", stroke);
      e.setAttribute("stroke-width", sw); return e;
    }
    svg.appendChild(ellipse(1000,700, 820, 580, "#2a3142", 30));
    svg.appendChild(ellipse(1000,700, 900, 640, "#202636", 30));

    // Title
    function label(y, size, txt, fill, weight=700, opacity=.9){
      const t=document.createElementNS(NS,"text");
      t.setAttribute("x","1000"); t.setAttribute("y",String(y));
      t.setAttribute("text-anchor","middle");
      t.setAttribute("fill",fill); t.setAttribute("font-size",size);
      t.setAttribute("font-weight",weight); t.setAttribute("opacity",opacity);
      t.textContent=txt; return t;
    }
    svg.appendChild(label(120,44,"Estadio — Actividad de Recolección","#e5e7eb",700,.95));
    svg.appendChild(label(165,28,"Burbujas ∝ kg por microzona · color = macrozona","#9ca3af",500,.95));

    // Bins
    bins.forEach(b=>{
      const r = Math.max(5, Math.sqrt(b.kg)*3);
      const c = document.createElementNS(NS,"circle");
      c.setAttribute("cx",b.x); c.setAttribute("cy",b.y); c.setAttribute("r",r);
      c.setAttribute("fill", macroColors[b.macro] || "#94a3b8"); c.setAttribute("opacity","0.9");
      const ring = document.createElementNS(NS,"circle");
      ring.setAttribute("cx",b.x); ring.setAttribute("cy",b.y); ring.setAttribute("r",r+2.5);
      ring.setAttribute("fill","none"); ring.setAttribute("stroke","rgba(255,255,255,0.35)"); ring.setAttribute("stroke-width","1.5");
      const g = document.createElementNS(NS,"g"); g.setAttribute("class","bin");
      const title = document.createElementNS(NS,"title");
      title.textContent = `${b.id}\nMacro: ${b.macro}\n${b.kg} kg`;
      g.appendChild(c); g.appendChild(ring); g.appendChild(title);
      svg.appendChild(g);
    });

    host.appendChild(svg);
  }

  function drawDonut(agg){
    const el = document.getElementById("zone-chart");
    if (!el || typeof ApexCharts === "undefined") return;
    const labels = Object.keys(agg);
    const series = labels.map(k => agg[k]);
    const colors = labels.map(l => macroColors[l] || "#94a3b8"); // match stadium colors
    try{
      new ApexCharts(el, {
        chart:{ type:"donut", height: 280 },
        labels, series, colors,
        legend:{
          show:true, position:"bottom", horizontalAlign:"center",
          markers:{ width:8, height:8, radius:8 }
        },
        dataLabels:{ enabled:false },
        plotOptions:{ pie:{ donut:{ size:"68%" } } },
        tooltip:{ y:{ formatter:v=>`${v} kg` } },
        responsive:[{ breakpoint: 576, options:{ chart:{ height:240 }, plotOptions:{ pie:{ donut:{ size:"62%" } } } } }]
      }).render();
    }catch(e){ console.warn("Donut init failed:", e); }
  }

  function init(){
    const host = document.getElementById("stadium-map");
    if (!host) return;
    const bins = buildExampleBins();
    drawStadium(host, bins);

    const agg = {};
    bins.forEach(b => agg[b.macro] = (agg[b.macro] || 0) + b.kg);
    drawDonut(agg);
  }

  if (document.readyState !== "loading") setTimeout(init, 40);
  else document.addEventListener("DOMContentLoaded", () => setTimeout(init, 40));
})();
</script>
