(function () {
  if (document.body) {
    captureInitialInvertedState(document);
  }

  function captureInitialInvertedState(root) {
    const uiElements = root.querySelectorAll('.ui');

    uiElements.forEach(function (element) {
      if (!element.hasAttribute('data-fps-original-inverted')) {
        element.setAttribute('data-fps-original-inverted', element.classList.contains('inverted') ? '1' : '0');
      }
    });
  }
})();

document.addEventListener("DOMContentLoaded", function () {
  const themeSwitchers = document.querySelectorAll('#fanspaysiteMode');
  const backToTopButton = document.getElementById('fanspaysiteBackToTop');
  const closeDelay = 1800;
  const idleCloseDelay = 3500;
  let invertedSyncTimer = null;

  initializeInvertedState(document);

  if (window.MutationObserver) {
    const invertedObserver = new MutationObserver(function (mutations) {
      mutations.forEach(function (mutation) {
        if (mutation.type === 'attributes' && mutation.target instanceof Element) {
          initializeInvertedState(mutation.target);
          return;
        }

        mutation.addedNodes.forEach(function (node) {
          if (!(node instanceof Element)) {
            return;
          }

          initializeInvertedState(node);
        });
      });

      scheduleInvertedSync();
    });

    invertedObserver.observe(document.body, {
      attributes: true,
      attributeFilter: ['class'],
      childList: true,
      subtree: true,
    });
  }

  // Initialize theme from server-provided mode (authoritative) so auto mode resolves correctly
  const currentTheme = (window.fanspaysiteThemeSwitch && fanspaysiteThemeSwitch.current_mode)
    ? fanspaysiteThemeSwitch.current_mode
    : (localStorage.getItem('theme') || 'light');
  setTheme(currentTheme); // Set the initial theme
  updateSwitchers(currentTheme);
  debugThemeState('initialized', currentTheme);

  const themeButtons = document.querySelectorAll('#fanspaysiteMode .fpsMode');
  themeButtons.forEach(button => {
    button.addEventListener('click', function (event) {
      event.preventDefault();
      event.stopPropagation();
      const switcher = this.closest('#fanspaysiteMode');
      const theme = this.dataset.theme;
      setTheme(theme);
      updateSwitchers(theme);
      closeSwitcher(switcher);
      focusSwitcherButton(switcher);
      updateThemeSetting(theme);
    });
  });

  const currentButtons = document.querySelectorAll('#fanspaysiteMode .fpsModeCurrent');
  currentButtons.forEach(button => {
    button.addEventListener('click', function (event) {
      event.preventDefault();
      event.stopPropagation();
      const switcher = this.closest('#fanspaysiteMode');
      const shouldOpen = !switcher.classList.contains('is-open');
      closeSwitchers();
      if (shouldOpen) {
        openSwitcher(switcher);
      }
    });
  });

  themeSwitchers.forEach(switcher => {
    switcher.addEventListener('focusout', function (event) {
      if (!switcher.contains(event.relatedTarget)) {
        scheduleClose(switcher);
      }
    });

    closeSwitcher(switcher);
  });

  document.addEventListener('click', function () {
    closeSwitchers();
  });

  document.addEventListener('keydown', function (event) {
    if (event.key === 'Escape') {
      closeSwitchers();
    }
  });

  if (backToTopButton) {
    const scrollElement = document.scrollingElement || document.documentElement;

    const updateBackToTopVisibility = function () {
      const scrollTop = scrollElement ? scrollElement.scrollTop : window.scrollY;
      const maxScroll = scrollElement ? (scrollElement.scrollHeight - scrollElement.clientHeight) : 0;
      const canScroll = maxScroll > 8;
      const shouldShow = canScroll && scrollTop > 80;

      backToTopButton.classList.toggle('is-visible', shouldShow);
      backToTopButton.setAttribute('aria-hidden', shouldShow ? 'false' : 'true');
      backToTopButton.tabIndex = shouldShow ? 0 : -1;
    };

    backToTopButton.addEventListener('click', function (event) {
      event.preventDefault();
      const reduceMotion = window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches;
      window.scrollTo({ top: 0, behavior: reduceMotion ? 'auto' : 'smooth' });
    });

    window.addEventListener('scroll', updateBackToTopVisibility, { passive: true });
    window.addEventListener('resize', updateBackToTopVisibility, { passive: true });
    updateBackToTopVisibility();
  }

  function setTheme(theme) {
    const isDarkMode = theme === 'dark' || (theme === 'auto' && window.matchMedia("(prefers-color-scheme: dark)").matches);
    // Resolve to actual "dark" or "light" for data-theme so CSS selectors match
    var resolved = isDarkMode ? 'dark' : 'light';
    document.body.dataset.theme = resolved;
    document.documentElement.setAttribute('data-theme', resolved);
    localStorage.setItem('theme', theme); // Store the user's choice (including "auto")
    jQuery("body").toggleClass("inverted", isDarkMode);
    syncInvertedClasses(theme);
    document.dispatchEvent(new CustomEvent('vws-theme-change', {
      detail: {
        preference: theme,
        resolved: resolved,
      },
    }));
    debugThemeState('setTheme', theme);
  }

  function initializeInvertedState(root) {
    if (!(root instanceof Element) && root !== document) {
      return;
    }

    const uiElements = [];

    if (root === document) {
      uiElements.push.apply(uiElements, document.querySelectorAll('.ui'));
    } else {
      if (root.classList.contains('ui')) {
        uiElements.push(root);
      }

      uiElements.push.apply(uiElements, root.querySelectorAll('.ui'));
    }

    uiElements.forEach(function (element) {
      if (!element.hasAttribute('data-fps-original-inverted')) {
        element.setAttribute('data-fps-original-inverted', element.classList.contains('inverted') ? '1' : '0');
        debug('Captured original inverted state', {
          element: describeElement(element),
          originalInverted: element.getAttribute('data-fps-original-inverted'),
        });
      } else {
        debug('Found preserved original inverted state', {
          element: describeElement(element),
          originalInverted: element.getAttribute('data-fps-original-inverted'),
        });
      }
    });
  }

  function scheduleInvertedSync() {
    if (invertedSyncTimer) {
      window.clearTimeout(invertedSyncTimer);
    }

    invertedSyncTimer = window.setTimeout(function () {
      const storedTheme = localStorage.getItem('theme') || currentTheme;
      syncInvertedClasses(storedTheme);
      debugThemeState('mutation-sync', storedTheme);
      invertedSyncTimer = null;
    }, 0);
  }

  function syncInvertedClasses(theme) {
    const isDarkMode = theme === 'dark' || (theme === 'auto' && window.matchMedia("(prefers-color-scheme: dark)").matches);
    let changedCount = 0;

    document.querySelectorAll('.ui').forEach(function (element) {
      const originallyInverted = element.getAttribute('data-fps-original-inverted') === '1';
      const shouldBeInverted = isDarkMode ? !originallyInverted : originallyInverted;
      const wasInverted = element.classList.contains('inverted');

      element.classList.toggle('inverted', shouldBeInverted);

      if (wasInverted !== shouldBeInverted) {
        changedCount++;
      }
    });

    debug('Synced Fomantic inverted classes', {
      requestedTheme: theme,
      resolvedTheme: isDarkMode ? 'dark' : 'light',
      changedCount: changedCount,
      totalUiElements: document.querySelectorAll('.ui').length,
      originallyInvertedCount: document.querySelectorAll('.ui[data-fps-original-inverted="1"]').length,
    });
  }

  // Listen for system color scheme changes to update auto mode in real time
  if (window.matchMedia) {
    window.matchMedia("(prefers-color-scheme: dark)").addEventListener('change', function () {
      const storedTheme = localStorage.getItem('theme');
      if (storedTheme === 'auto') {
        setTheme('auto');
        updateSwitchers('auto');
      }
    });
  }

  function updateSwitchers(theme) {
    themeSwitchers.forEach(switcher => {
      switcher.dataset.themeMode = theme;

      let activeButton = null;
      const currentButton = switcher.querySelector('.fpsModeCurrent');

      switcher.querySelectorAll('.fpsMode').forEach(button => {
        const isActive = button.dataset.theme === theme;
        button.classList.toggle('active', isActive);
        button.classList.toggle('is-current', isActive);
        button.setAttribute('aria-selected', isActive ? 'true' : 'false');
        if (isActive) {
          activeButton = button;
        }
      });

      if (currentButton && activeButton) {
        const currentIcon = currentButton.querySelector('i');
        const activeIcon = activeButton.querySelector('i');
        if (currentIcon && activeIcon) {
          currentIcon.className = activeIcon.className;
        }
      }
    });
  }

  function openSwitcher(switcher) {
    if (!switcher) {
      return;
    }

    clearCloseTimer(switcher);
    clearIdleCloseTimer(switcher);
    switcher.classList.add('is-open');
    const options = switcher.querySelector('.fps-mode-options');
    if (options) {
      options.hidden = false;
    }
    const currentButton = switcher.querySelector('.fpsModeCurrent');
    if (currentButton) {
      currentButton.setAttribute('aria-expanded', 'true');
    }

  }

  function scheduleClose(switcher) {
    if (!switcher) {
      return;
    }

    clearCloseTimer(switcher);
    switcher._fpsModeCloseTimer = window.setTimeout(function () {
      closeSwitcher(switcher);
      switcher._fpsModeCloseTimer = null;
    }, closeDelay);
  }

  function scheduleIdleClose(switcher) {
    if (!switcher) {
      return;
    }

    clearIdleCloseTimer(switcher);
    switcher._fpsModeIdleCloseTimer = window.setTimeout(function () {
      closeSwitcher(switcher);
      switcher._fpsModeIdleCloseTimer = null;
    }, idleCloseDelay);
  }

  function clearCloseTimer(switcher) {
    if (switcher && switcher._fpsModeCloseTimer) {
      window.clearTimeout(switcher._fpsModeCloseTimer);
      switcher._fpsModeCloseTimer = null;
    }
  }

  function clearIdleCloseTimer(switcher) {
    if (switcher && switcher._fpsModeIdleCloseTimer) {
      window.clearTimeout(switcher._fpsModeIdleCloseTimer);
      switcher._fpsModeIdleCloseTimer = null;
    }
  }

  function closeSwitcher(switcher, blurActive) {
    if (!switcher) {
      return;
    }

    clearCloseTimer(switcher);
    clearIdleCloseTimer(switcher);
    switcher.classList.remove('is-open');
    const options = switcher.querySelector('.fps-mode-options');
    if (options) {
      options.hidden = true;
    }

    const currentButton = switcher.querySelector('.fpsModeCurrent');
    if (currentButton) {
      currentButton.setAttribute('aria-expanded', 'false');
    }

    if (blurActive) {
      const activeElement = document.activeElement;
      if (activeElement && switcher.contains(activeElement) && typeof activeElement.blur === 'function') {
        activeElement.blur();
      }
    }
  }

  function closeSwitchers(blurActive) {
    themeSwitchers.forEach(switcher => {
      closeSwitcher(switcher, blurActive);
    });
  }

  function focusSwitcherButton(switcher) {
    if (!switcher) {
      return;
    }

    const currentButton = switcher.querySelector('.fpsModeCurrent');
    if (currentButton && typeof currentButton.focus === 'function') {
      currentButton.focus();
    }
  }

  function updateThemeSetting(theme) {
    jQuery.ajax({
      url: fanspaysiteThemeSwitch.ajax_url,
      type: "POST",
      data: {
        action: "fanspaysite_update_theme_mode",
        mode: theme,
        nonce: fanspaysiteThemeSwitch.nonce,
      },
      success: function (response) {
        if (response.warning) {
          console.warn(response.message);
        } else {
          debug("Theme mode updated using AJAX.", response);
        }
      },
      error: function (xhr, status, error) {
        console.error("AJAX Error:", status, error);
      }
    });
  }

  function isDeveloperMode() {
    return !!(window.fanspaysiteThemeSwitch && fanspaysiteThemeSwitch.developer_mode);
  }

  function debug(message, details) {
    if (!isDeveloperMode() || !window.console) {
      return;
    }

    if (details === undefined) {
      console.log('FansPaysite:', message);
      return;
    }

    console.log('FansPaysite:', message, details);
  }

  function debugThemeState(context, theme) {
    debug('Theme state ' + context, {
      requestedTheme: theme,
      htmlTheme: document.documentElement.getAttribute('data-theme'),
      bodyTheme: document.body ? document.body.dataset.theme : '',
      bodyInverted: document.body ? document.body.classList.contains('inverted') : false,
      uiElements: document.querySelectorAll('.ui').length,
      uiInverted: document.querySelectorAll('.ui.inverted').length,
      uiOriginalInverted: document.querySelectorAll('.ui[data-fps-original-inverted="1"]').length,
      foreignSetConfiguredTheme: typeof window.setConfiguredTheme === 'function',
    });
  }

  function describeElement(element) {
    if (!element) {
      return '';
    }

    const id = element.id ? '#' + element.id : '';
    const className = element.className ? '.' + String(element.className).trim().replace(/\s+/g, '.') : '';
    return element.tagName.toLowerCase() + id + className;
  }
});
