<?php
/**
 * Get the normalized right sidebar visibility mode.
 *
 * Treat missing or invalid values as hidden so legacy or incomplete
 * theme_mod data does not unexpectedly show the sidebar.
 *
 * @since 2.6
 * @return string
 */
function fanspaysite_get_right_sidebar_mode() {
	$mode  = get_theme_mod( 'fanspaysite_show_right_sidebar', 'no' );
	$valid = array( 'auto', 'yes', 'no' );

	return in_array( $mode, $valid, true ) ? $mode : 'no';
}

/**
 * Determine whether the right sidebar should render for the current layout.
 *
 * @since 2.6
 * @return bool
 */
function fanspaysite_should_render_right_sidebar() {
	if ( 'no' === fanspaysite_get_right_sidebar_mode() ) {
		return false;
	}

	if ( 'top-bar' === get_theme_mod( 'fanspaysite_layout', 'left-sidebar' ) ) {
		return is_active_sidebar( 'fanspaysite_left_sidebar' ) || is_active_sidebar( 'fanspaysite_right_sidebar' );
	}

	return is_active_sidebar( 'fanspaysite_right_sidebar' );
}

/**
 * Get the current theme color tokens for both light and dark palettes.
 *
 * @since 2.3
 * @return array<string, array<string, string>>
 */
function fanspaysite_get_theme_color_tokens() {
	$defaults = array(
		'light' => array(
			'background' => '#ffffff',
			'text'       => '#333333',
			'link'       => '#77145d',
		),
		'dark'  => array(
			'background' => '#18122B',
			'text'       => '#ffffff',
			'link'       => '#d39ed8',
		),
	);

	$colors = array(
		'light' => array(
			'background' => get_theme_mod( 'light_mode_background_color', $defaults['light']['background'] ),
			'text'       => get_theme_mod( 'light_mode_text_color', $defaults['light']['text'] ),
			'link'       => get_theme_mod( 'light_mode_link_color', $defaults['light']['link'] ),
		),
		'dark'  => array(
			'background' => get_theme_mod( 'dark_mode_background_color', $defaults['dark']['background'] ),
			'text'       => get_theme_mod( 'dark_mode_text_color', $defaults['dark']['text'] ),
			'link'       => get_theme_mod( 'dark_mode_link_color', $defaults['dark']['link'] ),
		),
	);

	$colors          = (array) apply_filters( 'fanspaysite_theme_color_tokens', $colors );
	$colors['light'] = wp_parse_args( $colors['light'] ?? array(), $defaults['light'] );
	$colors['dark']  = wp_parse_args( $colors['dark'] ?? array(), $defaults['dark'] );

	return $colors;
}

/**
 * Output inline CSS for Customizer color, layout, and typography settings.
 *
 * @since 2.0
 */
