/**
 * @file
 * JavaScript for FFmpeg Media progress polling.
 */

(function (Drupal, drupalSettings, once) {
  'use strict';

  /**
   * Poll for conversion progress updates.
   */
  Drupal.behaviors.ffmpegMediaProgress = {
    attach: function (context, settings) {
      const ffmpegMediaSettings = settings.ffmpegMedia || {};
      const progressConfig = ffmpegMediaSettings.progress || {};

      // Get global poll interval from config (in seconds), convert to milliseconds.
      // Falls back to 2 seconds if not configured.
      const globalPollInterval = (ffmpegMediaSettings.progressUpdateInterval || 2) * 1000;

      once('ffmpeg-progress', '.ffmpeg-media-progress[data-media-id]', context).forEach(function (element) {
        const mediaId = element.dataset.mediaId;
        const config = progressConfig[mediaId] || {};

        // Use per-media poll interval if provided, otherwise use global config.
        // Per-media pollInterval is expected in milliseconds for backward compatibility.
        const pollInterval = config.pollInterval || globalPollInterval;
        let intervalId = null;

        function updateProgress() {
          fetch(Drupal.url('api/ffmpeg-media/progress/' + mediaId))
            .then(response => response.json())
            .then(data => {
              updateProgressUI(element, data);

              // Stop polling if completed or failed.
              if (data.status === 'completed' || data.status === 'failed') {
                if (intervalId) {
                  clearInterval(intervalId);
                  intervalId = null;
                }

                // Reload page on completion to show video.
                if (data.status === 'completed') {
                  setTimeout(function () {
                    window.location.reload();
                  }, 1000);
                }
              }
            })
            .catch(error => {
              console.error('Failed to fetch progress:', error);
            });
        }

        function updateProgressUI(element, data) {
          const statusEl = element.querySelector('.ffmpeg-media-progress__status');
          const fillEl = element.querySelector('.ffmpeg-media-progress__fill');
          const barEl = element.querySelector('.ffmpeg-media-progress__bar');
          const percentEl = element.querySelector('.ffmpeg-media-progress__percent');
          const stepEl = element.querySelector('.ffmpeg-media-progress__step');
          const etaEl = element.querySelector('.ffmpeg-media-progress__eta');
          const errorEl = element.querySelector('.ffmpeg-media-progress__error');
          const liveEl = element.querySelector('[data-ffmpeg-progress-live]');

          if (statusEl) {
            statusEl.textContent = data.status;
            statusEl.className = 'ffmpeg-media-progress__status ffmpeg-media-progress__status--' + data.status;
          }

          if (fillEl) {
            fillEl.style.width = data.percent + '%';
          }

          if (barEl) {
            barEl.setAttribute('aria-valuenow', data.percent);
            barEl.setAttribute('aria-valuetext', data.status + ' ' + data.percent + '%');
          }

          if (percentEl) {
            percentEl.textContent = data.percent + '%';
          }

          if (stepEl && data.current_step) {
            stepEl.textContent = data.current_step;
          }

          if (etaEl && data.estimated_remaining) {
            etaEl.textContent = Drupal.t('ETA: @seconds seconds', {'@seconds': data.estimated_remaining});
          }

          if (liveEl) {
            const message = data.current_step
              ? Drupal.t('@status @percent% (@step)', {
                '@status': data.status,
                '@percent': data.percent,
                '@step': data.current_step
              })
              : Drupal.t('@status @percent%', {
                '@status': data.status,
                '@percent': data.percent
              });
            if (liveEl.textContent !== message) {
              liveEl.textContent = message;
            }
          }

          if (errorEl) {
            if (data.error) {
              errorEl.textContent = data.error;
              errorEl.style.display = 'block';
            } else {
              errorEl.style.display = 'none';
            }
          }
        }

        // Start polling.
        intervalId = setInterval(updateProgress, pollInterval);

        // Initial update.
        updateProgress();
      });
    }
  };

})(Drupal, drupalSettings, once);
