(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);
      this.blur();
      lockClickClosed(switcher);
      closeSwitcher(switcher, true);
      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');
      unlockClickClosed(switcher);
      const shouldOpen = !switcher.classList.contains('is-open');
      closeSwitchers();
      if (shouldOpen) {
        openSwitcher(switcher);
      }
    });
  });

  themeSwitchers.forEach(switcher => {
    switcher.addEventListener('mouseenter', function () {
      if (switcher.classList.contains('is-click-closed')) {
        return;
      }

      clearCloseTimer(switcher);
      openSwitcher(switcher);
    });

    switcher.addEventListener('mouseleave', function () {
      unlockClickClosed(switcher);
      scheduleClose(switcher);
    });

    switcher.addEventListener('focusin', function () {
      if (switcher.classList.contains('is-click-closed')) {
        return;
      }

      clearCloseTimer(switcher);
      openSwitcher(switcher);
    });

    switcher.addEventListener('focusout', function (event) {
      if (!switcher.contains(event.relatedTarget)) {
        scheduleClose(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();
      window.scrollTo({ top: 0, behavior: '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);
    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);
        if (isActive) {
          activeButton = button;
        }
      });

      if (currentButton && activeButton) {
        const currentIcon = currentButton.querySelector('i');
        const activeIcon = activeButton.querySelector('i');
        const themeLabel = activeButton.getAttribute('aria-label') || activeButton.getAttribute('title') || theme;
        const labelPrefix = currentButton.dataset.labelPrefix || 'Theme mode:';

        if (currentIcon && activeIcon) {
          currentIcon.className = activeIcon.className;
        }

        currentButton.setAttribute('title', themeLabel);
        currentButton.setAttribute('aria-label', `${labelPrefix} ${themeLabel}`);
      }
    });
  }

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

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

    scheduleIdleClose(switcher);
  }

  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, true);
      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 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 lockClickClosed(switcher) {
    if (switcher) {
      switcher.classList.add('is-click-closed');
    }
  }

  function unlockClickClosed(switcher) {
    if (switcher) {
      switcher.classList.remove('is-click-closed');
    }
  }

  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;
  }
});