function fanspaysite_customizer_css() {
	$colors = fanspaysite_get_theme_color_tokens();
	?>
	<style id="fanspaysite-customizer-css">
		:root {
			--fanspaysite-light-background-color: <?php echo esc_attr( $colors['light']['background'] ); ?>;
			--fanspaysite-light-text-color: <?php echo esc_attr( $colors['light']['text'] ); ?>;
			--fanspaysite-light-link-color: <?php echo esc_attr( $colors['light']['link'] ); ?>;
			--fanspaysite-dark-background-color: <?php echo esc_attr( $colors['dark']['background'] ); ?>;
			--fanspaysite-dark-text-color: <?php echo esc_attr( $colors['dark']['text'] ); ?>;
			--fanspaysite-dark-link-color: <?php echo esc_attr( $colors['dark']['link'] ); ?>;
			--fanspaysite-background-color: var(--fanspaysite-light-background-color);
			--fanspaysite-text-color: var(--fanspaysite-light-text-color);
			--fanspaysite-link-color: var(--fanspaysite-light-link-color);
		}
		[data-theme="light"] {
			--text-color: var(--fanspaysite-light-text-color);
			--background-color: var(--fanspaysite-light-background-color);
			--link-color: var(--fanspaysite-light-link-color);
			--fanspaysite-background-color: var(--fanspaysite-light-background-color);
			--fanspaysite-text-color: var(--fanspaysite-light-text-color);
			--fanspaysite-link-color: var(--fanspaysite-light-link-color);
		}
		[data-theme="dark"] {
			--text-color: var(--fanspaysite-dark-text-color);
			--background-color: var(--fanspaysite-dark-background-color);
			--link-color: var(--fanspaysite-dark-link-color);
			--fanspaysite-background-color: var(--fanspaysite-dark-background-color);
			--fanspaysite-text-color: var(--fanspaysite-dark-text-color);
			--fanspaysite-link-color: var(--fanspaysite-dark-link-color);
		}
		<?php // Sticky Menu Bar ?>
		<?php if ( get_theme_mod( 'fanspaysite_sticky_header', true ) ) : ?>
		html { height: auto !important; }
		.site-wrapper { min-height: 100vh; }
		body.archive-display-fullpage .site-wrapper { height: 100vh; }
		body:not(.archive-display-fullpage) { height: auto !important; overflow-y: visible !important; padding-bottom: 0 !important; }
		body:not(.archive-display-fullpage) .site-wrapper { height: auto !important; }
		body:not(.archive-display-fullpage) .site-sidebar,
		body:not(.archive-display-fullpage) .site-content,
		body:not(.archive-display-fullpage) .site-sidebar-right,
		body:not(.archive-display-fullpage) .site-content-wrapper { overflow: visible !important; }
		.layout-top-bar .site-topbar { position: sticky; top: 0; z-index: 9000; overflow: visible; }
		body.admin-bar.layout-top-bar .site-topbar { top: 32px; }
		@media screen and (max-width: 782px) {
			body.admin-bar.layout-top-bar .site-topbar { top: 46px; }
		}
		<?php else : ?>
		html, body { height: auto !important; overflow-y: auto !important; }
		.site-wrapper { height: auto !important; min-height: 100vh; }
		.site-sidebar { overflow: visible !important; }
		.site-content { overflow: visible !important; }
		.site-sidebar-right { overflow: visible !important; }
		.site-content-wrapper { overflow: visible !important; }
		<?php endif; ?>
		<?php // Content width ?>
		<?php $cw = get_theme_mod( 'fanspaysite_content_width', 'default' ); ?>
		<?php if ( $cw === 'boxed' ) : ?>
		.site-content { max-width: 960px; margin-left: auto; margin-right: auto; }
		<?php elseif ( $cw === 'wide' ) : ?>
		.site-content { max-width: 100%; }
		<?php endif; ?>
		<?php // Right sidebar ?>
		<?php $rs = fanspaysite_get_right_sidebar_mode(); ?>
		<?php if ( $rs === 'no' ) : ?>
		.site-sidebar-right { display: none !important; }
		<?php elseif ( $rs === 'yes' ) : ?>
		.site-sidebar-right { display: block !important; }
		<?php endif; ?>
		<?php // Font preset ?>
		<?php
		$font_stacks = array(
			'system'       => '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif',
			'modern'       => '"Inter", -apple-system, BlinkMacSystemFont, sans-serif',
			'rounded'      => '"Nunito", -apple-system, BlinkMacSystemFont, sans-serif',
			'lato'         => '"Lato", system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif',
			'roboto'       => '"Roboto", -apple-system, BlinkMacSystemFont, "Segoe UI", Arial, sans-serif',
			'open_sans'    => '"Open Sans", -apple-system, BlinkMacSystemFont, "Segoe UI", Arial, sans-serif',
			'poppins'      => '"Poppins", -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',
			'serif'        => 'Georgia, "Times New Roman", Times, serif',
			'merriweather' => '"Merriweather", Georgia, "Times New Roman", Times, serif',
		);
		$font = get_theme_mod( 'fanspaysite_font_preset', 'system' );
		if ( isset( $font_stacks[ $font ] ) ) :
		?>
		:root { --font-family-base: <?php echo $font_stacks[ $font ]; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- hardcoded CSS font stacks, no user input ?>; }
		body,
		h1, h2, h3, h4, h5, h6,
		.site-content, .entry-content,
		.ui.menu, .ui.button, .ui.header, .ui.form,
		.ui.input input, .ui.input textarea,
		.ui.card, .ui.item, .ui.list,
		.ui.accordion, .ui.statistic, .ui.step,
		.ui.segment, .ui.message, .ui.label,
		.ui.dropdown, .ui.comment {
			font-family: var(--font-family-base) !important;
		}
		<?php endif; ?>
		<?php
		$page_title_alignment = get_theme_mod( 'fanspaysite_page_title_alignment', 'left' );
		$page_title_alignment = in_array( $page_title_alignment, array( 'left', 'center', 'right' ), true ) ? $page_title_alignment : 'left';

		$page_title_size_map = array(
			'big'    => '2.4rem',
			'normal' => '2rem',
			'small'  => '1.6rem',
			'tiny'   => '1.2rem',
		);
		$page_title_size_key = get_theme_mod( 'fanspaysite_page_title_size', 'normal' );
		$page_title_size     = isset( $page_title_size_map[ $page_title_size_key ] ) ? $page_title_size_map[ $page_title_size_key ] : $page_title_size_map['normal'];
		?>
		.page .entry-header {
			text-align: <?php echo esc_attr( $page_title_alignment ); ?>;
		}
		.page .entry-header .entry-title {
			font-size: <?php echo esc_attr( $page_title_size ); ?>;
		}
		<?php // Fullpage archive mode: remove padding for edge-to-edge media ?>
		<?php if ( 'fullpage' === get_theme_mod( 'fanspaysite_archive_display', 'classic' ) ) : ?>
		.archive-display-fullpage .site-main { padding: 0; max-width: 100%; }
		.archive-display-fullpage .content-area { padding: 0; }
		<?php endif; ?>
		/* --- Fomantic UI dark/light mode palette pairing ---
		   data-fps-original-inverted is set by theme.js initializeInvertedState at DOMContentLoaded.
		   "originally inverted" (="1") elements flip appearance between modes:
		     light mode → they show dark  (inverted)   using the dark palette
		     dark  mode → they show light (de-inverted) using the light palette
		   "originally non-inverted" (="0") elements also flip:
		     light mode → light palette (Fomantic UI default, no override needed)
		     dark  mode → dark palette  (handled below as FOUC guard + native .inverted styles)
		   Before initializeInvertedState runs (no attribute yet), the :not([data-fps-original-inverted])
		   FOUC rules ensure no white-on-white flash while the attribute is absent. */

			/* Light mode – originally-inverted elements: use dark palette so they appear inverted */
			html[data-theme="light"] .ui.segment[data-fps-original-inverted="1"],
			html[data-theme="light"] .ui.form[data-fps-original-inverted="1"],
			html[data-theme="light"] .ui.card[data-fps-original-inverted="1"] {
				background-color: var(--fanspaysite-dark-background-color);
				color: var(--fanspaysite-dark-text-color);
			}
			html[data-theme="light"] .ui.inverted.segment:not([data-fps-original-inverted]),
			html[data-theme="light"] .ui.inverted.form:not([data-fps-original-inverted]),
			html[data-theme="light"] .ui.inverted.card:not([data-fps-original-inverted]) {
				background-color: var(--fanspaysite-dark-background-color);
				color: var(--fanspaysite-dark-text-color);
			}

		/* Dark mode – originally-inverted elements: use light palette so they appear de-inverted.
		   This also fixes white-on-white when body text-color is white but segment bg is white. */
		html[data-theme="dark"] .ui.segment[data-fps-original-inverted="1"],
		html[data-theme="dark"] .ui.form[data-fps-original-inverted="1"],
			html[data-theme="dark"] .ui.card[data-fps-original-inverted="1"] {
				background-color: var(--fanspaysite-light-background-color);
				color: var(--fanspaysite-light-text-color);
			}
			html[data-theme="dark"] .ui.segment[data-fps-original-inverted="0"],
			html[data-theme="dark"] .ui.form[data-fps-original-inverted="0"],
			html[data-theme="dark"] .ui.card[data-fps-original-inverted="0"] {
				background-color: var(--fanspaysite-dark-background-color);
				color: var(--fanspaysite-dark-text-color);
			}
			html[data-theme="dark"] .ui.segment[data-fps-original-inverted="0"],
			html[data-theme="dark"] .ui.card[data-fps-original-inverted="0"] {
				border-color: color-mix(in srgb, var(--fanspaysite-dark-text-color) 22%, transparent);
				box-shadow:
					0 1px 2px 0 color-mix(in srgb, #000 28%, transparent),
					0 0 0 1px color-mix(in srgb, var(--fanspaysite-dark-text-color) 10%, transparent);
			}

			/* Dark mode FOUC – before initializeInvertedState sets the attribute, prevent white-on-white
			   by giving all unprocessed segments the dark palette background + text. */
		html[data-theme="dark"] .ui.segment:not([data-fps-original-inverted]),
		html[data-theme="dark"] .ui.form:not([data-fps-original-inverted]),
		html[data-theme="dark"] .ui.card:not([data-fps-original-inverted]) {
			background-color: var(--background-color);
			color: var(--text-color);
		}
		/* Dark mode – non-inverted elements waiting for syncInvertedClasses to add .inverted */
		html[data-theme="dark"] .ui.segment[data-fps-original-inverted="0"]:not(.inverted),
		html[data-theme="dark"] .ui.form[data-fps-original-inverted="0"]:not(.inverted),
		html[data-theme="dark"] .ui.card[data-fps-original-inverted="0"]:not(.inverted) {
			background-color: var(--background-color);
			color: var(--text-color);
		}
		html[data-theme="dark"] .ui.card:not(.inverted) > .content {
			background-color: var(--background-color);
			color: var(--text-color);
		}
		<?php if ( get_theme_mod( 'fanspaysite_invert_menu_section', false ) ) : ?>
		/* ---- Invert menu/header section ---- */
		[data-theme="light"] .site-sidebar,
		[data-theme="light"] .site-topbar,
		[data-theme="light"] .site-topbar-expanded {
			--text-color: var(--fanspaysite-dark-text-color);
			--background-color: var(--fanspaysite-dark-background-color);
			--link-color: var(--fanspaysite-dark-link-color);
			background-color: var(--fanspaysite-dark-background-color);
			color: var(--fanspaysite-dark-text-color);
		}
		[data-theme="dark"] .site-sidebar,
		[data-theme="dark"] .site-topbar,
		[data-theme="dark"] .site-topbar-expanded {
			--text-color: var(--fanspaysite-light-text-color);
			--background-color: var(--fanspaysite-light-background-color);
			--link-color: var(--fanspaysite-light-link-color);
			background-color: var(--fanspaysite-light-background-color);
			color: var(--fanspaysite-light-text-color);
		}
		[data-theme="light"] .site-sidebar a,
		[data-theme="light"] .site-topbar a,
		[data-theme="light"] .site-topbar-expanded a {
			color: var(--fanspaysite-dark-link-color);
		}
		[data-theme="dark"] .site-sidebar a,
		[data-theme="dark"] .site-topbar a,
		[data-theme="dark"] .site-topbar-expanded a {
			color: var(--fanspaysite-light-link-color);
		}
		/* Mode switcher button tokens must match the inverted section background,
		   not the global theme mode — otherwise buttons become invisible. */
		/* Light mode → header is dark → use dark-mode button tokens (light icon/border) */
		html[data-theme="light"] .site-sidebar #fanspaysiteMode .fpsModeCurrent,
		html[data-theme="light"] .site-sidebar #fanspaysiteMode .fps-mode-options .ui.button,
		html[data-theme="light"] .site-topbar #fanspaysiteMode .fpsModeCurrent,
		html[data-theme="light"] .site-topbar #fanspaysiteMode .fps-mode-options .ui.button {
			color: rgba(255, 255, 255, 0.92) !important;
			background-color: rgba(255, 255, 255, 0.08) !important;
			border-color: rgba(255, 255, 255, 0.24) !important;
		}
		/* Dark mode → header is light → use light-mode button tokens (dark icon/border) */
		html[data-theme="dark"] .site-sidebar #fanspaysiteMode .fpsModeCurrent,
		html[data-theme="dark"] .site-sidebar #fanspaysiteMode .fps-mode-options .ui.button,
		html[data-theme="dark"] .site-topbar #fanspaysiteMode .fpsModeCurrent,
		html[data-theme="dark"] .site-topbar #fanspaysiteMode .fps-mode-options .ui.button {
			color: rgba(0, 0, 0, 0.75) !important;
			background-color: #f2f3f5 !important;
			border-color: rgba(34, 36, 38, 0.18) !important;
		}
		/* Burger menu overlay panel must also use the inverted palette */
		html[data-theme="light"] .sidebar-menu-panel.fps-open {
			background-color: var(--fanspaysite-dark-background-color);
			color: var(--fanspaysite-dark-text-color);
			--text-color: var(--fanspaysite-dark-text-color);
			--background-color: var(--fanspaysite-dark-background-color);
		}
		html[data-theme="light"] .sidebar-menu-panel.fps-open a {
			color: var(--fanspaysite-dark-link-color);
		}
		html[data-theme="light"] .sidebar-menu-panel.fps-open .sidebar-panel-close {
			color: var(--fanspaysite-dark-text-color);
		}
		html[data-theme="dark"] .sidebar-menu-panel.fps-open {
			background-color: var(--fanspaysite-light-background-color);
			color: var(--fanspaysite-light-text-color);
			--text-color: var(--fanspaysite-light-text-color);
			--background-color: var(--fanspaysite-light-background-color);
		}
		html[data-theme="dark"] .sidebar-menu-panel.fps-open a {
			color: var(--fanspaysite-light-link-color);
		}
		html[data-theme="dark"] .sidebar-menu-panel.fps-open .sidebar-panel-close {
			color: var(--fanspaysite-light-text-color);
		}
		/* Fomantic UI hardcodes background:#fff on .ui.menu and rgba(0,0,0,.87)
		   on .item; style.css uses var(--text-color) for .item a links — all of
		   which conflict with the inverted palette set on the panel. Override
		   every layer so the entire overlay is consistently inverted. */
		html[data-theme="light"] .sidebar-menu-panel.fps-open .ui.menu,
		html[data-theme="light"] .sidebar-menu-panel.fps-open .ui.dropdown.fpsDropdown .menu,
		html[data-theme="light"] .sidebar-menu-panel.fps-open .fps-submenu {
			background-color: var(--fanspaysite-dark-background-color) !important;
		}
		html[data-theme="light"] .sidebar-menu-panel.fps-open .ui.menu .item,
		html[data-theme="light"] .sidebar-menu-panel.fps-open .fps-submenu .item {
			color: var(--fanspaysite-dark-text-color) !important;
		}
		html[data-theme="dark"] .sidebar-menu-panel.fps-open .ui.menu,
		html[data-theme="dark"] .sidebar-menu-panel.fps-open .ui.dropdown.fpsDropdown .menu,
		html[data-theme="dark"] .sidebar-menu-panel.fps-open .fps-submenu {
			background-color: var(--fanspaysite-light-background-color) !important;
		}
		html[data-theme="dark"] .sidebar-menu-panel.fps-open .ui.menu .item,
		html[data-theme="dark"] .sidebar-menu-panel.fps-open .fps-submenu .item {
			color: var(--fanspaysite-light-text-color) !important;
		}
		<?php endif; ?>
		<?php if ( get_theme_mod( 'fanspaysite_invert_footer_section', false ) ) : ?>
		/* ---- Invert footer section ---- */
		[data-theme="light"] .site-footer,
		[data-theme="light"] .fps-footer-widgets {
			--text-color: var(--fanspaysite-dark-text-color);
			--background-color: var(--fanspaysite-dark-background-color);
			--link-color: var(--fanspaysite-dark-link-color);
			background-color: var(--fanspaysite-dark-background-color);
			color: var(--fanspaysite-dark-text-color);
		}
		[data-theme="dark"] .site-footer,
		[data-theme="dark"] .fps-footer-widgets {
			--text-color: var(--fanspaysite-light-text-color);
			--background-color: var(--fanspaysite-light-background-color);
			--link-color: var(--fanspaysite-light-link-color);
			background-color: var(--fanspaysite-light-background-color);
			color: var(--fanspaysite-light-text-color);
		}
		[data-theme="light"] .site-footer a,
		[data-theme="light"] .fps-footer-widgets a {
			color: var(--fanspaysite-dark-link-color);
		}
		[data-theme="dark"] .site-footer a,
		[data-theme="dark"] .fps-footer-widgets a {
			color: var(--fanspaysite-light-link-color);
		}
		/* Make .site-content a flex column so the inverted footer is pushed to
		   the very bottom, eliminating the uninverted gap beneath it. */
		.site-content {
			display: flex;
			flex-direction: column;
			padding-bottom: 0;
		}
		/* Push the first footer element (widgets when present, footer otherwise)
		   to the bottom of the flex column via auto top-margin. */
		.site-content:has(.fps-footer-widgets) .fps-footer-widgets { margin-top: auto; }
		.site-content:not(:has(.fps-footer-widgets)) .site-footer { margin-top: auto; }
		/* Restore bottom breathing room inside the footer itself. */
		.site-footer {
			padding-bottom: calc(var(--space-md, 16px) + 10px);
		}
		/* Break out of .site-content's 8 px horizontal padding so the footer
		   spans full page width (visible especially in wide layout). */
		.site-footer,
		.fps-footer-widgets {
			margin-left: -8px;
			margin-right: -8px;
			width: calc(100% + 16px);
		}
		<?php endif; ?>
	</style>
	<?php
}
add_action( 'wp_head', 'fanspaysite_customizer_css' );

