'use strict';
angular.module('beamng.apps')
.directive('sgrGlowboostsix', ['$log', '$timeout', function ($log, $timeout) {
  return {
    template: '<object style="width:100%; height:100%;" type="image/svg+xml" data="/ui/modules/apps/sgrglowboostsix/sgrglowboostsix.svg"></object>',
    replace: true,
    restrict: 'EA',
    scope: true,
    link: function (scope, element) {
      element.css({ transition: 'opacity 0.3s ease' });
      let svg;
      let needle;
      let visible = false;
      let currentColorIndex = 0;
      let currentGlowLevelIndex = 0;
      let colorSyncEnabled = false;
      let holdTimeout;
      let colorSyncInterval;

      const colors = ['#0000FF', '#39ff14', '#ff0000', '#00ffff', '#ffff00', '#9400d3', '#ffffff'];
      const glowLevels = [
        { blur: 7, intensity: 1 },
        { blur: 11, intensity: 2 },
        { blur: 15, intensity: 3 }
      ];

      const minBoost = 0;
      const maxBoost = 60;
      const minDegree = 2;
      const maxDegree = 265;

      const streamsList = ['electrics'];
      StreamsManager.add(streamsList);

      function interpolateBoostToDegree(boost) {
        const ratio = (boost - minBoost) / (maxBoost - minBoost);
        return minDegree + ratio * (maxDegree - minDegree);
      }

      function updateNeedleRotation(boost) {
        const rotationDegree = interpolateBoostToDegree(boost);
        if (needle) {
          needle.setAttribute('transform', `rotate(${rotationDegree}, 0, 0)`);
        }
      }

      function flashIndicator(color) {
        const backgroundCircle = svg.getElementById('background_circle');
        if (!backgroundCircle) return;

        const flashDuration = color === '#006400' ? 700 : 500;
        const resetDuration = color === '#006400' ? 400 : 300;

        for (let i = 0; i < 3; i++) {
          $timeout(function () {
            backgroundCircle.setAttribute('fill', color);
          }, flashDuration * i);

          $timeout(function () {
            backgroundCircle.setAttribute('fill', colors[currentColorIndex]);
          }, flashDuration * i + resetDuration);
        }

        $timeout(function () {
          backgroundCircle.setAttribute('fill', colors[currentColorIndex]);
        }, flashDuration * 3);
      }

      function toggleColorSync() {
        colorSyncEnabled = !colorSyncEnabled;
        saveSyncState();

        if (colorSyncEnabled) {
          flashIndicator('#006400');

          $timeout(function () {
            colorSyncInterval = setInterval(function () {
              loadSharedColorAndGlow();
            }, 200);
          }, 1800);
        } else {
          flashIndicator('#8B0000');

          clearInterval(colorSyncInterval);
          loadSavedColor();
          loadSavedGlowLevel();
        }
      }

      function loadSavedSyncState() {
        const savedSyncState = localStorage.getItem('sgrGlowboostsixSyncEnabled');
        if (savedSyncState !== null) {
          colorSyncEnabled = savedSyncState === 'true';
        }
        if (colorSyncEnabled) {
          colorSyncInterval = setInterval(function () {
            loadSharedColorAndGlow();
          }, 200);
        }
      }

      function saveSyncState() {
        localStorage.setItem('sgrGlowboostsixSyncEnabled', colorSyncEnabled);
      }

      function loadSharedColorAndGlow() {
        const sharedColorIndex = localStorage.getItem('colorSyncColorIndex');
        const sharedGlowLevelIndex = localStorage.getItem('colorSyncGlowLevelIndex');

        if (sharedColorIndex !== null) {
          currentColorIndex = parseInt(sharedColorIndex, 10);
          updateColor();
        }

        if (sharedGlowLevelIndex !== null) {
          currentGlowLevelIndex = parseInt(sharedGlowLevelIndex, 10);
          updateGlowIntensity();
        }
      }

      function saveSharedColorAndGlow() {
        localStorage.setItem('colorSyncColorIndex', currentColorIndex);
        localStorage.setItem('colorSyncGlowLevelIndex', currentGlowLevelIndex);
      }

      function loadSavedColor() {
        const savedColorIndex = localStorage.getItem('sgrGlowboostsixColorIndex');
        if (savedColorIndex !== null) {
          currentColorIndex = parseInt(savedColorIndex, 10);
        }
        updateColor();
      }

      function saveColor() {
        if (colorSyncEnabled) {
          saveSharedColorAndGlow();
        } else {
          localStorage.setItem('sgrGlowboostsixColorIndex', currentColorIndex);
        }
      }

      function loadSavedGlowLevel() {
        const savedGlowLevelIndex = localStorage.getItem('sgrGlowboostsixGlowLevelIndex');
        if (savedGlowLevelIndex !== null) {
          currentGlowLevelIndex = parseInt(savedGlowLevelIndex, 10);
        }
        updateGlowIntensity();
      }

      function saveGlowLevel() {
        if (colorSyncEnabled) {
          saveSharedColorAndGlow();
        } else {
          localStorage.setItem('sgrGlowboostsixGlowLevelIndex', currentGlowLevelIndex);
        }
      }

      function updateColor() {
        const newColor = colors[currentColorIndex];
        const backgroundCircle = svg.getElementById('background_circle');
        if (backgroundCircle) {
          backgroundCircle.setAttribute('fill', newColor);
        }
        const glowingOuterRing = svg.getElementById('glowing_outer_ring');
        if (glowingOuterRing) {
          glowingOuterRing.setAttribute('stroke', newColor);
        }
        const glowingInnerRing = svg.getElementById('glowing_inner_ring');
        if (glowingInnerRing) {
          glowingInnerRing.setAttribute('stroke', newColor);
        }
      }

      function updateGlowIntensity() {
        const { blur } = glowLevels[currentGlowLevelIndex];
        const glowFilter = svg.querySelector('filter#ring-glow feGaussianBlur');
        if (glowFilter) {
          glowFilter.setAttribute('stdDeviation', blur);
        }
      }

      function detectLongPress(event) {
        if (event.button === 0) {
          holdTimeout = $timeout(function () {
            toggleColorSync();
          }, 1000);
        }
      }

      function cancelLongPress() {
        $timeout.cancel(holdTimeout);
      }

      function initializeSvg() {
        svg = element[0].contentDocument;
        if (!svg) return;

        const colorButton = svg.getElementById('color');
        const resetButton = svg.getElementById('reset');

        needle = svg.getElementById('needle');

        if (colorButton) {
          colorButton.addEventListener('mousedown', detectLongPress);
          colorButton.addEventListener('mouseup', cancelLongPress);
          colorButton.addEventListener('mouseleave', cancelLongPress);
          colorButton.addEventListener('click', (event) => {
            if (event.button === 0) {
              currentColorIndex = (currentColorIndex + 1) % colors.length;
              updateColor();
              saveColor();
            }
          });

          colorButton.addEventListener('contextmenu', (event) => {
            event.preventDefault();
            currentGlowLevelIndex = (currentGlowLevelIndex + 1) % glowLevels.length;
            updateGlowIntensity();
            saveGlowLevel();
          });
        }

        if (resetButton) {
          resetButton.addEventListener('mousedown', (event) => {
            if (event.button === 0) {
              // Reset functionality can go here if needed
            }
          });
        }

        loadSavedColor();
        loadSavedGlowLevel();
        updateGlowIntensity();
        loadSavedSyncState();

        if (!visible) {
          element[0].style.opacity = 1;
          visible = true;
        }

        scope.$on('streamsUpdate', function (event, streams) {
          if (streams.electrics && streams.electrics.boost !== undefined) {
            const currentBoost = Math.max(minBoost, Math.min(streams.electrics.boost, maxBoost));
            updateNeedleRotation(currentBoost);
          }
        });

        scope.$on('$destroy', function () {
          if (colorSyncInterval) {
            clearInterval(colorSyncInterval);
          }
          StreamsManager.remove(streamsList);
        });
      }

      element[0].addEventListener('load', function () {
        $timeout(initializeSvg, 500);
      });
    }
  };
}]);
