/**
 * Dark Mode Toggle - Frontend Script
 *
 * @package kairo
 */

/**
 * Immediate theme initialization - runs before DOM is ready.
 * This prevents flash of wrong theme colors on page load.
 * CSP-compliant: no inline scripts, uses external file.
 * Uses multiple fallback mechanisms for WordPress.com compatibility.
 */
( function() {
	'use strict';

	// Get settings from localized script data or use defaults.
	var settings = window.kairoThemeSettings || {};
	var STORAGE_KEY = settings.storageKey || 'kairo-color-mode';
	var defaultMode = settings.defaultMode || 'system';

	/**
	 * Apply theme using multiple methods for maximum compatibility.
	 * WordPress.com may block some methods, so we try all of them.
	 */
	function applyTheme( theme ) {
		var root = document.documentElement;
		var body = document.body;

		// Method 1: data-theme attribute on html element (standard).
		try {
			root.setAttribute( 'data-theme', theme );
		} catch ( e ) {}

		// Method 2: Class on html element (fallback for restrictive CSP).
		try {
			root.classList.remove( 'kairo-theme-light', 'kairo-theme-dark' );
			root.classList.add( 'kairo-theme-' + theme );
		} catch ( e ) {}

		// Method 3: Class on body element (another fallback).
		if ( body ) {
			try {
				body.classList.remove( 'kairo-theme-light', 'kairo-theme-dark' );
				body.classList.add( 'kairo-theme-' + theme );
			} catch ( e ) {}
		}
	}

	try {
		var stored = localStorage.getItem( STORAGE_KEY );
		var theme;

		if ( stored ) {
			theme = stored;
		} else if ( defaultMode === 'dark' ) {
			theme = 'dark';
		} else if ( defaultMode === 'light' ) {
			theme = 'light';
		} else {
			// System preference.
			theme = window.matchMedia( '(prefers-color-scheme: dark)' ).matches ? 'dark' : 'light';
		}

		applyTheme( theme );

		// Store for later use by the main script.
		window.kairoCurrentTheme = theme;
	} catch ( e ) {
		// localStorage may be blocked in some environments.
		// Fall back to system preference via CSS media queries.
	}
} )();

/**
 * Main dark mode toggle functionality.
 */
( function() {
	'use strict';

	// Get settings from localized script data or use defaults.
	var settings = window.kairoThemeSettings || {};
	var STORAGE_KEY = settings.storageKey || 'kairo-color-mode';

	/**
	 * Get default mode from the first toggle block on the page.
	 */
	function getDefaultMode() {
		// First check localized settings.
		if ( settings.defaultMode ) {
			return settings.defaultMode;
		}
		// Fallback to data attribute on toggle element.
		var toggle = document.querySelector( '.kairo-dark-mode-toggle[data-default-mode]' );
		if ( toggle ) {
			return toggle.getAttribute( 'data-default-mode' ) || 'system';
		}
		return 'system';
	}

	/**
	 * Get the theme based on system preference.
	 */
	function getSystemTheme() {
		return window.matchMedia( '(prefers-color-scheme: dark)' ).matches ? 'dark' : 'light';
	}

	/**
	 * Get the preferred theme - checks localStorage first, then default mode.
	 */
	function getPreferredTheme() {
		try {
			// Check localStorage for user's saved choice.
			var stored = localStorage.getItem( STORAGE_KEY );
			if ( stored ) {
				return stored;
			}
		} catch ( e ) {
			// localStorage not available.
		}

		// No stored preference, use the block's default mode setting.
		var defaultMode = getDefaultMode();
		
		if ( defaultMode === 'light' ) {
			return 'light';
		}
		
		if ( defaultMode === 'dark' ) {
			return 'dark';
		}
		
		// System preference.
		return getSystemTheme();
	}

	/**
	 * Apply theme using multiple methods for maximum compatibility.
	 * WordPress.com may block some methods, so we try all of them.
	 */
	function applyThemeToDOM( theme ) {
		var root = document.documentElement;
		var body = document.body;

		// Method 1: data-theme attribute on html element (standard).
		try {
			root.setAttribute( 'data-theme', theme );
		} catch ( e ) {}

		// Method 2: Class on html element (fallback for restrictive CSP).
		try {
			root.classList.remove( 'kairo-theme-light', 'kairo-theme-dark' );
			root.classList.add( 'kairo-theme-' + theme );
		} catch ( e ) {}

		// Method 3: Class on body element (another fallback).
		if ( body ) {
			try {
				body.classList.remove( 'kairo-theme-light', 'kairo-theme-dark' );
				body.classList.add( 'kairo-theme-' + theme );
			} catch ( e ) {}
		}
	}

	/**
	 * Set the theme on the document and save to localStorage.
	 */
	function setTheme( theme ) {
		applyThemeToDOM( theme );
		try {
			localStorage.setItem( STORAGE_KEY, theme );
		} catch ( e ) {
			// localStorage not available.
		}
		updateToggleButtons( theme );
	}

	/**
	 * Update all toggle buttons to reflect current theme.
	 */
	function updateToggleButtons( theme ) {
		var toggles = document.querySelectorAll( '.kairo-dark-mode-toggle' );
		toggles.forEach( function( toggle ) {
			var btn = toggle.querySelector( '.kairo-toggle-btn' );
			var label = toggle.querySelector( '.kairo-toggle-label' );
			
			if ( btn ) {
				btn.setAttribute( 'aria-pressed', theme === 'dark' );
			}
			
			if ( label ) {
				var showLabel = toggle.getAttribute( 'data-show-label' ) === 'true';
				if ( showLabel ) {
					var lightLabel = toggle.getAttribute( 'data-light-label' ) || 'Light';
					var darkLabel = toggle.getAttribute( 'data-dark-label' ) || 'Dark';
					label.textContent = theme === 'dark' ? lightLabel : darkLabel;
				}
			}
		} );
	}

	/**
	 * Toggle between light and dark themes.
	 */
	function toggleTheme() {
		var current = document.documentElement.getAttribute( 'data-theme' ) || getPreferredTheme();
		var next = current === 'dark' ? 'light' : 'dark';
		setTheme( next );
	}

	/**
	 * Initialize the dark mode toggle.
	 */
	function init() {
		// Get preferred theme and apply.
		var theme = getPreferredTheme();
		document.documentElement.setAttribute( 'data-theme', theme );
		updateToggleButtons( theme );

		// Add click handlers to all toggle buttons.
		document.querySelectorAll( '.kairo-dark-mode-toggle .kairo-toggle-btn' ).forEach( function( btn ) {
			btn.addEventListener( 'click', toggleTheme );
		} );

		// Listen for system preference changes (only affects users who haven't made a choice).
		window.matchMedia( '(prefers-color-scheme: dark)' ).addEventListener( 'change', function( e ) {
			var stored = null;
			try {
				stored = localStorage.getItem( STORAGE_KEY );
			} catch ( err ) {
				// localStorage not available.
			}
			var currentDefaultMode = getDefaultMode();
			
			// Only respond to system changes if no stored preference and default is system.
			if ( ! stored && currentDefaultMode === 'system' ) {
				var newTheme = e.matches ? 'dark' : 'light';
				document.documentElement.setAttribute( 'data-theme', newTheme );
				updateToggleButtons( newTheme );
			}
		} );
	}

	// Initialize when DOM is ready.
	if ( document.readyState === 'loading' ) {
		document.addEventListener( 'DOMContentLoaded', init );
	} else {
		init();
	}
} )();