/**
 * Get the Google Font family for the active preset.
 *
 * @since 2.6
 * @return string
 */
function fanspaysite_get_google_font_family() {
	$font = get_theme_mod( 'fanspaysite_font_preset', 'system' );
	$google_fonts = array(
		'modern'       => 'Inter:wght@400;600;700',
		'rounded'      => 'Nunito:wght@400;600;700',
		'roboto'       => 'Roboto:wght@400;500;700',
		'open_sans'    => 'Open Sans:wght@400;600;700',
		'poppins'      => 'Poppins:wght@400;500;600;700',
		'merriweather' => 'Merriweather:wght@400;700',
	);

	return isset( $google_fonts[ $font ] ) ? $google_fonts[ $font ] : '';
}

/**
 * Enqueue Google Fonts when a non-system font preset is selected.
 *
 * @since 2.2
 */
function fanspaysite_enqueue_fonts() {
	$font_family = fanspaysite_get_google_font_family();
	if ( '' === $font_family ) {
		return;
	}

	wp_enqueue_style(
		'fanspaysite-google-fonts',
		'https://fonts.googleapis.com/css2?family=' . urlencode( $font_family ) . '&display=swap',
		array(),
		null
	);
}
add_action( 'wp_enqueue_scripts', 'fanspaysite_enqueue_fonts' );

