(function () {
  'use strict';

  var STORAGE_KEY = 'iav_theme';
  var VALID = ['system', 'light', 'dark'];
  var media = window.matchMedia('(prefers-color-scheme: dark)');

  function storedChoice() {
    try {
      var value = localStorage.getItem(STORAGE_KEY) || 'system';
      return VALID.indexOf(value) === -1 ? 'system' : value;
    } catch (error) {
      return 'system';
    }
  }

  function resolvedTheme(choice) {
    return choice === 'system' ? (media.matches ? 'dark' : 'light') : choice;
  }

  function apply(choice, persist) {
    var selected = VALID.indexOf(choice) === -1 ? 'system' : choice;
    var resolved = resolvedTheme(selected);

    document.documentElement.dataset.theme = resolved;
    document.documentElement.dataset.themeChoice = selected;

    if (persist !== false) {
      try {
        localStorage.setItem(STORAGE_KEY, selected);
      } catch (error) {
        // Storage can be unavailable in strict privacy modes.
      }
    }

    window.dispatchEvent(new CustomEvent('iav:themechange', {
      detail: { choice: selected, resolved: resolved }
    }));

    return resolved;
  }

  function toggle() {
    var current = document.documentElement.dataset.theme || resolvedTheme(storedChoice());
    return apply(current === 'dark' ? 'light' : 'dark', true);
  }

  function systemChanged() {
    if (storedChoice() === 'system') {
      apply('system', false);
    }
  }

  if (typeof media.addEventListener === 'function') {
    media.addEventListener('change', systemChanged);
  } else if (typeof media.addListener === 'function') {
    media.addListener(systemChanged);
  }

  window.InstantAITheme = {
    apply: apply,
    toggle: toggle,
    getChoice: storedChoice,
    getResolved: function () {
      return document.documentElement.dataset.theme || resolvedTheme(storedChoice());
    }
  };

  apply(storedChoice(), false);
}());
