{% load static %}
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Digital Twin City</title>
    <!-- A-Frame 1.7.0 & environment component -->
    <script src="https://aframe.io/releases/1.7.0/aframe.min.js"></script>
    <script src="https://unpkg.com/aframe-environment-component/dist/aframe-environment-component.min.js"></script>

    <!-- 1) Simple “look-at” component to face the camera -->
    <script>
      AFRAME.registerComponent('billboard', {
        schema: {type: 'selector'},
        tick: function () {
          if (!this.data) return;
          // Make this entity face the camera each frame
          this.el.object3D.lookAt(this.data.object3D.position);
        }
      });
    </script>

<script>
  AFRAME.registerComponent('gauge-click-toggle', {
    init: function () {
      const colors = ["#00FF00", "#FFFF00", "#FF0000", "#00FFFF"];
      const statuses = ["OK", "Warning", "Critical", "Offline"];
      let i = 0;

      const ring = this.el.querySelector('.gauge-ring');
      const label = this.el.querySelector('.gauge-label');

      this.el.addEventListener('click', () => {
        i = (i + 1) % colors.length;
        if (ring) ring.setAttribute('color', colors[i]);
        if (label) {
          const current = label.getAttribute('value');
          const idLine = current.split("\n")[0];  // Preserve ID line
          label.setAttribute('value', `${idLine}\n${statuses[i]}`);
        }
      });
    }
  });
</script>

<script>
  AFRAME.registerComponent('roads-ribbon', {
    init: function () {
      const dataEl = document.getElementById('road-paths-data');
      if (!dataEl) return;
      let paths = [];
      try {
        paths = JSON.parse(dataEl.textContent || '[]');
      } catch (e) {
        console.warn('roads-ribbon: failed to parse road paths', e);
      }
      if (!paths.length) return;

      const group = new THREE.Group();
      const materialCache = {};

      function getMaterial(color) {
        const key = (color || '#00ffff').toLowerCase();
        if (!materialCache[key]) {
          const base = new THREE.Color(key);
          materialCache[key] = new THREE.MeshStandardMaterial({
            color: base,
            emissive: base,
            emissiveIntensity: 1.1,
            transparent: true,
            opacity: 0.9,
          });
        }
        return materialCache[key];
      }

      paths.forEach((p) => {
        const pts = p.points || [];
        if (pts.length < 2) return;
        const curvePts = pts.map((pt) => new THREE.Vector3(pt.x || 0, 0.35, pt.z || 0));
        const curve = new THREE.CatmullRomCurve3(curvePts);
        const segments = Math.min(Math.max(curvePts.length * 2, 6), 200);
        const radius = Math.max((p.width || 0.2) * 0.35, 0.08);
        const tubeGeom = new THREE.TubeGeometry(curve, segments, radius, 6, false);
        const mesh = new THREE.Mesh(tubeGeom, getMaterial(p.color));
        mesh.frustumCulled = false;
        group.add(mesh);
      });

      group.frustumCulled = false;
      this.el.setObject3D('mesh', group);
      this.group = group;
      this.materials = Object.values(materialCache);

      this._pulseValue = 1.1;
      this._pulseDir = 1;
    },
    tick: function (time, delta) {
      if (!this.materials || !this.materials.length) return;
      const step = (delta || 16) / 1000;
      this._pulseValue += this._pulseDir * step * 0.6;
      if (this._pulseValue > 1.4) this._pulseDir = -1;
      if (this._pulseValue < 0.4) this._pulseDir = 1;
      for (let i = 0; i < this.materials.length; i++) {
        this.materials[i].emissiveIntensity = this._pulseValue;
      }
    }
  });
</script>