/**
 * Add resource hints for Google Fonts when a webfont preset is active.
 *
 * @since 2.6
 * @param array  $urls          Existing resource hints.
 * @param string $relation_type Hint type.
 * @return array
 */
function fanspaysite_google_fonts_resource_hints( $urls, $relation_type ) {
	if ( '' === fanspaysite_get_google_font_family() || 'preconnect' !== $relation_type ) {
		return $urls;
	}

	$urls[] = 'https://fonts.googleapis.com';
	$urls[] = array(
		'href'        => 'https://fonts.gstatic.com',
		'crossorigin' => 'anonymous',
	);

	return $urls;
}
add_filter( 'wp_resource_hints', 'fanspaysite_google_fonts_resource_hints', 10, 2 );

/**
 * Load Google Fonts asynchronously to keep them out of the critical render path.
 *
 * @since 2.6
 * @param string $html   The generated link tag.
 * @param string $handle Style handle.
 * @param string $href   Style URL.
 * @param string $media  Media attribute.
 * @return string
 */
function fanspaysite_google_fonts_style_loader_tag( $html, $handle, $href, $media ) {
	if ( 'fanspaysite-google-fonts' !== $handle ) {
		return $html;
	}

	$media = $media ? $media : 'all';

	return sprintf(
		"<link rel='stylesheet' id='%1\$s-css' href='%2\$s' media='print' onload=\"this.media='%3\$s'\" />\n<noscript><link rel='stylesheet' id='%1\$s-noscript-css' href='%2\$s' media='%3\$s' /></noscript>\n",
		esc_attr( $handle ),
		esc_url( $href ),
		esc_attr( $media )
	);
}
add_filter( 'style_loader_tag', 'fanspaysite_google_fonts_style_loader_tag', 10, 4 );

