(function() {
  'use strict';

  let currentStep = 0;
  let savedStepIndex = 0;
  const steps = document.querySelectorAll('.step');
  const configSteps = document.querySelectorAll('.config-step');
  const totalSteps = steps.length;
  let isConfigMode = false;

  const stepTitle = document.getElementById('steptitle');
  const stepProgress = document.getElementById('stepprogress');
  const prevBtn = document.getElementById('prevBtn');
  const nextBtn = document.getElementById('nextBtn');
  const quickConfigBtn = document.getElementById('quickconfig');
  const closeOverviewBtn = document.getElementById('closeoverview');
  const footer = document.querySelector('.step-footer');
  const body = document.body;
  const stepsContainer = document.getElementById('stepsContainer');
  const marketingVideo = document.getElementById('marketingVideo');
  const gettingStartedVideo = document.getElementById('gettingStartedVideo');
  const liveUpdateVideo = document.getElementById('liveUpdateVideo');
  const exportOptionsVideo = document.getElementById('exportOptionsVideo');
  const stepVideos = {
    0: marketingVideo,
    1: gettingStartedVideo,
    2: liveUpdateVideo,
    3: exportOptionsVideo
  };

  const accents = {
    'accent-1': 'accent-1',
    'accent-2': 'accent-2',
    'accent-3': 'accent-3',
    'accent-4': 'accent-4'
  };

  function enforceOverflowHidden() {
    document.documentElement.style.overflow = 'hidden';
    document.body.style.overflow = 'hidden';
  }

  enforceOverflowHidden();
  setInterval(enforceOverflowHidden, 100);

  function prefersReducedMotion() {
    return window.matchMedia('(prefers-reduced-motion: reduce)').matches;
  }

  function manageStepVideo(stepIndex) {
    Object.keys(stepVideos).forEach(key => {
      const video = stepVideos[key];
      if (!video) {
        return;
      }

      if (parseInt(key, 10) === stepIndex && !prefersReducedMotion()) {
        video.currentTime = 0;
        const playPromise = video.play();
        if (playPromise && typeof playPromise.catch === 'function') {
          playPromise.catch(() => {});
        }
      } else {
        video.pause();
      }
    });
  }

  function hideAllSteps() {
    steps.forEach(step => {
      step.classList.remove('active');
      step.removeAttribute('aria-current');
    });
    configSteps.forEach(step => {
      step.classList.remove('active');
      step.removeAttribute('aria-current');
    });
  }

  function updateAccent(step) {
    const accent = step.getAttribute('data-accent');
    if (accent && accents[accent]) {
      body.setAttribute('data-accent', accents[accent]);
    }
  }

  function updateProgress(index, isConfig) {
    if (!stepProgress) {
      return;
    }
    if (isConfig) {
      stepProgress.textContent = 'Quick Config';
      return;
    }
    stepProgress.textContent = 'Step ' + (index + 1) + ' of ' + totalSteps;
  }

  function focusStep(step) {
    if (!step) {
      return;
    }
    const focusTarget = step.querySelector(
      'button, a[href], input, [tabindex]:not([tabindex="-1"])'
    );
    if (focusTarget) {
      focusTarget.focus({ preventScroll: true });
    }
  }

  function scrollStepToTop(step) {
    if (!step) {
      return;
    }
    const scrollable = step.querySelector('.step-content, .config-content');
    if (!scrollable) {
      return;
    }
    const resetScroll = () => {
      scrollable.scrollTop = 0;
    };
    resetScroll();
    requestAnimationFrame(() => {
      resetScroll();
      requestAnimationFrame(resetScroll);
    });
  }

  function showStepById(stepId) {
    hideAllSteps();
    const step = document.getElementById(stepId);
    if (!step) {
      return null;
    }

    step.classList.add('active');
    step.setAttribute('aria-current', 'step');

    const title = step.getAttribute('data-title') || '';
    if (stepTitle) {
      stepTitle.textContent = title;
    }

    updateAccent(step);

    const isConfig = step.classList.contains('config-step');
    isConfigMode = isConfig;
    updateProgress(savedStepIndex, isConfig);

    if (footer) {
      footer.style.display = isConfigMode ? 'none' : 'flex';
    }

    enforceOverflowHidden();
    scrollStepToTop(step);
    focusStep(step);
    if (!isConfig) {
      manageStepVideo(savedStepIndex);
    } else {
      manageStepVideo(-1);
    }
    return step;
  }

  function setStep(index) {
    if (index < 0 || index >= totalSteps) {
      return;
    }

    savedStepIndex = index;
    isConfigMode = false;

    hideAllSteps();
    const currentStepEl = steps[index];
    currentStepEl.classList.add('active');
    currentStepEl.setAttribute('aria-current', 'step');

    const title = currentStepEl.getAttribute('data-title') || '';
    if (stepTitle) {
      stepTitle.textContent = title;
    }

    updateAccent(currentStepEl);
    updateProgress(index, false);

    if (footer) {
      footer.style.display = 'flex';
    }

    if (prevBtn) {
      prevBtn.disabled = index === 0;
      prevBtn.setAttribute('aria-disabled', index === 0 ? 'true' : 'false');
    }
    if (nextBtn) {
      nextBtn.disabled = index === totalSteps - 1;
      nextBtn.setAttribute('aria-disabled', index === totalSteps - 1 ? 'true' : 'false');
    }

    currentStep = index;
    enforceOverflowHidden();
    scrollStepToTop(currentStepEl);
    focusStep(currentStepEl);
    manageStepVideo(index);
  }

  function nextStep() {
    if (!isConfigMode && currentStep < totalSteps - 1) {
      setStep(currentStep + 1);
    }
  }

  function prevStep() {
    if (!isConfigMode && currentStep > 0) {
      setStep(currentStep - 1);
    }
  }

  function configFor(key) {
    if (window.__quickConfigPresets && window.__quickConfigPresets[key]) {
      return window.__quickConfigPresets[key];
    }
    return false;
  }

  function resultsToHTML(results) {
    const enabled = [];
    const disabled = [];
    const configured = [];

    results.forEach(item => {
      let title = item.title;
      if (typeof item.state === 'string') {
        title = '<strong>' + title + ':</strong> ' + item.state;
        configured.push('<li>' + title + '</li>');
      } else if (item.state) {
        enabled.push('<li>' + title + '</li>');
      } else {
        disabled.push('<li>' + title + '</li>');
      }
    });

    let html = '';
    if (configured.length > 0) {
      html += '<h2>Settings</h2><ul class="details" id="config-settings">' +
        configured.join('') + '</ul>';
    }
    if (enabled.length > 0) {
      html += '<h2>Enabled</h2><ul class="details" id="config-enabled">' +
        enabled.join('') + '</ul>';
    }
    if (disabled.length > 0) {
      html += '<h2>Disabled</h2><ul class="details" id="config-disabled">' +
        disabled.join('') + '</ul>';
    }
    return html;
  }

  function displayConfirmation(config) {
    const results = configFor(config);
    if (results) {
      showStepById('config-confirm');
      const confirmDiv = document.getElementById('configconfirm');
      if (confirmDiv) {
        confirmDiv.innerHTML = resultsToHTML(results);
      }
      const confirmBtn = document.getElementById('confirm');
      if (confirmBtn) {
        confirmBtn.setAttribute('data-config-setting', config);
        confirmBtn.setAttribute('aria-busy', 'false');
        confirmBtn.disabled = false;
        confirmBtn.textContent = 'Apply settings';
      }
    } else {
      showStepById('config-error');
    }
  }

  function parseConfigResults(json) {
    try {
      const data = typeof json === 'string' ? JSON.parse(json) : json;
      if (data && data.success) {
        showStepById('config-saved');
        const resultsDiv = document.getElementById('configresults');
        if (resultsDiv) {
          resultsDiv.innerHTML = resultsToHTML(data.results);
        }
      } else {
        showStepById('config-error');
      }
    } catch (e) {
      console.error('Error parsing config results:', e);
      showStepById('config-error');
    }
  }

  async function applyQuickSetup(configSetting) {
    if (!window.OVWebview || !window.OVWebview.quickSetup) {
      showStepById('config-error');
      return;
    }

    const confirmBtn = document.getElementById('confirm');
    if (confirmBtn) {
      confirmBtn.setAttribute('aria-busy', 'true');
      confirmBtn.disabled = true;
      confirmBtn.textContent = 'Applying...';
    }

    try {
      const json = await window.OVWebview.quickSetup(configSetting);
      parseConfigResults(json);
    } catch (e) {
      console.error('Quick setup failed:', e);
      showStepById('config-error');
    } finally {
      if (confirmBtn) {
        confirmBtn.setAttribute('aria-busy', 'false');
        confirmBtn.disabled = false;
        confirmBtn.textContent = 'Apply settings';
      }
    }
  }

  function startConfig() {
    savedStepIndex = currentStep;
    showStepById('config-home');
  }

  function exitConfig() {
    isConfigMode = false;
    setStep(savedStepIndex);
  }

  function handleConfigClick(e) {
    const target = e.target.closest('button, a');
    if (!target) {
      return;
    }

    e.preventDefault();

    const configConfirm = target.getAttribute('data-config-confirm');
    if (configConfirm) {
      displayConfirmation(configConfirm);
      return;
    }

    const configSetting = target.getAttribute('data-config-setting');
    if (configSetting) {
      applyQuickSetup(configSetting);
      return;
    }

    const configNext = target.getAttribute('data-config-next');
    if (configNext) {
      if (configNext === 'last') {
        exitConfig();
      } else {
        showStepById(configNext);
      }
    }
  }

  function setupConfigHandlers() {
    configSteps.forEach(step => {
      step.addEventListener('click', handleConfigClick);
    });
  }

  function setupNativeActionButtons() {
    const prefLink = document.getElementById('preflink');
    if (prefLink) {
      prefLink.addEventListener('click', e => {
        e.preventDefault();
        if (window.OVWebview && window.OVWebview.openSettings) {
          window.OVWebview.openSettings();
        }
      });
    }

    const openConductor = document.getElementById('openConductor');
    if (openConductor) {
      openConductor.addEventListener('click', e => {
        e.preventDefault();
        if (window.OVWebview && window.OVWebview.openConductor) {
          window.OVWebview.openConductor();
        }
      });
    }

    const openProcessorSettings = document.getElementById('openProcessorSettings');
    if (openProcessorSettings) {
      openProcessorSettings.addEventListener('click', e => {
        e.preventDefault();
        if (window.OVWebview && window.OVWebview.openProcessorSettings) {
          window.OVWebview.openProcessorSettings();
        }
      });
    }
  }

  if (prevBtn) {
    prevBtn.addEventListener('click', e => {
      e.preventDefault();
      prevStep();
    });
  }

  if (nextBtn) {
    nextBtn.addEventListener('click', e => {
      e.preventDefault();
      nextStep();
    });
  }

  if (quickConfigBtn) {
    quickConfigBtn.addEventListener('click', e => {
      e.preventDefault();
      startConfig();
    });
  }

  if (closeOverviewBtn) {
    closeOverviewBtn.addEventListener('click', e => {
      e.preventDefault();
      if (window.OVWebview && window.OVWebview.closeOverview) {
        window.OVWebview.closeOverview();
      }
    });
  }

  document.addEventListener('click', e => {
    if (e.target.id === 'exitSetup' || e.target.id === 'startOver' ||
        e.target.id === 'startOver2') {
      e.preventDefault();
      if (e.target.id === 'exitSetup') {
        exitConfig();
      } else {
        showStepById('config-home');
      }
    }
  });

  function getFocusableInContainer(container) {
    return Array.from(container.querySelectorAll(
      'button:not([disabled]), a[href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])'
    ));
  }

  function handleKeydown(e) {
    if (e.key === 'ArrowRight' || (e.key === ' ' && !e.shiftKey)) {
      if (!isConfigMode) {
        e.preventDefault();
        nextStep();
      }
      return;
    }

    if (e.key === 'ArrowLeft' || (e.key === ' ' && e.shiftKey)) {
      if (!isConfigMode) {
        e.preventDefault();
        prevStep();
      }
      return;
    }

    if (e.key === 'Escape') {
      e.preventDefault();
      if (isConfigMode) {
        exitConfig();
      } else if (window.OVWebview && window.OVWebview.closeOverview) {
        window.OVWebview.closeOverview();
      }
      return;
    }

    if (isConfigMode && (e.key === 'ArrowDown' || e.key === 'ArrowUp')) {
      const activeStep = document.querySelector('.config-step.active');
      if (!activeStep) {
        return;
      }
      const focusable = getFocusableInContainer(activeStep);
      if (focusable.length === 0) {
        return;
      }
      const currentIndex = focusable.indexOf(document.activeElement);
      let nextIndex = currentIndex;
      if (e.key === 'ArrowDown') {
        nextIndex = currentIndex < 0 ? 0 : (currentIndex + 1) % focusable.length;
      } else {
        nextIndex = currentIndex < 0 ? focusable.length - 1 :
          (currentIndex - 1 + focusable.length) % focusable.length;
      }
      e.preventDefault();
      focusable[nextIndex].focus();
    }
  }

  document.addEventListener('keydown', handleKeydown);

  document.querySelectorAll('.demo-video').forEach(video => {
    video.addEventListener('click', () => {
      if (prefersReducedMotion()) {
        return;
      }
      video.currentTime = 0;
      video.play().catch(() => {});
    });
  });

  setStep(0);
  setupConfigHandlers();
  setupNativeActionButtons();

  if (!window.Marked) {
    window.Marked = {};
  }

  window.Marked.overview = {
    next: nextStep,
    prev: prevStep,
    go: function(step) {
      if (typeof step === 'number') {
        setStep(step);
        return;
      }
      const stepEl = document.getElementById(step);
      if (stepEl && stepEl.classList.contains('config-step')) {
        showStepById(step);
        return;
      }
      const index = Array.from(steps).findIndex(s => s.id === 'step-' + step);
      if (index >= 0) {
        setStep(index);
      }
    },
    config: startConfig
  };
})();