</head>
<body>
  <a-scene environment="preset: tron; groundTexture: walk; dressing: trees; fog: 0.7">

    <!-- Camera & Controls (give it an id for look-at) -->
    <a-entity id="mainCamera" camera look-controls wasd-controls position="0 2 5">
      <a-cursor color="#FF0000"></a-cursor>
    </a-entity>

    <!-- Optional: Transparent ground plane (comment out if you want only environment ground) -->
    <a-plane position="0 -0.1 0" rotation="-90 0 0"
             width="200" height="200"
             color="#444" opacity="0.3">
    </a-plane>

    <!-- Roads -->
    {% if city_data.road_paths %}
    {{ city_data.road_paths|json_script:"road-paths-data" }}
    {% else %}
    <script id="road-paths-data" type="application/json">[]</script>
    {% endif %}
    <a-entity id="roadsRibbon" roads-ribbon></a-entity>

    <!-- Buildings -->
    {% for building in city_data.buildings %}
    <a-entity id="{{ building.id }}" status="{{ building.status }}">
        <!-- Building geometry -->
        <a-box position="{{ building.position_x }} 1 {{ building.position_z }}"
               width="{{ building.width }}" height="{{ building.height }}" depth="{{ building.depth }}"
               color="{{ building.color }}">
        </a-box>

        <a-entity
          position="{{ building.position_x }} {{ building.height }} {{ building.position_z }}">
          {% include "pxy_city_digital_twins/_status_gauge.html" with ring_color="#00FFFF" offset_y="1.50" status=building.status id=building.id %}
        </a-entity>



    </a-entity>
    {% endfor %}

    <!-- Lamps -->
    {% for lamp in city_data.lamps %}
    <a-entity id="{{ lamp.id }}" status="{{ lamp.status }}" position="{{ lamp.position_x }} 1 {{ lamp.position_z }}">
        <!-- Lamp geometry -->
        <a-cone radius-bottom="0.1" radius-top="0.5"
                height="{{ lamp.height }}" color="{{ lamp.color }}">
        </a-cone>
        <a-sphere radius="0.2" color="#FFFFFF"
                  position="0 {{ lamp.height }} 0">
        </a-sphere>

        <!-- Label: billboard to camera -->
        <a-entity position="0 3 0" billboard="#mainCamera">
          <a-plane width="4" height="1.2" color="#000" opacity="0.5"></a-plane>
          <a-text value="Status: {{ lamp.status }}"
                  width="4"
                  align="center"
                  color="#FFF"
                  position="0 0 0.01">
          </a-text>
        </a-entity>
    </a-entity>
    {% endfor %}

    <!-- Trees -->
    {% for tree in city_data.trees %}
    <a-entity id="{{ tree.id }}" status="{{ tree.status }}" position="{{ tree.position_x }} 1 {{ tree.position_z }}">
        <!-- Tree trunk & leaves -->
        <a-cone radius-bottom="{{ tree.radius_bottom }}"
                radius-top="{{ tree.radius_top }}"
                height="{{ tree.height }}"
                color="{{ tree.color_trunk }}">
        </a-cone>
        <a-sphere radius="{{ tree.radius_top }}"
                  color="{{ tree.color_leaves }}"
                  position="0 {{ tree.height }} 0">
        </a-sphere>

        <!-- Label: billboard to camera -->
        <a-entity position="0 3 0" billboard="#mainCamera">
          <a-plane width="4" height="1.2" color="#000" opacity="0.5"></a-plane>
          <a-text value="Status: {{ tree.status }}"
                  width="4"
                  align="center"
                  color="#FFF"
                  position="0 0 0.01">
          </a-text>
        </a-entity>
    </a-entity>
    {% endfor %}

    <!-- Cell Towers -->
    {% for tower in city_data.towers %}
    <a-entity id="tower{{ tower.id }}"
              position="{{ tower.position_x }} {{ tower.position_y }} {{ tower.position_z }}">
        <!-- Base tower cylinder -->
        <a-cylinder height="{{ tower.height }}" radius="1" color="{{ tower.color }}"></a-cylinder>

        <!-- Animated signal ring near top -->
        <a-ring color="#FF0000"
                radius-inner="2"
                radius-outer="2.5"
                position="0 {{ tower.height|add:'1' }} 0"
                rotation="-90 0 0"
                animation="property: scale; to: 1.5 1.5 1.5; dir: alternate; dur: 1000; loop: true">
        </a-ring>

        <!-- Tower label: billboard to camera -->
        <a-entity position="0 -5 0" billboard="#mainCamera">
          <a-plane width="4" height="1.2" color="#000" opacity="0.5"></a-plane>
          <a-text value="📡 Tower {{ tower.id }} - {{ tower.status }}"
                  width="4"
                  align="center"
                  color="#FFF"
                  position="0 0 0.01">
          </a-text>
        </a-entity>
    </a-entity>
    {% endfor %}

    <!-- Fiber Paths (Cylinders) -->
    {% for fiber in city_data.fiber_paths %}
    <a-entity>
        <a-cylinder position="{{ fiber.mid_x }} {{ fiber.mid_y }} {{ fiber.mid_z }}"
                    height="{{ fiber.length }}"
                    radius="0.1"
                    rotation="90 {{ fiber.angle }} 0"
                    color="{{ fiber.color }}">
        </a-cylinder>

        <!-- Fiber label: billboard to camera -->
        <a-entity position="{{ fiber.start_x }} 3 {{ fiber.start_z }}" billboard="#mainCamera">
          <a-plane width="4" height="1.2" color="#000" opacity="0.5"></a-plane>
          <a-text value="🔗 Fiber Path {{ fiber.id }} - {{ fiber.status }}"
                  width="4"
                  align="center"
                  color="{{ fiber.color }}"
                  position="0 0 0.01">
          </a-text>
        </a-entity>
    </a-entity>
    {% endfor %}

    <!-- Wi-Fi Hotspots -->
    {% for wifi in city_data.wifi_hotspots %}
    <a-entity id="wifi{{ wifi.id }}"
              position="{{ wifi.position_x }} {{ wifi.position_y }} {{ wifi.position_z }}">
        <!-- Hotspot sphere (animated) -->
        <a-sphere radius="{{ wifi.radius }}" color="{{ wifi.color }}"
                  animation="property: scale; to: 1.5 1.5 1.5; dir: alternate; dur: 1500; loop: true">
        </a-sphere>

        <!-- Coverage area (fixed or dynamic) -->
        <a-sphere radius="5"
                  color="#00FFFF"
                  opacity="0.2"
                  position="0 {{ wifi.radius }} 0">
        </a-sphere>

        <!-- Wi-Fi label: billboard to camera -->
        <a-entity position="0 3 0" billboard="#mainCamera">
          <a-plane width="4" height="1.2" color="#000" opacity="0.5"></a-plane>
          <a-text value="📶 WiFi {{ wifi.id }} - {{ wifi.status }}"
                  width="4"
                  align="center"
                  color="#FFF"
                  position="0 0 0.01">
          </a-text>
        </a-entity>
    </a-entity>
    {% endfor %}


</a-scene>



</body>
</html>