/**
 * Whether frontend developer diagnostics are enabled.
 *
 * @since 2.7
 * @return bool
 */
function fanspaysite_developer_mode_enabled() {
	return (bool) get_option( 'fanspaysite_developer_mode', false );
}


// Theme Mode settings
function fanspaysite_add_user_theme_mode_field($user) {
	$user_theme_mode = get_user_meta($user->ID, 'fanspaysite_user_theme_mode', true);
	?>
	<h3><?php _e('Theme Mode', 'fanspaysite'); ?></h3>
	<table class="form-table">
		<tr>
			<th><label for="fanspaysite_user_theme_mode"><?php _e('Theme Mode', 'fanspaysite'); ?></label></th>
			<td>
				<select name="fanspaysite_user_theme_mode" id="fanspaysite_user_theme_mode">
					<option value=""><?php _e('Use Site Default', 'fanspaysite'); ?></option>
					<option value="light" <?php selected($user_theme_mode, 'light'); ?>><?php _e('Light', 'fanspaysite'); ?></option>
					<option value="dark" <?php selected($user_theme_mode, 'dark'); ?>><?php _e('Dark', 'fanspaysite'); ?></option>
					<option value="auto" <?php selected($user_theme_mode, 'auto'); ?>><?php _e('Auto', 'fanspaysite'); ?></option>
				</select>
			</td>
		</tr>
	</table>
	<?php
}
add_action('show_user_profile', 'fanspaysite_add_user_theme_mode_field');
add_action('edit_user_profile', 'fanspaysite_add_user_theme_mode_field');

