/**
 * STRYKE WP — Branding Admin JS
 *
 * Handles:
 * - Alpine.js theme store ($store.theme) for dark/light mode toggle
 * - Dark/light theme mode persistence via AJAX
 * - Body class toggling for CSS custom property scoping
 *
 * Registered by AdminStyles::enqueue() on all admin pages when Branding is active.
 * Receives strykeAdmin.themeMode ('dark' | 'light') from wp_localize_script().
 */

( function () {
	'use strict';

	if ( typeof strykeAdmin === 'undefined' ) {
		return;
	}

	// Apply the stored theme mode immediately to prevent flash.
	var initialMode = strykeAdmin.themeMode || 'dark';
	document.documentElement.setAttribute( 'data-stryke-theme', initialMode );

	/**
	 * Persist the theme mode via AJAX to ThemePreference::ajax_save().
	 */
	function persistTheme( mode ) {
		var body = new FormData();
		body.append( 'action',   'stryke_set_theme' );
		body.append( '_wpnonce', strykeAdmin.nonce );
		body.append( 'mode',     mode );

		fetch( strykeAdmin.ajaxUrl, {
			method:      'POST',
			body:        body,
			credentials: 'same-origin',
		} );
	}

	/**
	 * Apply theme classes to the body element.
	 */
	function applyTheme( mode ) {
		var body = document.body;
		body.classList.remove( 'stryke-dark', 'stryke-light' );
		body.classList.add( 'stryke-' + mode );
		document.documentElement.setAttribute( 'data-stryke-theme', mode );
	}

	// Register Alpine.js store once Alpine is available.
	// AdminShell.php uses $store.theme.toggle() and $store.theme.mode.
	document.addEventListener( 'alpine:init', function () {
		window.Alpine.store( 'theme', {
			mode: initialMode,

			toggle: function () {
				this.mode = this.mode === 'dark' ? 'light' : 'dark';
				applyTheme( this.mode );
				persistTheme( this.mode );
			},
		} );
	} );
}() );
