/**
 * TieMeasureFlow - Alpine.js Theme Initialization
 *
 * This script MUST load before Alpine.js (which uses defer).
 * It reads the saved theme from localStorage or the system preference,
 * applies the 'dark' class to <html> immediately (no flash), and
 * registers an Alpine.store('theme') for reactive toggling.
 */

(function () {
  'use strict';

  // ---- Immediate theme application (before paint) ----

  var STORAGE_KEY = 'tmf-theme';

  /**
   * Resolve the initial dark-mode state.
   * Priority: server (per-user theme_pref) > localStorage > system preference > light.
   *
   * The server value (window.__SERVER_THEME) is authoritative for logged-in
   * users: it reflects the theme_pref of whoever is currently authenticated,
   * so switching user actually switches theme instead of inheriting the
   * previous user's localStorage value. It is empty for anonymous pages.
   */
  function getInitialDark() {
    var server = (typeof window !== 'undefined' && window.__SERVER_THEME) || '';
    if (server === 'dark' || server === 'light') {
      // Keep localStorage in sync so the rest of the app stays consistent.
      try { localStorage.setItem(STORAGE_KEY, server); } catch (_) {}
      return server === 'dark';
    }

    var stored = null;
    try {
      stored = localStorage.getItem(STORAGE_KEY);
    } catch (_) {
      // localStorage may be unavailable (private browsing, etc.)
    }

    if (stored === 'dark') return true;
    if (stored === 'light') return false;

    // Fall back to OS preference
    if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {
      return true;
    }

    return false;
  }

  var isDark = getInitialDark();

  // Apply immediately to prevent flash of wrong theme
  if (isDark) {
    document.documentElement.classList.add('dark');
  } else {
    document.documentElement.classList.remove('dark');
  }

  // ---- Enable smooth transitions after first paint ----

  // Use requestAnimationFrame to wait one frame, then enable transitions
  // so the initial theme application does not animate.
  if (typeof requestAnimationFrame === 'function') {
    requestAnimationFrame(function () {
      requestAnimationFrame(function () {
        document.documentElement.classList.add('theme-transitions');
      });
    });
  }

  // ---- Alpine.js Store Registration ----

  // Alpine.store is registered via the alpine:init event, which fires
  // when Alpine begins initialization but before it processes x-data.

  document.addEventListener('alpine:init', function () {
    Alpine.store('theme', {
      dark: isDark,

      toggle: function () {
        this.dark = !this.dark;
        this._apply();
        this._persist();
      },

      set: function (dark) {
        this.dark = dark;
        this._apply();
      },

      // Persist an explicit user choice to the server (session + theme_pref),
      // so it survives navigation and matches on the next login. Best-effort.
      _persist: function () {
        try {
          var csrf = document.querySelector('meta[name=csrf-token]');
          fetch('/auth/set-theme', {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json',
              'X-CSRFToken': (csrf && csrf.content) || ''
            },
            body: JSON.stringify({ theme: this.dark ? 'dark' : 'light' })
          }).catch(function () {});
        } catch (_) {
          // Non-fatal: localStorage already holds the choice for this browser.
        }
      },

      _apply: function () {
        if (this.dark) {
          document.documentElement.classList.add('dark');
        } else {
          document.documentElement.classList.remove('dark');
        }
        try {
          localStorage.setItem(STORAGE_KEY, this.dark ? 'dark' : 'light');
        } catch (_) {
          // Silently ignore storage errors
        }
      }
    });
  });

  // ---- Listen for system preference changes ----

  if (window.matchMedia) {
    try {
      var mq = window.matchMedia('(prefers-color-scheme: dark)');
      mq.addEventListener('change', function (e) {
        // Only auto-switch if the user hasn't manually set a preference
        var stored = null;
        try {
          stored = localStorage.getItem(STORAGE_KEY);
        } catch (_) {}

        if (!stored) {
          var newDark = e.matches;
          if (typeof Alpine !== 'undefined' && Alpine.store('theme')) {
            Alpine.store('theme').set(newDark);
          } else {
            // Alpine not loaded yet, apply directly
            if (newDark) {
              document.documentElement.classList.add('dark');
            } else {
              document.documentElement.classList.remove('dark');
            }
          }
        }
      });
    } catch (_) {
      // Older browsers may not support addEventListener on matchMedia
    }
  }

})();
