(function () {
  'use strict';

  if (!/^(localhost|127\.0\.0\.1)$/.test(window.location.hostname)) {
    return;
  }

  const THEME_KEY = 'overview-dev-theme';
  const THEME_CYCLE = ['system', 'dark', 'light'];
  const root = document.documentElement;

  function normalizeTheme(value) {
    return THEME_CYCLE.indexOf(value) >= 0 ? value : 'system';
  }

  function applyDevTheme(theme) {
    const normalized = normalizeTheme(theme);
    if (normalized === 'system') {
      delete root.dataset.devTheme;
      sessionStorage.removeItem(THEME_KEY);
    } else {
      root.dataset.devTheme = normalized;
      sessionStorage.setItem(THEME_KEY, normalized);
    }
    updateThemeToggleLabel();
  }

  function readInitialTheme() {
    const params = new URLSearchParams(window.location.search);
    if (params.has('theme')) {
      return normalizeTheme(params.get('theme'));
    }
    return normalizeTheme(sessionStorage.getItem(THEME_KEY) || 'system');
  }

  function updateThemeToggleLabel() {
    const button = document.getElementById('devThemeToggle');
    if (!button) {
      return;
    }
    const current = root.dataset.devTheme || 'system';
    const labels = {
      system: 'Theme: System',
      dark: 'Theme: Dark',
      light: 'Theme: Light'
    };
    button.textContent = labels[current];
    button.setAttribute('aria-pressed', current === 'system' ? 'false' : 'true');
  }

  applyDevTheme(readInitialTheme());

  window.__quickConfigPresets = {
    'prose-general': [
      { title: 'Processor', state: 'MultiMarkdown' },
      { title: 'Default Style', state: 'Swiss' },
      { title: 'Syntax Highlighting', state: false },
      { title: 'MathJax', state: false }
    ],
    'prose-academic': [
      { title: 'Processor', state: 'MultiMarkdown' },
      { title: 'Default Style', state: 'Swiss' },
      { title: 'Syntax Highlighting', state: false },
      { title: 'MathJax', state: true }
    ],
    code: [
      { title: 'Processor', state: 'CommonMark (GFM)' },
      { title: 'Default Style', state: 'GitHub' },
      { title: 'Syntax Highlighting', state: true },
      { title: 'Syntax Highlight Style', state: 'GitHub' },
      { title: 'GitHub Checkboxes', state: true },
      { title: 'GitHub Emoji', state: true },
      { title: 'MathJax', state: true }
    ]
  };

  function logAction(message) {
    const banner = document.getElementById('devBannerMessage');
    if (banner) {
      banner.textContent = message;
    }
    console.log('[overview dev]', message);
  }

  window.OVWebview = {
    closeOverview: function () {
      logAction('closeOverview()');
    },
    quickSetup: function (key) {
      logAction('quickSetup("' + key + '")');
      const preset = window.__quickConfigPresets[key];
      return Promise.resolve(
        JSON.stringify({
          success: !!preset,
          results: preset || []
        })
      );
    },
    openSettings: function () {
      logAction('openSettings()');
    },
    openProcessorSettings: function () {
      logAction('openProcessorSettings()');
    },
    openConductor: function () {
      logAction('openConductor()');
    }
  };

  document.addEventListener('click', function (e) {
    const link = e.target.closest('a[href^="x-marked-3:"]');
    if (!link) {
      return;
    }
    e.preventDefault();
    logAction('link: ' + link.getAttribute('href'));
  });

  document.addEventListener('DOMContentLoaded', function () {
    const banner = document.createElement('div');
    banner.id = 'devBanner';

    const message = document.createElement('span');
    message.id = 'devBannerMessage';
    message.setAttribute('aria-live', 'polite');
    message.textContent = 'Dev mode — CSS/JS/HTML auto-reload enabled';

    const themeButton = document.createElement('button');
    themeButton.id = 'devThemeToggle';
    themeButton.type = 'button';
    themeButton.addEventListener('click', function () {
      const current = root.dataset.devTheme || 'system';
      const nextIndex = (THEME_CYCLE.indexOf(current) + 1) % THEME_CYCLE.length;
      applyDevTheme(THEME_CYCLE[nextIndex]);
    });

    banner.appendChild(message);
    banner.appendChild(themeButton);
    document.body.insertBefore(banner, document.body.firstChild);
    updateThemeToggleLabel();
  });

  const watchPaths = ['dev.html', 'css/overview.css', 'css/dev.css', 'scripts/overview_new.js'];
  const stamps = {};

  async function checkForChanges() {
    for (let i = 0; i < watchPaths.length; i += 1) {
      const path = watchPaths[i];
      try {
        const response = await fetch(path + '?t=' + Date.now(), { method: 'HEAD' });
        const stamp = response.headers.get('Last-Modified') || String(response.status);
        if (stamps[path] && stamps[path] !== stamp) {
          window.location.reload();
          return;
        }
        stamps[path] = stamp;
      } catch (error) {
        // Ignore transient fetch errors while the dev server restarts.
      }
    }
  }

  checkForChanges();
  window.setInterval(checkForChanges, 1000);
})();
