(function() {
  'use strict';

  // State management
  let currentStep = 0;
  let savedStepIndex = 0; // Save the step index when entering config mode
  const steps = document.querySelectorAll('.step');
  const configSteps = document.querySelectorAll('.config-step');
  const totalSteps = steps.length;
  let isConfigMode = false;

  // Elements
  const stepTitle = document.getElementById('steptitle');
  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;

  // Colors mapping
  const colors = {
    'blue': 'blue',
    'green': 'green',
    'darkgreen': 'darkgreen',
    'darkblue': 'darkblue',
    'red': 'red',
    'yellow': 'yellow'
  };

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

  // Initialize overflow on load
  enforceOverflowHidden();

  // Enforce overflow hidden periodically (in case something else tries to change it)
  setInterval(enforceOverflowHidden, 100);

  // Hide all steps (both regular and config)
  function hideAllSteps() {
    steps.forEach(step => step.classList.remove('active'));
    configSteps.forEach(step => step.classList.remove('active'));
  }

  // Show a step by ID
  function showStepById(stepId) {
    hideAllSteps();
    const step = document.getElementById(stepId);
    if (step) {
      step.classList.add('active');
      const title = step.getAttribute('data-title') || '';
      if (stepTitle) {
        stepTitle.textContent = title;
      }

      // Update background color
      const color = step.getAttribute('data-color');
      if (color && colors[color]) {
        body.classList.remove('color');
        Object.values(colors).forEach(c => {
          body.classList.remove('color-' + c);
          body.classList.remove(c);
        });
        body.classList.add('color');
        body.classList.add('color-' + colors[color]);
        body.classList.add(colors[color]);
      }

      // Check if it's a config step
      const isConfig = step.classList.contains('config-step');
      isConfigMode = isConfig;

      // Hide/show footer navigation based on mode
      if (footer) {
        if (isConfigMode) {
          footer.style.display = 'none';
        } else {
          footer.style.display = 'flex';
        }
      }

      enforceOverflowHidden();
      return step;
    }
    return null;
  }

  // Set regular step by index
  function setStep(index) {
    if (index < 0 || index >= totalSteps) return;

    savedStepIndex = index;
    isConfigMode = false;

    hideAllSteps();
    const currentStepEl = steps[index];
    currentStepEl.classList.add('active');

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

    // Update background color
    const color = currentStepEl.getAttribute('data-color');
    if (color && colors[color]) {
      body.classList.remove('color');
      Object.values(colors).forEach(c => {
        body.classList.remove('color-' + c);
        body.classList.remove(c);
      });
      body.classList.add('color');
      body.classList.add('color-' + colors[color]);
      body.classList.add(colors[color]);
    }

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

    // Update navigation buttons
    if (prevBtn) {
      prevBtn.disabled = index === 0;
    }
    if (nextBtn) {
      nextBtn.disabled = index === totalSteps - 1;
    }

    currentStep = index;
    enforceOverflowHidden();
  }

  // Next step (only for regular steps)
  function nextStep() {
    if (!isConfigMode && currentStep < totalSteps - 1) {
      setStep(currentStep + 1);
    }
  }

  // Previous step (only for regular steps)
  function prevStep() {
    if (!isConfigMode && currentStep > 0) {
      setStep(currentStep - 1);
    }
  }

  // Config functions
  function configFor(key) {
    if (!window.OVWebview || !window.OVWebview.fetchSettings) {
      return false;
    }
    const data = window.OVWebview.fetchSettings(key);
    if (data) {
      try {
        const config = JSON.parse(data);
        return config.results;
      } catch (e) {
        console.error('Error parsing config:', e);
        return false;
      }
    }
    return false;
  }

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

    for (let i in results) {
      const item = results[i];
      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) {
        // Set the data-config-setting attribute so quickSetup knows which config to apply
        confirmBtn.setAttribute('data-config-setting', config);
      }
    } else {
      showStepById('config-error');
    }
  }

  function parseConfigResults(json) {
    try {
      const data = JSON.parse(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');
    }
  }

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

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

  // Handle config navigation
  function handleConfigClick(e) {
    const target = e.target.closest('a');
    if (!target) return;

    e.preventDefault();

    // Handle config-confirm (shows confirmation screen) - check this first
    const configConfirm = target.getAttribute('data-config-confirm');
    if (configConfirm) {
      displayConfirmation(configConfirm);
      return;
    }

    // Handle config-setting (applies the config) - check this before config-next
    // This is the key: when confirm button is clicked, it has data-config-setting set
    // by displayConfirmation, so we call quickSetup which makes Cocoa calls to save
    const configSetting = target.getAttribute('data-config-setting');
    if (configSetting && window.OVWebview && window.OVWebview.quickSetup) {
      // This calls the Cocoa layer which saves to NSUserDefaults
      const json = window.OVWebview.quickSetup(configSetting);
      if (json) {
        parseConfigResults(json);
      } else {
        showStepById('config-error');
      }
      return;
    }

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

  // Set up config step click handlers
  function setupConfigHandlers() {
    configSteps.forEach(step => {
      step.addEventListener('click', handleConfigClick);
    });
  }

  // Event listeners
  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();
      }
    });
  }

  // Handle exit setup and start over
  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');
      }
    }
  });

  // Keyboard navigation
  function handleKeydown(e) {
    // Right arrow or Space = next (only in regular steps)
    if (e.key === 'ArrowRight' || (e.key === ' ' && !e.shiftKey)) {
      if (!isConfigMode) {
        e.preventDefault();
        nextStep();
      }
    }
    // Left arrow or Shift+Space = previous (only in regular steps)
    else if (e.key === 'ArrowLeft' || (e.key === ' ' && e.shiftKey)) {
      if (!isConfigMode) {
        e.preventDefault();
        prevStep();
      }
    }
    // Escape = close (if OVWebview is available) or exit config
    else if (e.key === 'Escape') {
      e.preventDefault();
      if (isConfigMode) {
        exitConfig();
      } else if (window.OVWebview && window.OVWebview.closeOverview) {
        window.OVWebview.closeOverview();
      }
    }
  }

  document.addEventListener('keydown', handleKeydown);

  // Video handling (for step with video)
  const video = document.querySelector('video');
  if (video) {
    video.addEventListener('ended', function() {
      const figure = this.closest('figure');
      if (figure) {
        figure.classList.remove('video');
        const poster = this.getAttribute('data-poster');
        if (poster) {
          this.setAttribute('poster', poster);
          this.load();
        }
      }
    });

    const videoFigure = video.closest('figure');
    if (videoFigure) {
      videoFigure.addEventListener('click', function() {
        if (!this.classList.contains('video')) {
          this.classList.add('video');
          video.play();
        }
      });
    }
  }

  // Initialize
  setStep(0);
  setupConfigHandlers();

  // Export API for compatibility with existing code
  if (!window.Marked) {
    window.Marked = {};
  }

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

})();