function fanspaysite_save_user_theme_mode($user_id) {
	if (!current_user_can('edit_user', $user_id)) {
		return false;
	}
	update_user_meta($user_id, 'fanspaysite_user_theme_mode', sanitize_text_field( $_POST['fanspaysite_user_theme_mode'] ?? '' ));
}
add_action('personal_options_update', 'fanspaysite_save_user_theme_mode');
add_action('edit_user_profile_update', 'fanspaysite_save_user_theme_mode');

/**
 * Apply theme mode early in <head> to prevent FOUC (flash of unstyled content).
 *
 * Sets data-theme on <html> before CSS renders so color variables resolve immediately.
 * The Fomantic UI .inverted class toggle runs after DOMContentLoaded since it needs <body>.
 *
 * @since 2.2
 */
function fanspaysite_apply_theme_mode() {
	$theme_mode = fanspaysite_get_current_theme_mode();
	?>
	<script>
	(function(){
		var theme = "<?php echo esc_js( $theme_mode ); ?>";
		var isDark = (theme === "dark") || (theme === "auto" && window.matchMedia && window.matchMedia("(prefers-color-scheme: dark)").matches);
		document.documentElement.setAttribute("data-theme", isDark ? "dark" : "light");
	})();
	</script>
	<?php
}
add_action( 'wp_head', 'fanspaysite_apply_theme_mode', 1 );

