{% load static %}
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8" />
  <title>Waste Route Visualization</title>
  <!-- A-Frame core -->
  <script src="https://aframe.io/releases/1.7.0/aframe.min.js"></script>
  <!-- A-Frame environment effects -->
  <script src="https://unpkg.com/aframe-environment-component/dist/aframe-environment-component.min.js"></script>
</head>
<body>
  <a-scene id="scene">
    <!-- Camera & cursor -->
    <a-entity
      id="mainCamera"
      camera look-controls wasd-controls
      position="0 5 10">
      <a-cursor color="#ffffff"></a-cursor>
    </a-entity>

    <!-- Invisible ground-plane fallback -->
    <a-plane id="basePlane"
             rotation="-90 0 0"
             color="#444" opacity="0.0">
    </a-plane>

    <!-- 1) Draw city buildings from your OSM data -->
    {% for building in city_data.buildings %}
    <a-entity id="{{ building.id }}" status="{{ building.status }}">
      <a-box position="{{ building.position_x }} {{ building.height }} {{ building.position_z }}"
             width="{{ building.width }}"
             height="{{ building.height }}"
             depth="{{ building.depth }}"
             color="{{ building.color }}"
             opacity="0.8">
      </a-box>
    </a-entity>
    {% endfor %}

    <!-- 2) Draw each job-sphere & gauge from step_positions -->
    {% for pos in step_positions %}
    {% with sid=pos.step.id stype=pos.step.step_type %}
    <a-entity id="step-{{ sid }}" position="{{ pos.x }} 1 {{ pos.z }}">
      <!-- sphere now semi-transparent by default -->
      <a-sphere id="sphere-{{ sid }}"
                radius="10"
                color="#FF4136"
                emissive="#FF4136"
                transparent="true"
                opacity="0.4">
      </a-sphere>

      <!-- gauge above the sphere -->
      <a-entity
        class="status-gauge"
        gauge-click-toggle
        position="11 3 0"
        data-step-id="{{ sid }}"
        data-step-type="{{ stype }}">
        {% include "pxy_city_digital_twins/_status_gauge_waste.html" with ring_color="#FF4136" status=stype id=sid %}
      </a-entity>
    </a-entity>
    {% endwith %}
    {% endfor %}
  </a-scene>

  <script>
    // Expose Django vars into JS
    const subdivision = "{{ subdivision }}";
    const vehicle     = "{{ vehicle }}";
    const recordUrl   = "{% url 'waste-record-pickup' subdivision=subdivision vehicle=vehicle %}";

    document.querySelector('#scene').addEventListener('loaded', () => {
      const sceneEl = document.getElementById('scene');
      const rel     = {{ rel_coords|safe }};

      // 3) Compute bounding box & stageSize
      const xs = rel.map(r => r[0]), zs = rel.map(r => r[1]);
      const minX = Math.min(...xs), maxX = Math.max(...xs);
      const minZ = Math.min(...zs), maxZ = Math.max(...zs);
      const width  = maxX - minX, height = maxZ - minZ;
      const stageSize = Math.ceil(Math.max(width, height) * 1.2);

      // 4) Update invisible base-plane
      const base = document.getElementById('basePlane');
      base.setAttribute('width',  width * 1.5);
      base.setAttribute('height', height * 1.5);
      base.setAttribute('position',
        `${(minX+maxX)/2} 0 ${(minZ+maxZ)/2}`);

      // 5) Add environment
      const envEl = document.createElement('a-entity');
      envEl.setAttribute('environment', `
        preset: forest;
        stageSize: ${stageSize};
        ground: flat;
        grid: true;
        gridColor: #00ffff;
        skyColor: #000000;
        fog: 0.3;
        lighting: subtle;
      `);
      sceneEl.appendChild(envEl);

      // 6) Draw & animate each segment
      const pulseDuration = 600;
      rel.forEach(([x1,z1], i) => {
        if (i + 1 >= rel.length) return;
        const [x2,z2] = rel[i+1];
        const seg = document.createElement('a-entity');
        seg.setAttribute('line', `
          start: ${x1.toFixed(2)} 1 ${z1.toFixed(2)};
          end:   ${x2.toFixed(2)} 1 ${z2.toFixed(2)};
          color: #0077FF;
          opacity: 0.6
        `);
        seg.setAttribute('animation__color', `
          property: line.color;
          from:     #0077FF;
          to:       #FF4136;
          dur:      ${pulseDuration};
          delay:    ${i * pulseDuration};
          dir:      alternate;
          loop:     true
        `);
        sceneEl.appendChild(seg);
      });

      // 7) Position camera at first step
      if (rel.length) {
        const [fx,fz] = rel[0];
        const cam = document.getElementById('mainCamera');
        cam.setAttribute('position', `${fx.toFixed(2)} 6 ${fz.toFixed(2)+6}`);
        cam.setAttribute('look-at',   `${fx.toFixed(2)} 1 ${fz.toFixed(2)}`);
      }

      // ─────────────────────────────────────────────────────────────
      // 8) Record pickups by clicking each gauge
      // ─────────────────────────────────────────────────────────────

      // CSRF helper
      function getCookie(name) {
        const v = document.cookie.match('(^|;)\\s*'+name+'\\s*=\\s*([^;]+)');
        return v ? v.pop() : '';
      }
      const csrftoken = getCookie('csrftoken');

      // Track click counts & define colors
      const clickCounts = {};
      const colors = ['#2ECC40','#FFDC00','#FF851B','#FF4136'];

      document.querySelectorAll('.status-gauge').forEach(el => {
        const stepId = el.dataset.stepId;
        clickCounts[stepId] = 0;

        el.addEventListener('click', () => {
          // cycle 1→4
          clickCounts[stepId] = (clickCounts[stepId] % 4) + 1;
          const quarter = clickCounts[stepId];

          // recolor ring
          const ring = el.querySelector('.gauge-ring');
          if (ring) ring.setAttribute('color', colors[quarter-1]);

          // recolor sphere
          const sph = document.getElementById(`sphere-${stepId}`);
          if (sph) {
            sph.setAttribute(
              'material',
              `color: ${colors[quarter-1]};
               emissive: ${colors[quarter-1]};
               transparent: true; opacity: 0.4`
            );
          }

          // log & POST
          console.log('Recording pickup', { step_id: stepId, quarter }, '→', recordUrl);
          fetch(recordUrl, {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json',
              'X-CSRFToken': csrftoken
            },
            body: JSON.stringify({ step_id: stepId, quarter })
          }).then(res => {
            if (!res.ok) {
              console.error('Record pickup failed', res.status);
            } else {
              console.log('Pickup recorded');
            }
          });
        });
      });
    });
  </script>
</body>
</html>