/**
 * Apply the resolved theme mode to body after DOM is ready.
 *
 * Leave `.ui.inverted` management to theme.js so authored Fomantic markup
 * keeps its original inversion state.
 *
 * @since 2.2
 */
function fanspaysite_apply_theme_mode_body() {
	$theme_mode = fanspaysite_get_current_theme_mode();
	?>
	<script>
	(function() {
		function fanspaysiteSetConfiguredTheme(theme) {
			if (theme === "auto") {
				if (window.matchMedia && window.matchMedia("(prefers-color-scheme: dark)").matches) {
					document.body.dataset.theme = "dark";
				} else {
					document.body.dataset.theme = "light";
				}
			} else {
				document.body.dataset.theme = theme;
			}
			document.documentElement.setAttribute("data-theme", document.body.dataset.theme);
			var isDark = (document.body.dataset.theme === "dark");
			jQuery("body").toggleClass("inverted", isDark);
		}
		document.addEventListener("DOMContentLoaded", function() {
			fanspaysiteSetConfiguredTheme("<?php echo esc_js( $theme_mode ); ?>");
		});
	})();
	</script>
	<?php
}
add_action( 'wp_footer', 'fanspaysite_apply_theme_mode_body' );

/**
 * Enqueue the theme mode switch script.
 *
 * @since 2.0
 */
function fanspaysite_enqueue_theme_switch_script() {
	$scriptPath = get_template_directory() . '/js/theme.js';
	$version = file_exists( $scriptPath ) ? filemtime( $scriptPath ) : '2.2';
	wp_enqueue_script( 'fanspaysite-theme-switch', get_template_directory_uri() . '/js/theme.js', array( 'jquery' ), $version, true );

	// Pass the current theme mode to the script
	wp_localize_script('fanspaysite-theme-switch', 'fanspaysiteThemeSwitch', array(
		'ajax_url' => admin_url('admin-ajax.php'),
		'current_mode' => fanspaysite_get_current_theme_mode(),
		'developer_mode' => fanspaysite_developer_mode_enabled(),
		'nonce' => wp_create_nonce('fanspaysite-theme-switch-nonce'),
	));
}
add_action('wp_enqueue_scripts', 'fanspaysite_enqueue_theme_switch_script');

// Helper function to get the current theme mode
function fanspaysite_get_current_theme_mode() {

	// Get user-specific theme mode if logged in
	if (is_user_logged_in()) {
		$user_theme_mode = get_user_meta(get_current_user_id(), 'fanspaysite_user_theme_mode', true);
		if ($user_theme_mode ?? false) {
			return $user_theme_mode;
		}
	}

	// Check for a theme mode set in a cookie for non-logged-in users
	if (isset($_COOKIE['fanspaysite_user_theme_mode'])) {
		$cookie_theme_mode = sanitize_text_field($_COOKIE['fanspaysite_user_theme_mode']);
		if (!empty($cookie_theme_mode)) {
			return $cookie_theme_mode;
		}
	}

	// Fallback to the site-wide default theme mode
	return get_theme_mod('fanspaysite_default_theme_mode', 'light') ;
}

// AJAX action to update user theme mode
function fanspaysite_update_theme_mode() {
	check_ajax_referer('fanspaysite-theme-switch-nonce', 'nonce');

	$mode = isset($_POST['mode']) ? sanitize_text_field($_POST['mode']) : 'light'; // Default to light mode if not set.

	if (!is_user_logged_in()) {
		// Set a cookie for non-logged-in users to remember the theme mode.
		$cookie_name = 'fanspaysite_user_theme_mode';
		$cookie_value = $mode;
		$expire = time() + (86400 * 30); // 30 days from now.
		$path = '/'; // Available site-wide.

		setcookie($cookie_name, $cookie_value, $expire, $path, COOKIE_DOMAIN, is_ssl(), true);

		wp_send_json(array(
			'success' => true,
			'message' => 'Theme mode saved in a cookie.'
		));
		return;
	}

	// For logged-in users, update user meta.
	update_user_meta(get_current_user_id(), 'fanspaysite_user_theme_mode', $mode);

	wp_send_json_success('Theme mode updated for user: ' . esc_attr($mode));
}
add_action('wp_ajax_fanspaysite_update_theme_mode', 'fanspaysite_update_theme_mode'); // For logged-in users.
add_action('wp_ajax_nopriv_fanspaysite_update_theme_mode', 'fanspaysite_update_theme_mode'); // For not logged-in users.
