<?php
/**
 * FansPaysite Admin Page
 * Admin page: Appearance > FansPaysite (wp-admin/themes.php?page=fanspaysite)
 * Manages skins, advanced settings, admin dark mode, and integration docs.
 */

// Register admin page under Appearance
function fanspaysite_register_skins_page() {
	add_theme_page(
		__('FansPaysite Theme Settings', 'fanspaysite'),
		__('FansPaysite', 'fanspaysite'),
		'edit_theme_options',
		'fanspaysite',
		'fanspaysite_skins_page_html'
	);
}
add_action('admin_menu', 'fanspaysite_register_skins_page');

/**
 * Built-in skins that ship with the theme.
 */
function fanspaysite_get_builtin_skins() {
	$skins = array(
		'default' => array(
			'name'        => __('Default', 'fanspaysite'),
			'description' => __('FansPaysite default: top bar layout with burger menu, light mode with purple accents.', 'fanspaysite'),
			'layout'      => 'top-bar',
			'burger_menu'    => 'yes',
			'menu_display' => 'auto',
			'submenu_display' => 'auto',
			'submenu_hover' => 'auto',
			'default_mode' => 'light',
			'archive_display' => 'classic',
			'colors'      => array(
				'light_bg'   => '#ffffff',
				'light_text' => '#333333',
				'light_link' => '#77145d',
				'dark_bg'    => '#18122B',
				'dark_text'  => '#ffffff',
				'dark_link'  => '#d39ed8',
			),
			'custom_css'  => '',
			'is_builtin'  => true,
		),
		'sidebar-cyan' => array(
			'name'        => __('Sidebar Cyan', 'fanspaysite'),
			'description' => __('Left sidebar layout, light mode default, large icon navigation with cyan-blue accent color.', 'fanspaysite'),
			'layout'      => 'left-sidebar',
			'burger_menu'    => 'auto',
			'menu_display' => 'big_icon',
			'submenu_display' => 'auto',
			'submenu_hover' => 'auto',
			'default_mode' => 'light',
			'archive_display' => 'boxes',
			'colors'      => array(
				'light_bg'   => '#ffffff',
				'light_text' => '#0d0d0d',
				'light_link' => '#006f99',
				'dark_bg'    => '#1a1a1a',
				'dark_text'  => '#f5f5f5',
				'dark_link'  => '#7ddcff',
			),
			'custom_css'  => '',
			'is_builtin'  => true,
		),
		'sidebar-green' => array(
			'name'        => __('Sidebar Green', 'fanspaysite'),
			'description' => __('Left sidebar layout, light mode default, large icon navigation with bright green accent color.', 'fanspaysite'),
			'layout'      => 'left-sidebar',
			'burger_menu'    => 'auto',
			'menu_display' => 'big_icon',
			'submenu_display' => 'auto',
			'submenu_hover' => 'auto',
			'default_mode' => 'light',
			'archive_display' => 'fullpage',
			'colors'      => array(
				'light_bg'   => '#ffffff',
				'light_text' => '#1a1a1a',
				'light_link' => '#007a33',
				'dark_bg'    => '#121212',
				'dark_text'  => '#f0f0f0',
				'dark_link'  => '#69f0ae',
			),
			'custom_css'  => '',
			'is_builtin'  => true,
		),
		'sidebar-blue' => array(
			'name'        => __('Community Blue', 'fanspaysite'),
			'description' => __('Left sidebar layout, light mode default, small icon with text navigation and classic blue accent color.', 'fanspaysite'),
			'layout'      => 'left-sidebar',
			'burger_menu'    => 'auto',
			'menu_display' => 'small_icon_text',
			'submenu_display' => 'auto',
			'submenu_hover' => 'auto',
			'default_mode' => 'light',
			'archive_display' => 'classic',
			'colors'      => array(
				'light_bg'   => '#ffffff',
				'light_text' => '#2d2d2d',
				'light_link' => '#0066cc',
				'dark_bg'    => '#1c1c1c',
				'dark_text'  => '#e0e0e0',
				'dark_link'  => '#4d94ff',
			),
			'custom_css'  => '',
			'is_builtin'  => true,
		),
		'topbar-dark' => array(
			'name'        => __('Topbar Dark', 'fanspaysite'),
			'description' => __('Top bar navigation, dark mode default, near-black background with purple-violet accent color.', 'fanspaysite'),
			'layout'      => 'top-bar',
			'burger_menu'    => 'auto',
			'menu_display' => 'big_icon',
			'submenu_display' => 'small_icon_text',
			'submenu_hover' => 'auto',
			'default_mode' => 'dark',
			'archive_display' => 'fullpage',
			'colors'      => array(
				'light_bg'   => '#f8f8ff',
				'light_text' => '#1a1a2e',
				'light_link' => '#6c5ce7',
				'dark_bg'    => '#0d0d0d',
				'dark_text'  => '#e8e8f0',
				'dark_link'  => '#a29bfe',
			),
			'custom_css'  => '',
			'is_builtin'  => true,
		),
	);

	return apply_filters( 'fanspaysite_builtin_skins', $skins );
}

/**
 * Get all skins: built-in + custom saved ones.
 */
function fanspaysite_get_all_skins() {
	$builtin = fanspaysite_get_builtin_skins();
	$custom  = get_option('fanspaysite_skins', array());
	$skins   = array_merge($builtin, $custom);

	return apply_filters( 'fanspaysite_all_skins', $skins, $builtin, $custom );
}

/**
 * Check whether the active theme already has explicit skin-related theme mods.
 *
 * This prevents the built-in default skin bootstrap from overwriting older or
 * already configured installs.
 *
 * @since 2.6
 * @return bool
 */
function fanspaysite_has_saved_skin_state() {
	$theme_mods = get_option( 'theme_mods_' . get_stylesheet(), array() );

	if ( ! is_array( $theme_mods ) ) {
		return false;
	}

	$tracked_keys = array(
		'fanspaysite_layout',
		'fanspaysite_burger_menu',
		'fanspaysite_menu_display_mode',
		'fanspaysite_submenu_display_mode',
		'fanspaysite_submenu_hover',
		'fanspaysite_default_theme_mode',
		'light_mode_background_color',
		'light_mode_text_color',
		'light_mode_link_color',
		'dark_mode_background_color',
		'dark_mode_text_color',
		'dark_mode_link_color',
		'fanspaysite_skin_custom_css',
		'fanspaysite_archive_display',
	);

	foreach ( $tracked_keys as $key ) {
		if ( array_key_exists( $key, $theme_mods ) ) {
			return true;
		}
	}

	return false;
}

/**
 * Apply the built-in default skin on first activation.
 *
 * @since 2.6
 * @return void
 */
function fanspaysite_maybe_apply_default_skin() {
	$active_skin = get_option( 'fanspaysite_active_skin', null );

	if ( null !== $active_skin || fanspaysite_has_saved_skin_state() ) {
		return;
	}

	fanspaysite_apply_skin( 'default' );
}
add_action( 'after_switch_theme', 'fanspaysite_maybe_apply_default_skin' );

/**
 * Built-in palettes for the palette manager tab.
 *
 * Each preset is inspired by a high-like palette from Color Hunt's dark tag.
 * The theme stores six colors, so each preset includes paired light/dark values.
 *
 * @return array<string, array<string, mixed>>
 */
function fanspaysite_get_builtin_palettes() {
	$palettes = array(
		'palette-01' => array(
			'label'       => __( 'Palette 01', 'fanspaysite' ),
			'source_likes'=> 11163,
			'colors'      => array('light_bg' => '#DFD0B8', 'light_text' => '#393E46', 'light_link' => '#948979', 'dark_bg' => '#222831', 'dark_text' => '#DFD0B8', 'dark_link' => '#948979'),
			'is_builtin'  => true,
		),
		'palette-02' => array(
			'label'       => __( 'Palette 02', 'fanspaysite' ),
			'source_likes'=> 10570,
			'colors'      => array('light_bg' => '#F4E5ED', 'light_text' => '#3B1C32', 'light_link' => '#A64D79', 'dark_bg' => '#1A1A1D', 'dark_text' => '#F4E5ED', 'dark_link' => '#A64D79'),
			'is_builtin'  => true,
		),
		'palette-03' => array(
			'label'       => __( 'Palette 03', 'fanspaysite' ),
			'source_likes'=> 10776,
			'colors'      => array('light_bg' => '#ECDFCC', 'light_text' => '#3C3D37', 'light_link' => '#697565', 'dark_bg' => '#181C14', 'dark_text' => '#ECDFCC', 'dark_link' => '#697565'),
			'is_builtin'  => true,
		),
		'palette-04' => array(
			'label'       => __( 'Palette 04', 'fanspaysite' ),
			'source_likes'=> 14295,
			'colors'      => array('light_bg' => '#F9E7EE', 'light_text' => '#5D0E41', 'light_link' => '#A0153E', 'dark_bg' => '#00224D', 'dark_text' => '#F9E7EE', 'dark_link' => '#FF204E'),
			'is_builtin'  => true,
		),
		'palette-05' => array(
			'label'       => __( 'Palette 05', 'fanspaysite' ),
			'source_likes'=> 16202,
			'colors'      => array('light_bg' => '#EEEEEE', 'light_text' => '#31363F', 'light_link' => '#76ABAE', 'dark_bg' => '#222831', 'dark_text' => '#EEEEEE', 'dark_link' => '#76ABAE'),
			'is_builtin'  => true,
		),
		'palette-06' => array(
			'label'       => __( 'Palette 06', 'fanspaysite' ),
			'source_likes'=> 16764,
			'colors'      => array('light_bg' => '#ECEBFA', 'light_text' => '#1B1A55', 'light_link' => '#535C91', 'dark_bg' => '#070F2B', 'dark_text' => '#ECEBFA', 'dark_link' => '#9290C3'),
			'is_builtin'  => true,
		),
		'palette-07' => array(
			'label'       => __( 'Palette 07', 'fanspaysite' ),
			'source_likes'=> 11887,
			'colors'      => array('light_bg' => '#F6E4F1', 'light_text' => '#3C0753', 'light_link' => '#910A67', 'dark_bg' => '#030637', 'dark_text' => '#F6E4F1', 'dark_link' => '#910A67'),
			'is_builtin'  => true,
		),
		'palette-08' => array(
			'label'       => __( 'Palette 08', 'fanspaysite' ),
			'source_likes'=> 10166,
			'colors'      => array('light_bg' => '#F0E6E6', 'light_text' => '#503C3C', 'light_link' => '#7E6363', 'dark_bg' => '#3E3232', 'dark_text' => '#F0E6E6', 'dark_link' => '#A87C7C'),
			'is_builtin'  => true,
		),
		'palette-09' => array(
			'label'       => __( 'Palette 09', 'fanspaysite' ),
			'source_likes'=> 12382,
			'colors'      => array('light_bg' => '#E5F2EE', 'light_text' => '#1B4242', 'light_link' => '#5C8374', 'dark_bg' => '#092635', 'dark_text' => '#E5F2EE', 'dark_link' => '#9EC8B9'),
			'is_builtin'  => true,
		),
		'palette-10' => array(
			'label'       => __( 'Palette 10', 'fanspaysite' ),
			'source_likes'=> 10563,
			'colors'      => array('light_bg' => '#FCE9E5', 'light_text' => '#872341', 'light_link' => '#BE3144', 'dark_bg' => '#22092C', 'dark_text' => '#FCE9E5', 'dark_link' => '#F05941'),
			'is_builtin'  => true,
		),
		'palette-11' => array(
			'label'       => __( 'Palette 11', 'fanspaysite' ),
			'source_likes'=> 19259,
			'colors'      => array('light_bg' => '#E7F1EE', 'light_text' => '#183D3D', 'light_link' => '#5C8374', 'dark_bg' => '#040D12', 'dark_text' => '#E7F1EE', 'dark_link' => '#93B1A6'),
			'is_builtin'  => true,
		),
		'palette-12' => array(
			'label'       => __( 'Palette 12', 'fanspaysite' ),
			'source_likes'=> 12918,
			'colors'      => array('light_bg' => '#FAF0E6', 'light_text' => '#5C5470', 'light_link' => '#B9B4C7', 'dark_bg' => '#352F44', 'dark_text' => '#FAF0E6', 'dark_link' => '#B9B4C7'),
			'is_builtin'  => true,
		),
		'palette-13' => array(
			'label'       => __( 'Palette 13', 'fanspaysite' ),
			'source_likes'=> 11313,
			'colors'      => array('light_bg' => '#EFE1D1', 'light_text' => '#3F2E3E', 'light_link' => '#A78295', 'dark_bg' => '#331D2C', 'dark_text' => '#EFE1D1', 'dark_link' => '#A78295'),
			'is_builtin'  => true,
		),
		'palette-14' => array(
			'label'       => __( 'Palette 14', 'fanspaysite' ),
			'source_likes'=> 34867,
			'colors'      => array('light_bg' => '#DDE6ED', 'light_text' => '#526D82', 'light_link' => '#27374D', 'dark_bg' => '#27374D', 'dark_text' => '#DDE6ED', 'dark_link' => '#9DB2BF'),
			'is_builtin'  => true,
		),
		'palette-15' => array(
			'label'       => __( 'Palette 15', 'fanspaysite' ),
			'source_likes'=> 13928,
			'colors'      => array('light_bg' => '#F1E8FF', 'light_text' => '#1D267D', 'light_link' => '#5C469C', 'dark_bg' => '#0C134F', 'dark_text' => '#F1E8FF', 'dark_link' => '#D4ADFC'),
			'is_builtin'  => true,
		),
		'palette-16' => array(
			'label'       => __( 'Palette 16', 'fanspaysite' ),
			'source_likes'=> 14701,
			'colors'      => array('light_bg' => '#E8F3FB', 'light_text' => '#19376D', 'light_link' => '#576CBC', 'dark_bg' => '#0B2447', 'dark_text' => '#E8F3FB', 'dark_link' => '#A5D7E8'),
			'is_builtin'  => true,
		),
		'palette-17' => array(
			'label'       => __( 'Palette 17', 'fanspaysite' ),
			'source_likes'=> 13318,
			'colors'      => array('light_bg' => '#E6F3F1', 'light_text' => '#2E4F4F', 'light_link' => '#0E8388', 'dark_bg' => '#2C3333', 'dark_text' => '#E6F3F1', 'dark_link' => '#0E8388'),
			'is_builtin'  => true,
		),
		'palette-18' => array(
			'label'       => __( 'Palette 18', 'fanspaysite' ),
			'source_likes'=> 14956,
			'colors'      => array('light_bg' => '#EEEAF8', 'light_text' => '#393053', 'light_link' => '#635985', 'dark_bg' => '#18122B', 'dark_text' => '#EEEAF8', 'dark_link' => '#635985'),
			'is_builtin'  => true,
		),
		'palette-19' => array(
			'label'       => __( 'Palette 19', 'fanspaysite' ),
			'source_likes'=> 21345,
			'colors'      => array('light_bg' => '#E6EFF7', 'light_text' => '#144272', 'light_link' => '#205295', 'dark_bg' => '#0A2647', 'dark_text' => '#E6EFF7', 'dark_link' => '#2C74B3'),
			'is_builtin'  => true,
		),
		'palette-20' => array(
			'label'       => __( 'Palette 20', 'fanspaysite' ),
			'source_likes'=> 27112,
			'colors'      => array('light_bg' => '#F1EEE7', 'light_text' => '#3F4E4F', 'light_link' => '#A27B5C', 'dark_bg' => '#2C3639', 'dark_text' => '#F1EEE7', 'dark_link' => '#A27B5C'),
			'is_builtin'  => true,
		),
	);

	foreach ( fanspaysite_get_builtin_skins() as $skin_key => $skin ) {
		if ( empty( $skin['colors'] ) || ! is_array( $skin['colors'] ) ) {
			continue;
		}

		$palettes[ 'skin-' . $skin_key ] = array(
			'label'       => $skin['name'] ?? $skin_key,
			'source_likes'=> 0,
			'colors'      => fanspaysite_normalize_palette_colors( $skin['colors'] ),
			'is_builtin'  => true,
			'is_skin_palette' => true,
		);
	}

	return apply_filters( 'fanspaysite_builtin_palettes', $palettes );
}

/**
 * Return saved custom palettes.
 *
 * @return array<string, array<string, mixed>>
 */
function fanspaysite_get_custom_palettes() {
	$palettes = get_option( 'fanspaysite_palettes', array() );
	return is_array( $palettes ) ? $palettes : array();
}

/**
 * Return all palettes.
 *
 * @return array<string, array<string, mixed>>
 */
function fanspaysite_get_all_palettes() {
	return array_merge( fanspaysite_get_builtin_palettes(), fanspaysite_get_custom_palettes() );
}

/**
 * Capture current six-color palette from theme mods.
 *
 * @return array<string, string>
 */
function fanspaysite_capture_current_palette() {
	return array(
		'light_bg'   => get_theme_mod( 'light_mode_background_color', '#ffffff' ),
		'light_text' => get_theme_mod( 'light_mode_text_color', '#333333' ),
		'light_link' => get_theme_mod( 'light_mode_link_color', '#77145d' ),
		'dark_bg'    => get_theme_mod( 'dark_mode_background_color', '#18122B' ),
		'dark_text'  => get_theme_mod( 'dark_mode_text_color', '#ffffff' ),
		'dark_link'  => get_theme_mod( 'dark_mode_link_color', '#d39ed8' ),
	);
}

/**
 * Normalize a palette color array.
 *
 * @param array<string, string> $colors Input colors.
 * @return array<string, string>
 */
function fanspaysite_normalize_palette_colors( $colors ) {
	$defaults = array(
		'light_bg'   => '#ffffff',
		'light_text' => '#333333',
		'light_link' => '#77145d',
		'dark_bg'    => '#18122B',
		'dark_text'  => '#ffffff',
		'dark_link'  => '#d39ed8',
	);

	$normalized = array();
	foreach ( $defaults as $key => $fallback ) {
		$value = isset( $colors[ $key ] ) ? sanitize_hex_color( $colors[ $key ] ) : '';
		$normalized[ $key ] = $value ? strtolower( $value ) : strtolower( $fallback );
	}

	return $normalized;
}

/**
 * Compare two palette arrays.
 *
 * @param array<string, string> $first First palette.
 * @param array<string, string> $second Second palette.
 * @return bool
 */
function fanspaysite_palette_colors_equal( $first, $second ) {
	return fanspaysite_normalize_palette_colors( $first ) === fanspaysite_normalize_palette_colors( $second );
}

/**
 * Get the key of the palette matching the current colors.
 *
 * @return string
 */
function fanspaysite_get_current_palette_key() {
	$current  = fanspaysite_capture_current_palette();
	$palettes = fanspaysite_get_all_palettes();

	foreach ( $palettes as $key => $palette ) {
		if ( ! empty( $palette['colors'] ) && fanspaysite_palette_colors_equal( $current, $palette['colors'] ) ) {
			return $key;
		}
	}

	return '';
}

/**
 * Apply a palette by key.
 *
 * @param string $palette_key Palette key.
 * @return bool
 */
function fanspaysite_apply_palette( $palette_key ) {
	$palettes = fanspaysite_get_all_palettes();
	if ( empty( $palettes[ $palette_key ]['colors'] ) ) {
		return false;
	}

	$colors = fanspaysite_normalize_palette_colors( $palettes[ $palette_key ]['colors'] );

	set_theme_mod( 'light_mode_background_color', $colors['light_bg'] );
	set_theme_mod( 'light_mode_text_color', $colors['light_text'] );
	set_theme_mod( 'light_mode_link_color', $colors['light_link'] );
	set_theme_mod( 'dark_mode_background_color', $colors['dark_bg'] );
	set_theme_mod( 'dark_mode_text_color', $colors['dark_text'] );
	set_theme_mod( 'dark_mode_link_color', $colors['dark_link'] );

	return true;
}

/**
 * Save the current colors as a custom palette.
 *
 * @return string|false Palette key on success, false on failure.
 */
function fanspaysite_save_current_palette() {
	$current_key = fanspaysite_get_current_palette_key();
	if ( '' !== $current_key ) {
		return false;
	}

	$custom_palettes = fanspaysite_get_custom_palettes();
	$next_index      = count( $custom_palettes ) + 1;
	$palette_key     = 'custom-palette-' . time();

	while ( isset( $custom_palettes[ $palette_key ] ) ) {
		$palette_key .= '-1';
	}

	$custom_palettes[ $palette_key ] = array(
		'label'      => sprintf( __( 'Custom %d', 'fanspaysite' ), $next_index ),
		'colors'     => fanspaysite_normalize_palette_colors( fanspaysite_capture_current_palette() ),
		'is_builtin' => false,
	);

	update_option( 'fanspaysite_palettes', $custom_palettes );

	return $palette_key;
}

/**
 * Delete a custom palette.
 *
 * @param string $palette_key Palette key.
 * @return bool
 */
function fanspaysite_delete_palette( $palette_key ) {
	$custom_palettes = fanspaysite_get_custom_palettes();
	if ( ! isset( $custom_palettes[ $palette_key ] ) ) {
		return false;
	}

	unset( $custom_palettes[ $palette_key ] );
	update_option( 'fanspaysite_palettes', $custom_palettes );

	return true;
}

/**
 * Capture current theme settings as a skin data array.
 */
function fanspaysite_capture_current_settings() {
	$settings = array(
		'layout'          => get_theme_mod('fanspaysite_layout', 'left-sidebar'),
		'burger_menu'     => get_theme_mod('fanspaysite_burger_menu', 'auto'),
		'menu_display'    => get_theme_mod('fanspaysite_menu_display_mode', 'auto'),
		'submenu_display' => get_theme_mod('fanspaysite_submenu_display_mode', 'auto'),
		'submenu_hover'   => get_theme_mod('fanspaysite_submenu_hover', 'auto'),
		'default_mode'    => get_theme_mod('fanspaysite_default_theme_mode', 'light'),
		'colors'          => array(
			'light_bg'   => get_theme_mod('light_mode_background_color', '#ffffff'),
			'light_text' => get_theme_mod('light_mode_text_color', '#333333'),
			'light_link' => get_theme_mod('light_mode_link_color', '#77145d'),
			'dark_bg'    => get_theme_mod('dark_mode_background_color', '#18122B'),
			'dark_text'  => get_theme_mod('dark_mode_text_color', '#ffffff'),
			'dark_link'  => get_theme_mod('dark_mode_link_color', '#d39ed8'),
		),
		'custom_css'      => get_theme_mod('fanspaysite_skin_custom_css', ''),
		// New v2.2 settings
		'sticky_header'   => get_theme_mod('fanspaysite_sticky_header', true),
		'content_width'   => get_theme_mod('fanspaysite_content_width', 'default'),
		'right_sidebar'   => fanspaysite_get_right_sidebar_mode(),
		'font_preset'     => get_theme_mod('fanspaysite_font_preset', 'system'),
		'footer_columns'  => get_theme_mod('fanspaysite_footer_columns', 1),
		'show_footer_menu' => get_theme_mod('fanspaysite_show_footer_menu', true),
		'archive_display' => get_theme_mod('fanspaysite_archive_display', 'classic'),
		'page_show_title' => get_theme_mod('fanspaysite_page_show_title', true),
		'page_title_alignment' => get_theme_mod('fanspaysite_page_title_alignment', 'left'),
		'page_title_size' => get_theme_mod('fanspaysite_page_title_size', 'normal'),
		'is_builtin'      => false,
	);

	return apply_filters( 'fanspaysite_capture_skin_settings', $settings );
}

/**
 * Apply a skin's settings to theme_mods.
 */
function fanspaysite_apply_skin($skin_key) {
	$skins = fanspaysite_get_all_skins();
	if (!isset($skins[$skin_key])) {
		return false;
	}

	$skin = $skins[$skin_key];

	set_theme_mod('fanspaysite_layout', $skin['layout']);
	set_theme_mod('fanspaysite_burger_menu', $skin['burger_menu'] ?? 'auto');
	set_theme_mod('fanspaysite_menu_display_mode', $skin['menu_display']);
	set_theme_mod('fanspaysite_submenu_display_mode', $skin['submenu_display'] ?? 'auto');
	set_theme_mod('fanspaysite_submenu_hover', $skin['submenu_hover'] ?? 'auto');
	set_theme_mod('fanspaysite_default_theme_mode', $skin['default_mode']);

	if (!empty($skin['colors'])) {
		set_theme_mod('light_mode_background_color', $skin['colors']['light_bg']);
		set_theme_mod('light_mode_text_color', $skin['colors']['light_text']);
		set_theme_mod('light_mode_link_color', $skin['colors']['light_link']);
		set_theme_mod('dark_mode_background_color', $skin['colors']['dark_bg']);
		set_theme_mod('dark_mode_text_color', $skin['colors']['dark_text']);
		set_theme_mod('dark_mode_link_color', $skin['colors']['dark_link']);
	}

	set_theme_mod('fanspaysite_skin_custom_css', $skin['custom_css'] ?? '');

	// New v2.2 settings (backward-compatible: use defaults when missing)
	set_theme_mod('fanspaysite_sticky_header', $skin['sticky_header'] ?? true);
	set_theme_mod('fanspaysite_content_width', $skin['content_width'] ?? 'default');
	set_theme_mod('fanspaysite_show_right_sidebar', $skin['right_sidebar'] ?? 'auto');
	set_theme_mod('fanspaysite_font_preset', $skin['font_preset'] ?? 'system');
	set_theme_mod('fanspaysite_footer_columns', $skin['footer_columns'] ?? 1);
	set_theme_mod('fanspaysite_show_footer_menu', $skin['show_footer_menu'] ?? true);
	set_theme_mod('fanspaysite_archive_display', $skin['archive_display'] ?? 'classic');
	set_theme_mod('fanspaysite_page_show_title', $skin['page_show_title'] ?? true);
	set_theme_mod('fanspaysite_page_title_alignment', $skin['page_title_alignment'] ?? 'left');
	set_theme_mod('fanspaysite_page_title_size', $skin['page_title_size'] ?? 'normal');

	update_option('fanspaysite_active_skin', $skin_key);
	do_action( 'fanspaysite_skin_applied', $skin_key, $skin );

	return true;
}

/**
 * Save current settings as a skin.
 */
function fanspaysite_save_skin($skin_key, $name, $description) {
	$custom_skins = get_option('fanspaysite_skins', array());
	$settings     = fanspaysite_capture_current_settings();

	$settings['name']        = sanitize_text_field($name);
	$settings['description'] = sanitize_textarea_field($description);
	$settings['is_builtin']  = false;

	$custom_skins[$skin_key] = $settings;
	update_option('fanspaysite_skins', $custom_skins);
	update_option('fanspaysite_active_skin', $skin_key);

	return true;
}

/**
 * Delete a custom skin.
 */
function fanspaysite_delete_skin($skin_key) {
	$builtin = fanspaysite_get_builtin_skins();
	if (isset($builtin[$skin_key])) {
		return false; // Cannot delete built-in skins
	}

	$custom_skins = get_option('fanspaysite_skins', array());
	if (isset($custom_skins[$skin_key])) {
		unset($custom_skins[$skin_key]);
		update_option('fanspaysite_skins', $custom_skins);

		// If active skin was deleted, revert to default
		if (get_option('fanspaysite_active_skin') === $skin_key) {
			fanspaysite_apply_skin('default');
		}
		return true;
	}
	return false;
}

/**
 * Handle form submissions on the skins page.
 */
function fanspaysite_handle_skins_actions() {
	if (!current_user_can('edit_theme_options')) {
		return;
	}

	// Save advanced settings.
	if (isset($_POST['fanspaysite_save_advanced_settings']) && check_admin_referer('fanspaysite_skins_action', 'fanspaysite_skins_nonce')) {
		update_option('fanspaysite_use_cdn_libraries', !empty($_POST['fanspaysite_use_cdn_libraries']));
		update_option('fanspaysite_admin_darkmode_enabled', !empty($_POST['fanspaysite_admin_darkmode_enabled']));
		update_option('fanspaysite_developer_mode', !empty($_POST['fanspaysite_developer_mode']));
		add_settings_error('fanspaysite_skins', 'advanced_saved', __('Advanced settings saved.', 'fanspaysite'), 'updated');
	}

	// Apply skin.
	if (isset($_POST['fanspaysite_apply_skin']) && check_admin_referer('fanspaysite_skins_action', 'fanspaysite_skins_nonce')) {
		$skin_key = sanitize_key($_POST['skin_key']);
		if (fanspaysite_apply_skin($skin_key)) {
			add_settings_error('fanspaysite_skins', 'skin_applied', __('Skin applied successfully.', 'fanspaysite'), 'updated');
		} else {
			add_settings_error('fanspaysite_skins', 'skin_error', __('Skin not found.', 'fanspaysite'), 'error');
		}
	}

	// Save current as skin.
	if (isset($_POST['fanspaysite_save_skin']) && check_admin_referer('fanspaysite_skins_action', 'fanspaysite_skins_nonce')) {
		$name        = sanitize_text_field($_POST['skin_name'] ?? '');
		$description = sanitize_textarea_field($_POST['skin_description'] ?? '');
		$skin_key    = sanitize_key($_POST['save_skin_key'] ?? '');

		if (empty($name)) {
			add_settings_error('fanspaysite_skins', 'skin_error', __('Skin name is required.', 'fanspaysite'), 'error');
		} else {
			if (empty($skin_key)) {
				$skin_key = sanitize_key(str_replace(' ', '-', strtolower($name)));
			}
			// Prevent overwriting built-in skins.
			$builtin = fanspaysite_get_builtin_skins();
			if (isset($builtin[$skin_key])) {
				$skin_key = 'custom-' . $skin_key;
			}
			fanspaysite_save_skin($skin_key, $name, $description);
			add_settings_error('fanspaysite_skins', 'skin_saved', __('Skin saved successfully.', 'fanspaysite'), 'updated');
		}
	}

	// Delete skin.
	if (isset($_POST['fanspaysite_delete_skin']) && check_admin_referer('fanspaysite_skins_action', 'fanspaysite_skins_nonce')) {
		$skin_key = sanitize_key($_POST['skin_key']);
		if (fanspaysite_delete_skin($skin_key)) {
			add_settings_error('fanspaysite_skins', 'skin_deleted', __('Skin deleted successfully.', 'fanspaysite'), 'updated');
		} else {
			add_settings_error('fanspaysite_skins', 'skin_error', __('Cannot delete this skin.', 'fanspaysite'), 'error');
		}
	}

	// Apply palette.
	if ( isset( $_POST['fanspaysite_apply_palette'] ) && check_admin_referer( 'fanspaysite_skins_action', 'fanspaysite_skins_nonce' ) ) {
		$palette_key = sanitize_key( $_POST['palette_key'] ?? '' );
		if ( fanspaysite_apply_palette( $palette_key ) ) {
			add_settings_error( 'fanspaysite_skins', 'palette_applied', __( 'Palette applied successfully.', 'fanspaysite' ), 'updated' );
		} else {
			add_settings_error( 'fanspaysite_skins', 'palette_error', __( 'Palette not found.', 'fanspaysite' ), 'error' );
		}
	}

	// Save current palette.
	if ( isset( $_POST['fanspaysite_save_palette'] ) && check_admin_referer( 'fanspaysite_skins_action', 'fanspaysite_skins_nonce' ) ) {
		if ( fanspaysite_save_current_palette() ) {
			add_settings_error( 'fanspaysite_skins', 'palette_saved', __( 'Current palette saved.', 'fanspaysite' ), 'updated' );
		} else {
			add_settings_error( 'fanspaysite_skins', 'palette_exists', __( 'Current colors already match an existing palette.', 'fanspaysite' ), 'error' );
		}
	}

	// Delete custom palette.
	if ( isset( $_POST['fanspaysite_delete_palette'] ) && check_admin_referer( 'fanspaysite_skins_action', 'fanspaysite_skins_nonce' ) ) {
		$palette_key = sanitize_key( $_POST['palette_key'] ?? '' );
		if ( fanspaysite_delete_palette( $palette_key ) ) {
			add_settings_error( 'fanspaysite_skins', 'palette_deleted', __( 'Palette deleted.', 'fanspaysite' ), 'updated' );
		} else {
			add_settings_error( 'fanspaysite_skins', 'palette_delete_error', __( 'Cannot delete this palette.', 'fanspaysite' ), 'error' );
		}
	}
}
add_action('admin_init', 'fanspaysite_handle_skins_actions');

/**
 * Output custom CSS from skin settings on the frontend.
 */
function fanspaysite_skin_custom_css() {
	$custom_css = get_theme_mod('fanspaysite_skin_custom_css', '');
	if (!empty($custom_css)) {
		echo '<style id="fanspaysite-skin-css">' . wp_strip_all_tags($custom_css) . '</style>';
	}
}
add_action('wp_head', 'fanspaysite_skin_custom_css', 20);

/**
 * Get the active tab for the FansPaysite admin page.
 *
 * @return string
 */
function fanspaysite_get_skins_page_tab() {
	$tab = sanitize_key($_GET['tab'] ?? 'skins');
	return in_array($tab, array('skins', 'palettes', 'advanced', 'integration'), true) ? $tab : 'skins';
}

/**
 * Get the public integration tab code examples.
 *
 * @return array<string, string>
 */
function fanspaysite_get_integration_examples() {
	return array(
		'css'        => <<<'CSS'
.my-plugin-panel {
	background: var(--fanspaysite-background-color, var(--background-color, #fff));
	color: var(--fanspaysite-text-color, var(--text-color, #333));
	border: 1px solid color-mix(in srgb, var(--fanspaysite-link-color, var(--link-color, #77145d)) 20%, transparent);
}

html[data-theme="dark"] .my-plugin-panel {
	box-shadow: 0 12px 32px rgba(0, 0, 0, 0.35);
}
CSS,
		'enqueue'    => <<<'PHP'
add_action( 'wp_enqueue_scripts', function() {
	if ( function_exists( 'fanspaysite_enqueue_fomantic_components' ) ) {
		fanspaysite_enqueue_fomantic_components(
			array( 'segment', 'form', 'message', 'button' ),
			array()
		);
	}
}, 20 );
PHP,
		'context'    => <<<'PHP'
$context = function_exists( 'fanspaysite_get_theme_integration_context' )
	? fanspaysite_get_theme_integration_context()
	: array();

$active_skin = $context['active_skin'] ?? 'default';
$layout      = $context['layout'] ?? 'left-sidebar';
$mode        = $context['theme_mode_preference'] ?? 'light';
PHP,
		'skins'      => <<<'PHP'
add_filter( 'fanspaysite_builtin_skins', function( $skins ) {
	$skins['my-plugin-midnight'] = array(
		'name'            => __( 'My Plugin Midnight', 'my-plugin' ),
		'description'     => __( 'Dark preset aligned with My Plugin screens.', 'my-plugin' ),
		'layout'          => 'top-bar',
		'burger_menu'     => 'auto',
		'menu_display'    => 'auto',
		'submenu_display' => 'auto',
		'submenu_hover'   => 'auto',
		'default_mode'    => 'dark',
		'archive_display' => 'classic',
		'colors'          => array(
			'light_bg'   => '#ffffff',
			'light_text' => '#1f2933',
			'light_link' => '#0f6cbd',
			'dark_bg'    => '#111827',
			'dark_text'  => '#f9fafb',
			'dark_link'  => '#60a5fa',
		),
		'custom_css'      => '',
		'is_builtin'      => true,
	);

	return $skins;
} );

add_action( 'fanspaysite_skin_applied', function( $skin_key, $skin ) {
	if ( 'my-plugin-midnight' === $skin_key ) {
		update_option( 'my_plugin_color_scheme', 'midnight' );
	}
}, 10, 2 );
PHP,
		'cards'      => <<<'PHP'
add_action( 'fanspaysite_post_card_actions', function( $post_id, $format, $mode ) {
	echo '<a class="ui tiny button" href="' . esc_url( get_permalink( $post_id ) ) . '#bookmark">';
	esc_html_e( 'Bookmark', 'my-plugin' );
	echo '</a>';
}, 10, 3 );
PHP,
	);
}

/**
 * Get plugins with known FansPaysite integrations.
 *
 * @return array[] Integrated plugin definitions.
 */
function fanspaysite_get_integrated_plugins() {
	$plugins = array(
		array(
			'name'           => __( 'VideoWhisper Light Cookie Consent', 'fanspaysite' ),
			'integration'    => __( 'Uses the theme palette, light/dark state, and shared Fomantic UI components for its consent controls.', 'fanspaysite' ),
			'plugin_files'   => array( 'videowhisper-light-cookie-consent/videowhisper-light-cookie-consent.php' ),
			'homepage_url'   => 'https://promptaur.com/wordpress/light-cookie-consent/',
			'repository_url' => 'https://wordpress.org/plugins/videowhisper-light-cookie-consent/',
		),
		array(
			'name'           => __( 'Contact Forms, Live Support, CRM, Video Messages', 'fanspaysite' ),
			'integration'    => __( 'Reuses shared Fomantic assets, follows the theme mode and color tokens, and extends archive cards.', 'fanspaysite' ),
			'plugin_files'   => array( 'live-support-tickets/live-support-tickets.php' ),
			'homepage_url'   => 'https://consult.videowhisper.com/',
			'repository_url' => 'https://wordpress.org/plugins/live-support-tickets/',
		),
		array(
			'name'           => __( 'MicroPayments/FansPaysite', 'fanspaysite' ),
			'integration'    => __( 'Synchronizes plugin interfaces with the current FansPaysite light, dark, or automatic mode.', 'fanspaysite' ),
			'plugin_files'   => array( 'paid-membership/paid-membership.php' ),
			'homepage_url'   => 'https://fanspaysite.com/',
			'repository_url' => 'https://wordpress.org/plugins/paid-membership/',
		),
		array(
			'name'           => __( 'Picture Gallery', 'fanspaysite' ),
			'integration'    => __( 'Uses the current FansPaysite mode for its frontend gallery and upload interfaces.', 'fanspaysite' ),
			'plugin_files'   => array( 'picture-gallery/picture-gallery.php' ),
			'repository_url' => 'https://wordpress.org/plugins/picture-gallery/',
		),
		array(
			'name'           => __( 'Paid Videochat Turnkey Site - HTML5 PPV Live Webcams', 'fanspaysite' ),
			'integration'    => __( 'Defers its dynamic interface mode to FansPaysite and follows theme changes in AJAX listings.', 'fanspaysite' ),
			'plugin_files'   => array( 'ppv-live-webcams/ppv-live-webcams.php' ),
			'homepage_url'   => 'https://paidvideochat.com/',
			'repository_url' => 'https://wordpress.org/plugins/ppv-live-webcams/',
		),
		array(
			'name'           => __( 'Broadcast Live Video', 'fanspaysite' ),
			'integration'    => __( 'Follows the resolved FansPaysite mode and live mode switches across channel, management, playback, and chat interfaces.', 'fanspaysite' ),
			'plugin_files'   => array( 'videowhisper-live-streaming-integration/videowhisper_streaming.php' ),
			'homepage_url'   => 'https://broadcastlivevideo.com/',
			'repository_url' => 'https://wordpress.org/plugins/videowhisper-live-streaming-integration/',
		),
		array(
			'name'           => __( 'Video Share VOD', 'fanspaysite' ),
			'integration'    => __( 'Uses the current FansPaysite mode for video listings and other dynamic frontend interfaces.', 'fanspaysite' ),
			'plugin_files'   => array( 'video-share-vod/video-share-vod.php' ),
			'homepage_url'   => 'https://videosharevod.com/',
			'repository_url' => 'https://wordpress.org/plugins/video-share-vod/',
		),
		array(
			'name'           => __( 'VideoWhisper Site Manager for ChatGPT, Claude, Codex', 'fanspaysite' ),
			'integration'    => __( 'Detects FansPaysite, exposes compatible settings, and styles its user connection screen for the theme.', 'fanspaysite' ),
			'plugin_files'   => array( 'videowhisper-site-manager/videowhisper-site-manager.php' ),
			'homepage_url'   => 'https://promptaur.com/wordpress/site-manager/',
			'repository_url' => 'https://wordpress.org/plugins/videowhisper-site-manager/',
		),
		array(
			'name'         => __( 'AI Site Manager Pro', 'fanspaysite' ),
			'integration'  => __( 'Adds FansPaysite menu icon support to AI-assisted menu inspection and updates.', 'fanspaysite' ),
			'plugin_files' => array( 'videowhisper-site-manager-pro/videowhisper-site-manager-pro.php' ),
			'homepage_url' => 'https://promptaur.com/wordpress/site-manager/',
		),
		array(
			'name'         => __( 'AI Site Manager Server', 'fanspaysite' ),
			'integration'  => __( 'Detects FansPaysite and applies the theme mode and compatible styling to its turnkey status interface.', 'fanspaysite' ),
			'plugin_files' => array( 'videowhisper-site-manager-server/videowhisper-site-manager-server.php' ),
			'homepage_url' => 'https://promptaur.com/wordpress/site-manager-server/',
		),
		array(
			'name'           => __( 'WooCommerce', 'fanspaysite' ),
			'integration'    => __( 'FansPaysite provides dedicated storefront, product, cart, and account compatibility.', 'fanspaysite' ),
			'plugin_files'   => array( 'woocommerce/woocommerce.php' ),
			'homepage_url'   => 'https://woocommerce.com/',
			'repository_url' => 'https://wordpress.org/plugins/woocommerce/',
		),
		array(
			'name'           => __( 'BuddyPress', 'fanspaysite' ),
			'integration'    => __( 'FansPaysite provides dedicated community, member, and activity compatibility.', 'fanspaysite' ),
			'plugin_files'   => array( 'buddypress/bp-loader.php' ),
			'homepage_url'   => 'https://buddypress.org/',
			'repository_url' => 'https://wordpress.org/plugins/buddypress/',
		),
	);

	/**
	 * Filters plugins displayed in the Integration tab catalog.
	 *
	 * Each item accepts name, integration, plugin_files, homepage_url, and
	 * repository_url values. A plugin is detected when one of its plugin_files
	 * entries is active for the current site or network.
	 *
	 * @param array[] $plugins Integrated plugin definitions.
	 */
	return apply_filters( 'fanspaysite_integrated_plugins', $plugins );
}

/**
 * Determine whether an integrated plugin is active for this site or network.
 *
 * @param string[] $plugin_files Candidate plugin basenames.
 * @return bool Whether one of the candidate files is active.
 */
function fanspaysite_is_integrated_plugin_active( $plugin_files ) {
	static $active_plugin_files = null;

	if ( null === $active_plugin_files ) {
		$active_plugin_files = array_fill_keys( (array) get_option( 'active_plugins', array() ), true );

		if ( is_multisite() ) {
			$network_plugin_files = array_keys( (array) get_site_option( 'active_sitewide_plugins', array() ) );
			$active_plugin_files  = array_merge( $active_plugin_files, array_fill_keys( $network_plugin_files, true ) );
		}
	}

	foreach ( (array) $plugin_files as $plugin_file ) {
		if ( isset( $active_plugin_files[ $plugin_file ] ) ) {
			return true;
		}
	}

	return false;
}

/**
 * Render the Integration tab for plugin developers.
 *
 * @return void
 */
function fanspaysite_render_integration_tab() {
	$context            = function_exists( 'fanspaysite_get_theme_integration_context' ) ? fanspaysite_get_theme_integration_context() : array();
	$colors             = function_exists( 'fanspaysite_get_theme_color_tokens' ) ? fanspaysite_get_theme_color_tokens() : array();
	$examples           = fanspaysite_get_integration_examples();
	$integrated_plugins = fanspaysite_get_integrated_plugins();
	?>
	<div class="fps-save-section fps-integration-section" style="max-width:none;">
		<h2><?php esc_html_e( 'Plugin Integration Guide', 'fanspaysite' ); ?></h2>
		<nav class="fps-current-info fps-integration-toc" aria-label="<?php esc_attr_e( 'Integration guide contents', 'fanspaysite' ); ?>">
			<p><strong><?php esc_html_e( 'Contents', 'fanspaysite' ); ?></strong></p>
			<ul>
				<li><a href="#fanspaysite-integration-context"><?php esc_html_e( 'Current Context', 'fanspaysite' ); ?></a></li>
				<li><a href="#fanspaysite-integrated-plugins"><?php esc_html_e( 'Integrated Plugins', 'fanspaysite' ); ?></a></li>
				<li><a href="#fanspaysite-frontend-signals"><?php esc_html_e( 'Frontend Signals', 'fanspaysite' ); ?></a></li>
				<li><a href="#fanspaysite-css-tokens"><?php esc_html_e( 'CSS Tokens', 'fanspaysite' ); ?></a></li>
				<li><a href="#fanspaysite-php-helpers"><?php esc_html_e( 'PHP Helpers', 'fanspaysite' ); ?></a></li>
				<li><a href="#fanspaysite-hooks"><?php esc_html_e( 'Hooks', 'fanspaysite' ); ?></a></li>
				<li><a href="#fanspaysite-examples"><?php esc_html_e( 'Examples', 'fanspaysite' ); ?></a></li>
			</ul>
		</nav>
		<p><?php esc_html_e( 'Use these selectors, helpers, and hooks when building plugin screens that should feel native inside FansPaysite.', 'fanspaysite' ); ?></p>

		<h3 id="fanspaysite-integration-context"><?php esc_html_e( 'Current Context', 'fanspaysite' ); ?></h3>
		<div class="fps-current-info">
			<p><strong><?php esc_html_e( 'Current active skin:', 'fanspaysite' ); ?></strong> <code><?php echo esc_html( $context['active_skin'] ?? 'default' ); ?></code></p>
			<p><strong><?php esc_html_e( 'Current layout:', 'fanspaysite' ); ?></strong> <code><?php echo esc_html( $context['layout'] ?? 'left-sidebar' ); ?></code></p>
			<p><strong><?php esc_html_e( 'Current mode preference:', 'fanspaysite' ); ?></strong> <code><?php echo esc_html( $context['theme_mode_preference'] ?? 'light' ); ?></code></p>
			<p><strong><?php esc_html_e( 'Shared Fomantic handles:', 'fanspaysite' ); ?></strong> <code><?php echo esc_html( implode( ', ', array_merge( $context['fomantic_styles'] ?? array(), $context['fomantic_scripts'] ?? array() ) ) ); ?></code></p>
		</div>

		<h3 id="fanspaysite-integrated-plugins"><?php esc_html_e( 'Integrated Plugins', 'fanspaysite' ); ?></h3>
		<p><?php esc_html_e( 'These plugins contain FansPaysite-aware behavior, or are supported by dedicated compatibility code in the theme. Detection means that the plugin is active for this site or network.', 'fanspaysite' ); ?></p>
		<table class="widefat striped fps-integrated-plugins-table">
			<thead>
				<tr>
					<th><?php esc_html_e( 'Plugin', 'fanspaysite' ); ?></th>
					<th><?php esc_html_e( 'FansPaysite Integration', 'fanspaysite' ); ?></th>
					<th><?php esc_html_e( 'Links', 'fanspaysite' ); ?></th>
					<th><?php esc_html_e( 'Detected', 'fanspaysite' ); ?></th>
				</tr>
			</thead>
			<tbody>
				<?php foreach ( $integrated_plugins as $plugin ) : ?>
					<?php $is_detected = fanspaysite_is_integrated_plugin_active( $plugin['plugin_files'] ?? array() ); ?>
					<tr>
						<td><strong><?php echo esc_html( $plugin['name'] ?? '' ); ?></strong></td>
						<td><?php echo esc_html( $plugin['integration'] ?? '' ); ?></td>
						<td class="fps-integration-links">
							<?php if ( ! empty( $plugin['homepage_url'] ) ) : ?>
								<a href="<?php echo esc_url( $plugin['homepage_url'] ); ?>" target="_blank" rel="noopener noreferrer"><?php esc_html_e( 'Homepage', 'fanspaysite' ); ?></a>
							<?php endif; ?>
							<?php if ( ! empty( $plugin['repository_url'] ) ) : ?>
								<a href="<?php echo esc_url( $plugin['repository_url'] ); ?>" target="_blank" rel="noopener noreferrer"><?php esc_html_e( 'WordPress.org', 'fanspaysite' ); ?></a>
							<?php endif; ?>
						</td>
						<td>
							<?php if ( $is_detected ) : ?>
								<span class="fps-integration-detected"><span aria-hidden="true">&#10003;</span> <?php esc_html_e( 'Active', 'fanspaysite' ); ?></span>
							<?php else : ?>
								<span class="fps-integration-not-detected"><span aria-hidden="true">&mdash;</span> <?php esc_html_e( 'Not active', 'fanspaysite' ); ?></span>
							<?php endif; ?>
						</td>
					</tr>
				<?php endforeach; ?>
			</tbody>
		</table>

		<h3 id="fanspaysite-frontend-signals"><?php esc_html_e( 'Frontend Signals', 'fanspaysite' ); ?></h3>
		<ul style="list-style:disc; padding-left:20px;">
			<li><code>html[data-theme="light"]</code> and <code>html[data-theme="dark"]</code> are set very early to prevent flash of incorrect colors.</li>
			<li><code>body[data-theme]</code>, <code>body.inverted</code>, and <code>.ui.inverted</code> are applied once the page is ready so standard Fomantic markup adapts automatically.</li>
			<li><code>vws-theme-change</code> is dispatched on <code>document</code> after initial mode resolution and every visitor mode switch. Its detail includes <code>preference</code> and resolved <code>light</code> or <code>dark</code> values.</li>
			<li><code>fanspaysite-skin-{skin-key}</code>, <code>layout-{left-sidebar|top-bar}</code>, <code>menu-display-*</code>, and <code>submenu-display-*</code> are added to <code>body_class()</code>.</li>
		</ul>

		<h3 id="fanspaysite-css-tokens"><?php esc_html_e( 'CSS Tokens', 'fanspaysite' ); ?></h3>
		<table class="widefat striped">
			<thead>
				<tr>
					<th><?php esc_html_e( 'Token', 'fanspaysite' ); ?></th>
					<th><?php esc_html_e( 'Purpose', 'fanspaysite' ); ?></th>
					<th><?php esc_html_e( 'Current Value', 'fanspaysite' ); ?></th>
				</tr>
			</thead>
			<tbody>
				<tr><td><code>--fanspaysite-background-color</code></td><td><?php esc_html_e( 'Resolved current background color', 'fanspaysite' ); ?></td><td><code><?php echo esc_html( $colors['light']['background'] ?? '#ffffff' ); ?> / <?php echo esc_html( $colors['dark']['background'] ?? '#333333' ); ?></code></td></tr>
				<tr><td><code>--fanspaysite-text-color</code></td><td><?php esc_html_e( 'Resolved current text color', 'fanspaysite' ); ?></td><td><code><?php echo esc_html( $colors['light']['text'] ?? '#333333' ); ?> / <?php echo esc_html( $colors['dark']['text'] ?? '#ffffff' ); ?></code></td></tr>
				<tr><td><code>--fanspaysite-link-color</code></td><td><?php esc_html_e( 'Resolved current accent/link color', 'fanspaysite' ); ?></td><td><code><?php echo esc_html( $colors['light']['link'] ?? '#77145d' ); ?> / <?php echo esc_html( $colors['dark']['link'] ?? '#d39ed8' ); ?></code></td></tr>
				<tr><td><code>--text-color</code>, <code>--background-color</code>, <code>--link-color</code></td><td><?php esc_html_e( 'Legacy generic aliases used by the theme styles', 'fanspaysite' ); ?></td><td><code><?php esc_html_e( 'Available in both modes', 'fanspaysite' ); ?></code></td></tr>
				<tr><td><code>--fanspaysite-light-*</code> and <code>--fanspaysite-dark-*</code></td><td><?php esc_html_e( 'Explicit light and dark palette values for advanced plugin styling', 'fanspaysite' ); ?></td><td><code><?php esc_html_e( 'Background / text / link', 'fanspaysite' ); ?></code></td></tr>
			</tbody>
		</table>

		<h3 id="fanspaysite-php-helpers"><?php esc_html_e( 'PHP Helpers', 'fanspaysite' ); ?></h3>
		<table class="widefat striped">
			<thead>
				<tr>
					<th><?php esc_html_e( 'Helper', 'fanspaysite' ); ?></th>
					<th><?php esc_html_e( 'Purpose', 'fanspaysite' ); ?></th>
				</tr>
			</thead>
			<tbody>
				<tr><td><code>fanspaysite_get_current_theme_mode()</code></td><td><?php esc_html_e( 'Returns the visitor preference: light, dark, or auto.', 'fanspaysite' ); ?></td></tr>
				<tr><td><code>fanspaysite_get_theme_color_tokens()</code></td><td><?php esc_html_e( 'Returns the light and dark palette arrays used by the theme.', 'fanspaysite' ); ?></td></tr>
				<tr><td><code>fanspaysite_get_theme_integration_context()</code></td><td><?php esc_html_e( 'Returns current skin, layout, menu modes, palette tokens, and shared asset handles.', 'fanspaysite' ); ?></td></tr>
				<tr><td><code>fanspaysite_enqueue_fomantic_components()</code></td><td><?php esc_html_e( 'Lets a plugin reuse the theme resolver for bundled Fomantic components instead of shipping duplicates.', 'fanspaysite' ); ?></td></tr>
			</tbody>
		</table>

		<h3 id="fanspaysite-hooks"><?php esc_html_e( 'Hooks', 'fanspaysite' ); ?></h3>
		<table class="widefat striped">
			<thead>
				<tr>
					<th><?php esc_html_e( 'Hook', 'fanspaysite' ); ?></th>
					<th><?php esc_html_e( 'Type', 'fanspaysite' ); ?></th>
					<th><?php esc_html_e( 'Purpose', 'fanspaysite' ); ?></th>
				</tr>
			</thead>
			<tbody>
				<tr><td><code>fanspaysite_fomantic_css_components</code></td><td><?php esc_html_e( 'Filter', 'fanspaysite' ); ?></td><td><?php esc_html_e( 'Extend the default shared frontend Fomantic CSS component list.', 'fanspaysite' ); ?></td></tr>
				<tr><td><code>fanspaysite_fomantic_js_components</code></td><td><?php esc_html_e( 'Filter', 'fanspaysite' ); ?></td><td><?php esc_html_e( 'Extend the default shared frontend Fomantic JS component list.', 'fanspaysite' ); ?></td></tr>
				<tr><td><code>fanspaysite_theme_color_tokens</code></td><td><?php esc_html_e( 'Filter', 'fanspaysite' ); ?></td><td><?php esc_html_e( 'Adjust exported light/dark palette tokens before they are exposed to PHP and CSS.', 'fanspaysite' ); ?></td></tr>
				<tr><td><code>fanspaysite_theme_integration_context</code></td><td><?php esc_html_e( 'Filter', 'fanspaysite' ); ?></td><td><?php esc_html_e( 'Extend the context array returned to plugins.', 'fanspaysite' ); ?></td></tr>
				<tr><td><code>fanspaysite_integrated_plugins</code></td><td><?php esc_html_e( 'Filter', 'fanspaysite' ); ?></td><td><?php esc_html_e( 'Add or adjust entries in the integrated plugin catalog shown above.', 'fanspaysite' ); ?></td></tr>
				<tr><td><code>fanspaysite_builtin_skins</code></td><td><?php esc_html_e( 'Filter', 'fanspaysite' ); ?></td><td><?php esc_html_e( 'Register plugin-aware built-in skins on the admin page.', 'fanspaysite' ); ?></td></tr>
				<tr><td><code>fanspaysite_all_skins</code></td><td><?php esc_html_e( 'Filter', 'fanspaysite' ); ?></td><td><?php esc_html_e( 'Inspect or extend the combined built-in + custom skin list.', 'fanspaysite' ); ?></td></tr>
				<tr><td><code>fanspaysite_capture_skin_settings</code></td><td><?php esc_html_e( 'Filter', 'fanspaysite' ); ?></td><td><?php esc_html_e( 'Add plugin settings when a user saves the current skin.', 'fanspaysite' ); ?></td></tr>
				<tr><td><code>fanspaysite_skin_applied</code></td><td><?php esc_html_e( 'Action', 'fanspaysite' ); ?></td><td><?php esc_html_e( 'React when a FansPaysite skin is applied, for example by syncing a plugin palette.', 'fanspaysite' ); ?></td></tr>
				<tr><td><code>fanspaysite_integration_tab_content</code></td><td><?php esc_html_e( 'Action', 'fanspaysite' ); ?></td><td><?php esc_html_e( 'Append plugin-specific notes to this Integration tab.', 'fanspaysite' ); ?></td></tr>
				<tr><td><code>fanspaysite_breadcrumb</code></td><td><?php esc_html_e( 'Action', 'fanspaysite' ); ?></td><td><?php esc_html_e( 'Render breadcrumbs before the main content area.', 'fanspaysite' ); ?></td></tr>
				<tr><td><code>fanspaysite_post_card_before</code>, <code>fanspaysite_post_card_meta</code>, <code>fanspaysite_post_card_actions</code>, <code>fanspaysite_post_card_after</code></td><td><?php esc_html_e( 'Action', 'fanspaysite' ); ?></td><td><?php esc_html_e( 'Extend archive cards in classic, fullpage, and boxes modes.', 'fanspaysite' ); ?></td></tr>
			</tbody>
		</table>

		<h3 id="fanspaysite-examples"><?php esc_html_e( 'Examples', 'fanspaysite' ); ?></h3>
		<p><strong><?php esc_html_e( '1. Dark/light aware CSS', 'fanspaysite' ); ?></strong></p>
		<pre style="background:#f6f7f7; padding:16px; overflow:auto;"><?php echo esc_html( $examples['css'] ); ?></pre>

		<p><strong><?php esc_html_e( '2. Reuse shared Fomantic components', 'fanspaysite' ); ?></strong></p>
		<pre style="background:#f6f7f7; padding:16px; overflow:auto;"><?php echo esc_html( $examples['enqueue'] ); ?></pre>

		<p><strong><?php esc_html_e( '3. Read the current theme context', 'fanspaysite' ); ?></strong></p>
		<pre style="background:#f6f7f7; padding:16px; overflow:auto;"><?php echo esc_html( $examples['context'] ); ?></pre>

		<p><strong><?php esc_html_e( '4. Add or react to skins', 'fanspaysite' ); ?></strong></p>
		<pre style="background:#f6f7f7; padding:16px; overflow:auto;"><?php echo esc_html( $examples['skins'] ); ?></pre>

		<p><strong><?php esc_html_e( '5. Add actions to archive cards', 'fanspaysite' ); ?></strong></p>
		<pre style="background:#f6f7f7; padding:16px; overflow:auto;"><?php echo esc_html( $examples['cards'] ); ?></pre>

		<?php do_action( 'fanspaysite_integration_tab_content', $context ); ?>
	</div>
	<?php
}

/**
 * Render the skins admin page.
 */
function fanspaysite_skins_page_html() {
	if (!current_user_can('edit_theme_options')) {
		return;
	}

	$skins             = fanspaysite_get_all_skins();
	$palettes          = fanspaysite_get_all_palettes();
	$active_skin       = get_option('fanspaysite_active_skin', 'default');
	$current_palette   = fanspaysite_capture_current_palette();
	$current_palette_key = fanspaysite_get_current_palette_key();
	$current_tab       = fanspaysite_get_skins_page_tab();
	$use_cdn_libraries = fanspaysite_use_cdn_libraries();
	$skins_url         = admin_url('themes.php?page=fanspaysite');
	$palettes_url      = admin_url('themes.php?page=fanspaysite&tab=palettes');
	$advanced_url      = admin_url('themes.php?page=fanspaysite&tab=advanced');
	$integration_url   = admin_url('themes.php?page=fanspaysite&tab=integration');

	settings_errors('fanspaysite_skins');
	?>
	<div class="wrap">
		<h1><?php esc_html_e('FansPaysite Theme Settings', 'fanspaysite'); ?></h1>
		<p><?php esc_html_e('Manage skins, color palettes, and advanced asset-loading settings for the FansPaysite theme.', 'fanspaysite'); ?></p>

		<h2 class="nav-tab-wrapper">
			<a href="<?php echo esc_url($skins_url); ?>" class="nav-tab <?php echo ('skins' === $current_tab) ? 'nav-tab-active' : ''; ?>"><?php esc_html_e('Skins', 'fanspaysite'); ?></a>
			<a href="<?php echo esc_url($palettes_url); ?>" class="nav-tab <?php echo ('palettes' === $current_tab) ? 'nav-tab-active' : ''; ?>"><?php esc_html_e('Palettes', 'fanspaysite'); ?></a>
			<a href="<?php echo esc_url($advanced_url); ?>" class="nav-tab <?php echo ('advanced' === $current_tab) ? 'nav-tab-active' : ''; ?>"><?php esc_html_e('Advanced', 'fanspaysite'); ?></a>
			<a href="<?php echo esc_url($integration_url); ?>" class="nav-tab <?php echo ('integration' === $current_tab) ? 'nav-tab-active' : ''; ?>"><?php esc_html_e('Integration', 'fanspaysite'); ?></a>
		</h2>

		<style>
			.fps-skins-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(320px, 1fr)); gap: 20px; margin: 20px 0; }
			.fps-skin-card { background: #fff; border: 1px solid #c3c4c7; border-radius: 4px; padding: 20px; position: relative; }
			.fps-skin-card.active { border-color: #2271b1; border-width: 2px; }
			.fps-skin-card h3 { margin: 0 0 8px; font-size: 16px; }
			.fps-skin-card .description { color: #646970; margin-bottom: 12px; }
			.fps-skin-card .skin-meta { font-size: 12px; color: #8c8f94; margin-bottom: 12px; }
			.fps-skin-card .skin-meta span { display: inline-block; margin-right: 12px; }
			.fps-skin-card .skin-colors { display: flex; gap: 4px; margin-bottom: 12px; }
			.fps-skin-color { width: 24px; height: 24px; border-radius: 3px; border: 1px solid #ddd; }
			.fps-skin-card .actions { display: flex; gap: 8px; }
			.fps-skin-badge { display: inline-block; background: #2271b1; color: #fff; font-size: 11px; padding: 2px 8px; border-radius: 3px; margin-left: 8px; }
			.fps-skin-badge.builtin { background: #8c8f94; }
			.fps-save-section { background: #fff; border: 1px solid #c3c4c7; border-radius: 4px; padding: 20px; margin-top: 30px; max-width: 720px; }
			.fps-save-section h2 { margin-top: 0; }
			.fps-save-section label { display: block; margin-bottom: 4px; font-weight: 600; }
			.fps-save-section input[type="text"],
			.fps-save-section textarea { width: 100%; margin-bottom: 12px; }
			.fps-save-section textarea { height: 60px; }
			.fps-current-info { background: #f0f6fc; border: 1px solid #c3c4c7; border-radius: 4px; padding: 16px; margin: 20px 0; }
			.fps-current-info p:last-child { margin-bottom: 0; }
			.fps-status-pill { display: inline-block; padding: 2px 10px; border-radius: 999px; font-size: 12px; font-weight: 600; }
			.fps-status-pill.local { background: #e7f5ea; color: #116329; }
			.fps-status-pill.cdn { background: #e8f0fe; color: #174ea6; }
			.fps-integration-toc ul { display: flex; flex-wrap: wrap; gap: 6px 24px; margin-bottom: 0; }
			.fps-integration-toc li { margin: 0; }
			.fps-integrated-plugins-table th,
			.fps-integrated-plugins-table td { vertical-align: top; }
			.fps-integrated-plugins-table th:first-child { width: 22%; }
			.fps-integrated-plugins-table th:nth-child(3) { width: 15%; }
			.fps-integrated-plugins-table th:last-child { width: 10%; }
			.fps-integration-links a { display: block; margin-bottom: 4px; }
			.fps-integration-detected { color: #008a20; font-weight: 600; white-space: nowrap; }
			.fps-integration-not-detected { color: #646970; white-space: nowrap; }
			.fps-advanced-section .description { max-width: 64em; }
			.fps-advanced-toggle { margin: 18px 0 10px; }
			.fps-advanced-toggle label { display: flex; gap: 10px; align-items: flex-start; font-weight: 600; }
			.fps-advanced-toggle input { margin-top: 2px; }
			.fps-palettes-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(220px, 1fr)); gap: 14px; margin: 20px 0; }
			.fps-palette-card { background: #fff; border: 1px solid #c3c4c7; border-radius: 4px; padding: 14px; }
			.fps-palette-card.active { border-color: #2271b1; box-shadow: inset 0 0 0 1px #2271b1; }
			.fps-palette-swatches { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 4px; margin-bottom: 10px; }
			.fps-palette-swatch { min-height: 42px; border-radius: 4px; border: 1px solid rgba(0,0,0,.08); position: relative; overflow: hidden; }
			.fps-palette-swatch span { position: absolute; inset: auto 4px 3px 4px; font-size: 10px; line-height: 1.1; color: rgba(255,255,255,.92); text-shadow: 0 1px 2px rgba(0,0,0,.45); }
			.fps-palette-swatch span code { display: block; margin-top: 2px; padding: 0; font-size: 9px; line-height: 1.1; color: inherit; background: transparent; }
			.fps-palette-actions { display: flex; flex-wrap: wrap; gap: 6px; }
			.fps-palette-actions form { margin: 0; }
			.fps-palette-save { max-width: none; }
		</style>

		<?php if ('palettes' === $current_tab) : ?>
			<div class="fps-current-info">
				<p><strong><?php esc_html_e( 'Current Colors', 'fanspaysite' ); ?></strong></p>
				<div class="fps-palette-swatches" style="max-width:360px;">
					<div class="fps-palette-swatch" style="background:<?php echo esc_attr( $current_palette['light_bg'] ); ?>;"><span style="color:<?php echo esc_attr( $current_palette['light_text'] ); ?>; text-shadow:none;"><?php esc_html_e( 'Light BG', 'fanspaysite' ); ?><code><?php echo esc_html( strtoupper( $current_palette['light_bg'] ) ); ?></code></span></div>
					<div class="fps-palette-swatch" style="background:<?php echo esc_attr( $current_palette['light_text'] ); ?>;"><span><?php esc_html_e( 'Light Text', 'fanspaysite' ); ?><code><?php echo esc_html( strtoupper( $current_palette['light_text'] ) ); ?></code></span></div>
					<div class="fps-palette-swatch" style="background:<?php echo esc_attr( $current_palette['light_link'] ); ?>;"><span><?php esc_html_e( 'Light Link', 'fanspaysite' ); ?><code><?php echo esc_html( strtoupper( $current_palette['light_link'] ) ); ?></code></span></div>
					<div class="fps-palette-swatch" style="background:<?php echo esc_attr( $current_palette['dark_bg'] ); ?>;"><span style="color:<?php echo esc_attr( $current_palette['dark_text'] ); ?>; text-shadow:none;"><?php esc_html_e( 'Dark BG', 'fanspaysite' ); ?><code><?php echo esc_html( strtoupper( $current_palette['dark_bg'] ) ); ?></code></span></div>
					<div class="fps-palette-swatch" style="background:<?php echo esc_attr( $current_palette['dark_text'] ); ?>;"><span><?php esc_html_e( 'Dark Text', 'fanspaysite' ); ?><code><?php echo esc_html( strtoupper( $current_palette['dark_text'] ) ); ?></code></span></div>
					<div class="fps-palette-swatch" style="background:<?php echo esc_attr( $current_palette['dark_link'] ); ?>;"><span><?php esc_html_e( 'Dark Link', 'fanspaysite' ); ?><code><?php echo esc_html( strtoupper( $current_palette['dark_link'] ) ); ?></code></span></div>
				</div>
				<p>
					<?php if ( '' !== $current_palette_key ) : ?>
						<?php esc_html_e( 'Matches:', 'fanspaysite' ); ?> <code><?php echo esc_html( $palettes[ $current_palette_key ]['label'] ?? $current_palette_key ); ?></code>
					<?php else : ?>
						<?php esc_html_e( 'These colors do not match a saved palette yet.', 'fanspaysite' ); ?>
					<?php endif; ?>
				</p>
			</div>

			<div class="fps-save-section fps-palette-save">
				<h2><?php esc_html_e( 'Palette Library', 'fanspaysite' ); ?></h2>
				<p><?php esc_html_e( 'Apply a six-color palette to the theme core colors. Presets below are inspired by high-like dark palettes from Color Hunt.', 'fanspaysite' ); ?></p>
				<?php if ( '' === $current_palette_key ) : ?>
					<form method="post" style="margin-bottom:14px;">
						<?php wp_nonce_field('fanspaysite_skins_action', 'fanspaysite_skins_nonce'); ?>
						<button type="submit" name="fanspaysite_save_palette" class="button button-primary"><?php esc_html_e( 'Save Current Palette', 'fanspaysite' ); ?></button>
					</form>
				<?php endif; ?>

				<div class="fps-palettes-grid">
					<?php foreach ( $palettes as $key => $palette ) : ?>
						<?php $colors = fanspaysite_normalize_palette_colors( $palette['colors'] ?? array() ); ?>
						<div class="fps-palette-card <?php echo ( $key === $current_palette_key ) ? 'active' : ''; ?>">
							<div class="fps-palette-swatches">
								<div class="fps-palette-swatch" style="background:<?php echo esc_attr( $colors['light_bg'] ); ?>;"><span style="color:<?php echo esc_attr( $colors['light_text'] ); ?>; text-shadow:none;"><?php esc_html_e( 'L BG', 'fanspaysite' ); ?><code><?php echo esc_html( strtoupper( $colors['light_bg'] ) ); ?></code></span></div>
								<div class="fps-palette-swatch" style="background:<?php echo esc_attr( $colors['light_text'] ); ?>;"><span><?php esc_html_e( 'L TXT', 'fanspaysite' ); ?><code><?php echo esc_html( strtoupper( $colors['light_text'] ) ); ?></code></span></div>
								<div class="fps-palette-swatch" style="background:<?php echo esc_attr( $colors['light_link'] ); ?>;"><span><?php esc_html_e( 'L LINK', 'fanspaysite' ); ?><code><?php echo esc_html( strtoupper( $colors['light_link'] ) ); ?></code></span></div>
								<div class="fps-palette-swatch" style="background:<?php echo esc_attr( $colors['dark_bg'] ); ?>;"><span style="color:<?php echo esc_attr( $colors['dark_text'] ); ?>; text-shadow:none;"><?php esc_html_e( 'D BG', 'fanspaysite' ); ?><code><?php echo esc_html( strtoupper( $colors['dark_bg'] ) ); ?></code></span></div>
								<div class="fps-palette-swatch" style="background:<?php echo esc_attr( $colors['dark_text'] ); ?>;"><span><?php esc_html_e( 'D TXT', 'fanspaysite' ); ?><code><?php echo esc_html( strtoupper( $colors['dark_text'] ) ); ?></code></span></div>
								<div class="fps-palette-swatch" style="background:<?php echo esc_attr( $colors['dark_link'] ); ?>;"><span><?php esc_html_e( 'D LINK', 'fanspaysite' ); ?><code><?php echo esc_html( strtoupper( $colors['dark_link'] ) ); ?></code></span></div>
							</div>
							<?php if ( $key === $current_palette_key ) : ?>
								<div style="margin-bottom:10px;"><span class="fps-skin-badge"><?php esc_html_e( 'Current', 'fanspaysite' ); ?></span></div>
							<?php endif; ?>
							<div class="fps-palette-actions">
								<?php if ( $key !== $current_palette_key ) : ?>
									<form method="post">
										<?php wp_nonce_field('fanspaysite_skins_action', 'fanspaysite_skins_nonce'); ?>
										<input type="hidden" name="palette_key" value="<?php echo esc_attr( $key ); ?>">
										<button type="submit" name="fanspaysite_apply_palette" class="button button-secondary"><?php esc_html_e( 'Apply', 'fanspaysite' ); ?></button>
									</form>
								<?php endif; ?>
								<?php if ( empty( $palette['is_builtin'] ) ) : ?>
									<form method="post" onsubmit="return confirm('<?php esc_attr_e( 'Delete this palette?', 'fanspaysite' ); ?>');">
										<?php wp_nonce_field('fanspaysite_skins_action', 'fanspaysite_skins_nonce'); ?>
										<input type="hidden" name="palette_key" value="<?php echo esc_attr( $key ); ?>">
										<button type="submit" name="fanspaysite_delete_palette" class="button button-link-delete"><?php esc_html_e( 'Delete', 'fanspaysite' ); ?></button>
									</form>
								<?php endif; ?>
							</div>
						</div>
					<?php endforeach; ?>
				</div>
			</div>
			<?php elseif ('advanced' === $current_tab) : ?>
				<?php
				$admin_darkmode_enabled = (bool) get_option('fanspaysite_admin_darkmode_enabled', false);
				$developer_mode_enabled = (bool) get_option('fanspaysite_developer_mode', false);
				?>
				<div class="fps-save-section fps-advanced-section">
					<h2><?php esc_html_e('Admin Dark Mode', 'fanspaysite'); ?></h2>
					<p><?php esc_html_e('When enabled, a ☀/☾/⚙ icon appears in the admin bar. Click it to switch between Light, Dark, and System modes — the choice is saved immediately and adjusts the admin panel styling.', 'fanspaysite'); ?></p>

				<form method="post">
					<?php wp_nonce_field('fanspaysite_skins_action', 'fanspaysite_skins_nonce'); ?>
					<div class="fps-advanced-toggle">
						<label for="fanspaysite_admin_darkmode_enabled">
							<input type="checkbox" id="fanspaysite_admin_darkmode_enabled" name="fanspaysite_admin_darkmode_enabled" value="1" <?php checked($admin_darkmode_enabled); ?>>
							<span><?php esc_html_e('Enable Admin Dark Mode control', 'fanspaysite'); ?></span>
						</label>
						</div>
						<p class="description"><?php esc_html_e('Disabled by default. Once enabled, use the admin bar icon to pick Light / Dark / System. The mode is saved per-site and applies to the admin content area, tabs, panels, tables, inputs, and links.', 'fanspaysite'); ?></p>
						<input type="hidden" name="fanspaysite_use_cdn_libraries" value="<?php echo $use_cdn_libraries ? '1' : ''; ?>">
						<input type="hidden" name="fanspaysite_developer_mode" value="<?php echo $developer_mode_enabled ? '1' : ''; ?>">
						<button type="submit" name="fanspaysite_save_advanced_settings" class="button button-primary" style="margin-top:10px;"><?php esc_html_e('Save', 'fanspaysite'); ?></button>
					</form>
				</div>

				<div class="fps-save-section fps-advanced-section" style="margin-top:20px;">
					<h2><?php esc_html_e('Developer Mode', 'fanspaysite'); ?></h2>
					<p><?php esc_html_e('Enable frontend console diagnostics for theme mode resolution, Fomantic UI inverted-state capture, and runtime re-syncs caused by dynamic content or plugin class changes.', 'fanspaysite'); ?></p>

					<form method="post">
						<?php wp_nonce_field('fanspaysite_skins_action', 'fanspaysite_skins_nonce'); ?>
						<input type="hidden" name="fanspaysite_admin_darkmode_enabled" value="<?php echo $admin_darkmode_enabled ? '1' : ''; ?>">
						<input type="hidden" name="fanspaysite_use_cdn_libraries" value="<?php echo $use_cdn_libraries ? '1' : ''; ?>">
						<div class="fps-advanced-toggle">
							<label for="fanspaysite_developer_mode">
								<input type="checkbox" id="fanspaysite_developer_mode" name="fanspaysite_developer_mode" value="1" <?php checked($developer_mode_enabled); ?>>
								<span><?php esc_html_e('Enable Developer Mode console diagnostics', 'fanspaysite'); ?></span>
							</label>
						</div>
						<p class="description"><?php esc_html_e('Keep disabled on production unless actively troubleshooting. When enabled, messages are prefixed with “FansPaysite:” in the browser console.', 'fanspaysite'); ?></p>
						<button type="submit" name="fanspaysite_save_advanced_settings" class="button button-primary"><?php esc_html_e('Save Developer Mode', 'fanspaysite'); ?></button>
					</form>
				</div>

				<div class="fps-save-section fps-advanced-section" style="margin-top:20px;">
					<h2><?php esc_html_e('Library Delivery', 'fanspaysite'); ?></h2>
					<p><?php esc_html_e('By default, FansPaysite loads bundled library files from the theme itself. This keeps the WordPress.org-compliant local setup intact and avoids introducing third-party frontend dependencies unless you explicitly opt in.', 'fanspaysite'); ?></p>

				<div class="fps-current-info">
					<p>
						<strong><?php esc_html_e('Current Mode:', 'fanspaysite'); ?></strong>
						<span class="fps-status-pill <?php echo $use_cdn_libraries ? 'cdn' : 'local'; ?>"><?php echo esc_html($use_cdn_libraries ? __('CDN libraries enabled', 'fanspaysite') : __('Local bundled libraries', 'fanspaysite')); ?></span>
					</p>
					<p><?php esc_html_e('Affected libraries: Fomantic UI components, Font Awesome, and the Font Awesome icon picker used on Appearance > Menus.', 'fanspaysite'); ?></p>
				</div>

					<form method="post">
						<?php wp_nonce_field('fanspaysite_skins_action', 'fanspaysite_skins_nonce'); ?>
						<input type="hidden" name="fanspaysite_admin_darkmode_enabled" value="<?php echo $admin_darkmode_enabled ? '1' : ''; ?>">
						<input type="hidden" name="fanspaysite_developer_mode" value="<?php echo $developer_mode_enabled ? '1' : ''; ?>">
						<div class="fps-advanced-toggle">
							<label for="fanspaysite_use_cdn_libraries">
								<input type="checkbox" id="fanspaysite_use_cdn_libraries" name="fanspaysite_use_cdn_libraries" value="1" <?php checked($use_cdn_libraries); ?>>
							<span><?php esc_html_e('Load bundled libraries from CDN instead of local theme files', 'fanspaysite'); ?></span>
						</label>
					</div>
					<p class="description"><?php esc_html_e('Disabled by default. Enabling this makes requests to cdn.jsdelivr.net, which may improve load speed when those files are already cached in the visitor browser.', 'fanspaysite'); ?></p>
					<p class="description"><?php esc_html_e('Keep this disabled if you want the most self-contained setup, need stricter privacy/CSP rules, or want to avoid any third-party asset dependency.', 'fanspaysite'); ?></p>
					<button type="submit" name="fanspaysite_save_advanced_settings" class="button button-primary"><?php esc_html_e('Save Advanced Settings', 'fanspaysite'); ?></button>
				</form>
			</div>
		<?php elseif ('integration' === $current_tab) : ?>
			<?php fanspaysite_render_integration_tab(); ?>
		<?php else : ?>
			<div class="fps-current-info">
				<strong><?php esc_html_e('Current Settings:', 'fanspaysite'); ?></strong>
				<?php
				$current_layout       = get_theme_mod('fanspaysite_layout', 'left-sidebar');
				$current_burger       = get_theme_mod('fanspaysite_burger_menu', 'auto');
				$current_menu         = get_theme_mod('fanspaysite_menu_display_mode', 'auto');
				$current_submenu      = get_theme_mod('fanspaysite_submenu_display_mode', 'auto');
				$current_hover        = get_theme_mod('fanspaysite_submenu_hover', 'auto');
				$current_mode         = get_theme_mod('fanspaysite_default_theme_mode', 'light');
				?>
				<span><?php printf(__('Layout: %s', 'fanspaysite'), '<code>' . esc_html($current_layout) . '</code>'); ?></span> |
				<span><?php printf(__('Burger: %s', 'fanspaysite'), '<code>' . esc_html($current_burger) . '</code>'); ?></span> |
				<span><?php printf(__('Main Menu: %s', 'fanspaysite'), '<code>' . esc_html($current_menu) . '</code>'); ?></span> |
				<span><?php printf(__('Submenus: %s', 'fanspaysite'), '<code>' . esc_html($current_submenu) . '</code>'); ?></span> |
				<span><?php printf(__('Hover: %s', 'fanspaysite'), '<code>' . esc_html($current_hover) . '</code>'); ?></span> |
				<span><?php printf(__('Mode: %s', 'fanspaysite'), '<code>' . esc_html($current_mode) . '</code>'); ?></span> |
				<span><?php printf(__('Active Skin: %s', 'fanspaysite'), '<code>' . esc_html($active_skin) . '</code>'); ?></span>
			</div>

			<h2><?php esc_html_e('Available Skins', 'fanspaysite'); ?></h2>
			<div class="fps-skins-grid">
				<?php foreach ($skins as $key => $skin) : ?>
					<div class="fps-skin-card <?php echo ($key === $active_skin) ? 'active' : ''; ?>">
						<h3>
							<?php echo esc_html($skin['name']); ?>
							<?php if ($key === $active_skin) : ?>
								<span class="fps-skin-badge"><?php esc_html_e('Active', 'fanspaysite'); ?></span>
							<?php endif; ?>
							<?php if (!empty($skin['is_builtin'])) : ?>
								<span class="fps-skin-badge builtin"><?php esc_html_e('Built-in', 'fanspaysite'); ?></span>
							<?php endif; ?>
						</h3>
						<div class="description"><?php echo esc_html($skin['description'] ?? ''); ?></div>
						<div class="skin-meta">
							<span><?php printf(__('Layout: %s', 'fanspaysite'), esc_html($skin['layout'])); ?></span>
							<span><?php printf(__('Burger: %s', 'fanspaysite'), esc_html($skin['burger_menu'] ?? 'auto')); ?></span>
							<span><?php printf(__('Menu: %s', 'fanspaysite'), esc_html($skin['menu_display'])); ?></span>
							<span><?php printf(__('Submenus: %s', 'fanspaysite'), esc_html($skin['submenu_display'] ?? 'auto')); ?></span>
							<span><?php printf(__('Hover: %s', 'fanspaysite'), esc_html($skin['submenu_hover'] ?? 'auto')); ?></span>
							<span><?php printf(__('Mode: %s', 'fanspaysite'), esc_html($skin['default_mode'])); ?></span>
						</div>
						<?php if (!empty($skin['colors'])) : ?>
							<div class="skin-colors">
								<div class="fps-skin-color" style="background:<?php echo esc_attr($skin['colors']['light_bg']); ?>;" title="Light BG"></div>
								<div class="fps-skin-color" style="background:<?php echo esc_attr($skin['colors']['light_text']); ?>;" title="Light Text"></div>
								<div class="fps-skin-color" style="background:<?php echo esc_attr($skin['colors']['light_link']); ?>;" title="Light Link"></div>
								<div class="fps-skin-color" style="background:<?php echo esc_attr($skin['colors']['dark_bg']); ?>;" title="Dark BG"></div>
								<div class="fps-skin-color" style="background:<?php echo esc_attr($skin['colors']['dark_text']); ?>;" title="Dark Text"></div>
								<div class="fps-skin-color" style="background:<?php echo esc_attr($skin['colors']['dark_link']); ?>;" title="Dark Link"></div>
							</div>
						<?php endif; ?>
						<div class="actions">
							<?php if ($key !== $active_skin) : ?>
								<form method="post" style="display:inline;">
									<?php wp_nonce_field('fanspaysite_skins_action', 'fanspaysite_skins_nonce'); ?>
									<input type="hidden" name="skin_key" value="<?php echo esc_attr($key); ?>">
									<button type="submit" name="fanspaysite_apply_skin" class="button button-primary"><?php esc_html_e('Apply', 'fanspaysite'); ?></button>
								</form>
							<?php endif; ?>
							<?php if (empty($skin['is_builtin'])) : ?>
								<form method="post" style="display:inline;" onsubmit="return confirm('<?php esc_attr_e('Delete this skin?', 'fanspaysite'); ?>');">
									<?php wp_nonce_field('fanspaysite_skins_action', 'fanspaysite_skins_nonce'); ?>
									<input type="hidden" name="skin_key" value="<?php echo esc_attr($key); ?>">
									<button type="submit" name="fanspaysite_delete_skin" class="button button-link-delete"><?php esc_html_e('Delete', 'fanspaysite'); ?></button>
								</form>
							<?php endif; ?>
						</div>
					</div>
				<?php endforeach; ?>
			</div>

			<div class="fps-save-section">
				<h2><?php esc_html_e('Save Current Settings as Skin', 'fanspaysite'); ?></h2>
				<p><?php esc_html_e('Capture your current layout, menu mode, theme mode, and color settings as a reusable skin.', 'fanspaysite'); ?></p>
				<form method="post">
					<?php wp_nonce_field('fanspaysite_skins_action', 'fanspaysite_skins_nonce'); ?>
					<label for="skin_name"><?php esc_html_e('Skin Name', 'fanspaysite'); ?></label>
					<input type="text" id="skin_name" name="skin_name" required placeholder="<?php esc_attr_e('My Custom Skin', 'fanspaysite'); ?>">

					<label for="skin_description"><?php esc_html_e('Description', 'fanspaysite'); ?></label>
					<textarea id="skin_description" name="skin_description" placeholder="<?php esc_attr_e('Brief description of this skin configuration...', 'fanspaysite'); ?>"></textarea>

					<label for="save_skin_key"><?php esc_html_e('Skin Key (optional, auto-generated from name)', 'fanspaysite'); ?></label>
					<input type="text" id="save_skin_key" name="save_skin_key" placeholder="<?php esc_attr_e('my-custom-skin', 'fanspaysite'); ?>" pattern="[a-z0-9\-]*">

					<p class="description"><?php esc_html_e('Use an existing key to overwrite that skin. Leave empty to auto-generate.', 'fanspaysite'); ?></p>

					<button type="submit" name="fanspaysite_save_skin" class="button button-primary" style="margin-top:8px;"><?php esc_html_e('Save Current Settings as Skin', 'fanspaysite'); ?></button>
				</form>
			</div>
		<?php endif; ?>
	</div>
	<?php
}

// ============================================================
// Admin Dark Mode — admin bar, CSS, JS, AJAX
// ============================================================

/**
 * Whether admin dark mode is enabled (opt-in, default off).
 *
 * @return bool
 */
function fanspaysite_is_admin_darkmode_enabled() {
	return (bool) get_option('fanspaysite_admin_darkmode_enabled', false);
}

/**
 * Return the current admin dark mode setting (light/dark/system).
 * Defaults to 'system' when not yet set.
 *
 * @return string 'light'|'dark'|'system'
 */
function fanspaysite_get_admin_darkmode() {
	$mode = get_option('fanspaysite_admin_darkmode', 'system');
	return in_array($mode, array('light', 'dark', 'system'), true) ? $mode : 'system';
}

/**
 * Add the saved admin color mode to the body classes before wp-admin renders.
 *
 * The CSS already loads in admin_head; adding the dark class here avoids the
 * light-mode flash previously caused by waiting for admin_footer JavaScript.
 *
 * @param string $classes Existing admin body classes.
 * @return string
 */
function fanspaysite_admin_darkmode_body_class($classes) {
	if (!fanspaysite_is_admin_darkmode_enabled() || !current_user_can('manage_options')) {
		return $classes;
	}

	$mode     = fanspaysite_get_admin_darkmode();
	$classes .= ' fps-admin-darkmode-enabled fps-admin-mode-' . sanitize_html_class($mode);

	if ('dark' === $mode) {
		$classes .= ' fps-admin-dark';
	} elseif ('system' === $mode) {
		$classes .= ' fps-admin-system';
	}

	return $classes;
}
add_filter('admin_body_class', 'fanspaysite_admin_darkmode_body_class');

/**
 * Add admin dark mode toggle to the admin bar (right side, before account menu).
 */
function fanspaysite_admin_bar_darkmode($wp_admin_bar) {
	if (!is_admin_bar_showing() || !fanspaysite_is_admin_darkmode_enabled()) {
		return;
	}
	if (!current_user_can('manage_options')) {
		return;
	}

	$mode = fanspaysite_get_admin_darkmode();

	$icons = array(
		'light'  => '&#9728;', // ☀ sun
		'dark'   => '&#9790;', // ☾ crescent moon
		'system' => '&#9881;', // ⚙ gear
	);
	$labels = array(
		'light'  => __('Light', 'fanspaysite'),
		'dark'   => __('Dark', 'fanspaysite'),
		'system' => __('System', 'fanspaysite'),
	);
	$icon  = $icons[ $mode ];
	$label = $labels[ $mode ];

	$wp_admin_bar->add_node(array(
		'id'     => 'fps-admin-darkmode',
		'title'  => '<span class="fps-adm-icon" aria-hidden="true">' . $icon . '</span>'
		           . '<span class="fps-adm-label screen-reader-text">' . esc_html__('Admin Color Mode: ', 'fanspaysite') . esc_html($label) . '</span>',
		'parent' => 'top-secondary',
		'href'   => false,
		'meta'   => array(
			'class'   => 'menupop fps-adm-wrap',
			'title'   => esc_attr__('Admin Color Mode', 'fanspaysite'),
			'tabindex' => 0,
		),
	));

	foreach ($icons as $mode_key => $mode_icon) {
		$active = ($mode_key === $mode) ? ' fps-adm-active' : '';
		$wp_admin_bar->add_node(array(
			'id'     => 'fps-admin-dm-' . $mode_key,
			'title'  => '<span class="fps-adm-opt-icon" aria-hidden="true">' . $mode_icon . '</span> ' . esc_html($labels[$mode_key]),
			'parent' => 'fps-admin-darkmode',
			'href'   => '#',
			'meta'   => array(
				'class'     => 'fps-adm-option' . $active,
				'tabindex'  => 0,
				'data-mode' => $mode_key,
			),
		));
	}
}
add_action('admin_bar_menu', 'fanspaysite_admin_bar_darkmode', 200);

/**
 * Output admin dark mode CSS in <head> of every admin page.
 * Only active when the feature is enabled in Advanced settings.
 * Always emits body.fps-admin-dark rules so JS class toggling works for any
 * mode switch without a page reload.
 */
function fanspaysite_admin_darkmode_styles() {
	if (!is_admin_bar_showing() || !current_user_can('manage_options')) {
		return;
	}
	if (!fanspaysite_is_admin_darkmode_enabled()) {
		return;
	}
	?>
	<style id="fps-admin-darkmode-css">
	/* FansPaysite Admin Bar: darkmode toggle button */
	#wpadminbar #wp-admin-bar-fps-admin-darkmode > .ab-item {
		font-size: 18px;
		line-height: 32px;
		padding: 0 8px;
		cursor: pointer;
	}
	#wpadminbar #wp-admin-bar-fps-admin-darkmode .fps-adm-icon {
		font-style: normal;
		line-height: 1;
	}
	#wpadminbar .fps-adm-option.fps-adm-active > .ab-item {
		font-weight: 700;
		color: #72aee6 !important;
	}
	#wpadminbar .fps-adm-opt-icon { font-style: normal; margin-right: 4px; }

	/* ---- Dark mode styles: applied via body.fps-admin-dark (added by JS) ---- */
	body.fps-admin-dark { background: #1a1a1a !important; color: #e0e0e0 !important; color-scheme: dark; }
	body.fps-admin-dark #wpcontent,
	body.fps-admin-dark #wpbody-content,
	body.fps-admin-dark #wpbody { background: #1a1a1a !important; }
	body.fps-admin-dark #wpadminbar { background: #111 !important; }
	body.fps-admin-dark #wpadminbar .ab-item,
	body.fps-admin-dark #wpadminbar a.ab-item,
	body.fps-admin-dark #wpadminbar > #wp-toolbar > ul > li > .ab-item { color: #ccc !important; }
	body.fps-admin-dark #wpadminbar #wp-admin-bar-site-name > .ab-item:before { color: #ccc; }
	body.fps-admin-dark #adminmenu a,
	body.fps-admin-dark #adminmenu .wp-submenu a,
	body.fps-admin-dark #adminmenu .wp-menu-name,
	body.fps-admin-dark #adminmenu div.wp-menu-image:before { color: #fff !important; }

	/* Main wrap */
	body.fps-admin-dark .wrap { color: #e0e0e0; }
	body.fps-admin-dark .wrap h1,
	body.fps-admin-dark .wrap h2,
	body.fps-admin-dark .wrap h3 { color: #f0f0f0; }

	/* Nav tabs */
	body.fps-admin-dark .nav-tab-wrapper,
	body.fps-admin-dark .wp-filter { border-bottom-color: #444 !important; background: transparent !important; }
	body.fps-admin-dark .nav-tab { background: #2a2a2a !important; border-color: #444 !important; color: #bbb !important; }
	body.fps-admin-dark .nav-tab:hover { background: #333 !important; color: #eee !important; }
	body.fps-admin-dark .nav-tab-active { background: #1a1a1a !important; border-bottom-color: #1a1a1a !important; color: #fff !important; }

	/* Postboxes / fps panels / skin cards */
	body.fps-admin-dark .postbox,
	body.fps-admin-dark .stuffbox,
	body.fps-admin-dark .fps-save-section,
	body.fps-admin-dark .fps-skin-card,
	body.fps-admin-dark .fps-current-info { background: #252525 !important; border-color: #444 !important; color: #e0e0e0 !important; }
	body.fps-admin-dark .postbox .hndle,
	body.fps-admin-dark .postbox .handle-actions { border-bottom-color: #444 !important; }
	body.fps-admin-dark .postbox h2,
	body.fps-admin-dark .postbox h3,
	body.fps-admin-dark .fps-save-section h2,
	body.fps-admin-dark .fps-skin-card h3 { color: #f0f0f0 !important; }

	/* Tables */
	body.fps-admin-dark .widefat,
	body.fps-admin-dark .wp-list-table { border-color: #444 !important; background: #252525 !important; }
	body.fps-admin-dark .widefat th,
	body.fps-admin-dark .widefat thead td,
	body.fps-admin-dark .wp-list-table th { background: #2e2e2e !important; color: #e0e0e0 !important; border-bottom-color: #444 !important; }
	body.fps-admin-dark .widefat td,
	body.fps-admin-dark .wp-list-table td { color: #ccc !important; border-bottom-color: #3a3a3a !important; }
	body.fps-admin-dark .widefat .alternate td,
	body.fps-admin-dark .wp-list-table .alternate td { background: #2a2a2a !important; }
	body.fps-admin-dark .widefat tr:hover td { background: #333 !important; }
	body.fps-admin-dark .widefat.striped > tbody > tr:nth-child(odd) { background: #2a2a2a !important; }
	body.fps-admin-dark .widefat.striped > tbody > tr:nth-child(even) { background: #252525 !important; }
	body.fps-admin-dark .wp-list-table.comments .column-comment,
	body.fps-admin-dark .wp-list-table.comments .column-comment p,
	body.fps-admin-dark .wp-list-table.comments .column-comment .submitted-on { color: #e0e0e0 !important; }

	/* Inputs, selects, textareas */
	body.fps-admin-dark input[type="text"],
	body.fps-admin-dark input[type="email"],
	body.fps-admin-dark input[type="url"],
	body.fps-admin-dark input[type="password"],
	body.fps-admin-dark input[type="number"],
	body.fps-admin-dark input[type="search"],
	body.fps-admin-dark select,
	body.fps-admin-dark textarea { background: #2e2e2e !important; border-color: #555 !important; color: #e0e0e0 !important; }
	body.fps-admin-dark input[type="text"]:focus,
	body.fps-admin-dark select:focus,
	body.fps-admin-dark textarea:focus { border-color: #72aee6 !important; box-shadow: 0 0 0 1px #72aee6 !important; }
	body.fps-admin-dark input[type="checkbox"],
	body.fps-admin-dark input[type="radio"] { accent-color: #72aee6; }

	/* Labels and descriptions */
	body.fps-admin-dark label { color: #ddd !important; }
	body.fps-admin-dark .description,
	body.fps-admin-dark p.description { color: #aaa !important; }

	/* Buttons */
	body.fps-admin-dark .button { background: #2e2e2e !important; border-color: #555 !important; color: #ddd !important; }
	body.fps-admin-dark .button:hover { background: #3a3a3a !important; border-color: #777 !important; color: #fff !important; }
	body.fps-admin-dark .button-primary { background: #2271b1 !important; border-color: #2271b1 !important; color: #fff !important; }
	body.fps-admin-dark .button-primary:hover { background: #135e96 !important; border-color: #135e96 !important; }
	body.fps-admin-dark .button-link-delete { color: #f86368 !important; }

	/* Links */
	body.fps-admin-dark a { color: #72aee6 !important; }
	body.fps-admin-dark a:hover { color: #93c4f5 !important; }

	/* Pagination */
	body.fps-admin-dark .tablenav .tablenav-pages a,
	body.fps-admin-dark .tablenav-pages a.button { background: #2e2e2e !important; border-color: #555 !important; color: #72aee6 !important; }
	body.fps-admin-dark .tablenav-pages span.current { background: #3a3a3a !important; border-color: #555 !important; color: #e0e0e0 !important; }
	body.fps-admin-dark .tablenav .displaying-num { color: #aaa !important; }

	/* Admin notices */
	body.fps-admin-dark .notice,
	body.fps-admin-dark .updated,
	body.fps-admin-dark div.error { background: #2a2a2a !important; border-left-color: #72aee6 !important; color: #e0e0e0 !important; }
	body.fps-admin-dark .notice-success,
	body.fps-admin-dark .updated { border-left-color: #68de7c !important; }
	body.fps-admin-dark .notice-error,
	body.fps-admin-dark div.error { border-left-color: #f86368 !important; }
	body.fps-admin-dark .notice-warning { border-left-color: #dba617 !important; }

	/* Code blocks */
	body.fps-admin-dark pre { background: #111 !important; color: #ccc !important; border-color: #333 !important; }
	body.fps-admin-dark code { background: #333 !important; color: #e0e0e0 !important; }

	/* Server-rendered system mode: let CSS resolve OS preference before footer JS runs. */
	@media (prefers-color-scheme: dark) {
		body.fps-admin-system { background: #1a1a1a !important; color: #e0e0e0 !important; color-scheme: dark; }
		body.fps-admin-system #wpcontent,
		body.fps-admin-system #wpbody-content,
		body.fps-admin-system #wpbody { background: #1a1a1a !important; }
		body.fps-admin-system #wpadminbar { background: #111 !important; }
		body.fps-admin-system #wpadminbar .ab-item,
		body.fps-admin-system #wpadminbar a.ab-item,
		body.fps-admin-system #wpadminbar > #wp-toolbar > ul > li > .ab-item { color: #ccc !important; }
		body.fps-admin-system #wpadminbar #wp-admin-bar-site-name > .ab-item:before { color: #ccc; }
		body.fps-admin-system #adminmenu a,
		body.fps-admin-system #adminmenu .wp-submenu a,
		body.fps-admin-system #adminmenu .wp-menu-name,
		body.fps-admin-system #adminmenu div.wp-menu-image:before { color: #fff !important; }

		body.fps-admin-system .wrap { color: #e0e0e0; }
		body.fps-admin-system .wrap h1,
		body.fps-admin-system .wrap h2,
		body.fps-admin-system .wrap h3 { color: #f0f0f0; }

		body.fps-admin-system .nav-tab-wrapper,
		body.fps-admin-system .wp-filter { border-bottom-color: #444 !important; background: transparent !important; }
		body.fps-admin-system .nav-tab { background: #2a2a2a !important; border-color: #444 !important; color: #bbb !important; }
		body.fps-admin-system .nav-tab:hover { background: #333 !important; color: #eee !important; }
		body.fps-admin-system .nav-tab-active { background: #1a1a1a !important; border-bottom-color: #1a1a1a !important; color: #fff !important; }

		body.fps-admin-system .postbox,
		body.fps-admin-system .stuffbox,
		body.fps-admin-system .fps-save-section,
		body.fps-admin-system .fps-skin-card,
		body.fps-admin-system .fps-current-info { background: #252525 !important; border-color: #444 !important; color: #e0e0e0 !important; }
		body.fps-admin-system .postbox .hndle,
		body.fps-admin-system .postbox .handle-actions { border-bottom-color: #444 !important; }
		body.fps-admin-system .postbox h2,
		body.fps-admin-system .postbox h3,
		body.fps-admin-system .fps-save-section h2,
		body.fps-admin-system .fps-skin-card h3 { color: #f0f0f0 !important; }

		body.fps-admin-system .widefat,
		body.fps-admin-system .wp-list-table { border-color: #444 !important; background: #252525 !important; }
		body.fps-admin-system .widefat th,
		body.fps-admin-system .widefat thead td,
		body.fps-admin-system .wp-list-table th { background: #2e2e2e !important; color: #e0e0e0 !important; border-bottom-color: #444 !important; }
		body.fps-admin-system .widefat td,
		body.fps-admin-system .wp-list-table td { color: #ccc !important; border-bottom-color: #3a3a3a !important; }
		body.fps-admin-system .widefat .alternate td,
		body.fps-admin-system .wp-list-table .alternate td { background: #2a2a2a !important; }
		body.fps-admin-system .widefat tr:hover td { background: #333 !important; }
		body.fps-admin-system .widefat.striped > tbody > tr:nth-child(odd) { background: #2a2a2a !important; }
		body.fps-admin-system .widefat.striped > tbody > tr:nth-child(even) { background: #252525 !important; }
		body.fps-admin-system .wp-list-table.comments .column-comment,
		body.fps-admin-system .wp-list-table.comments .column-comment p,
		body.fps-admin-system .wp-list-table.comments .column-comment .submitted-on { color: #e0e0e0 !important; }

		body.fps-admin-system input[type="text"],
		body.fps-admin-system input[type="email"],
		body.fps-admin-system input[type="url"],
		body.fps-admin-system input[type="password"],
		body.fps-admin-system input[type="number"],
		body.fps-admin-system input[type="search"],
		body.fps-admin-system select,
		body.fps-admin-system textarea { background: #2e2e2e !important; border-color: #555 !important; color: #e0e0e0 !important; }
		body.fps-admin-system input[type="text"]:focus,
		body.fps-admin-system select:focus,
		body.fps-admin-system textarea:focus { border-color: #72aee6 !important; box-shadow: 0 0 0 1px #72aee6 !important; }
		body.fps-admin-system input[type="checkbox"],
		body.fps-admin-system input[type="radio"] { accent-color: #72aee6; }

		body.fps-admin-system label { color: #ddd !important; }
		body.fps-admin-system .description,
		body.fps-admin-system p.description { color: #aaa !important; }

		body.fps-admin-system .button { background: #2e2e2e !important; border-color: #555 !important; color: #ddd !important; }
		body.fps-admin-system .button:hover { background: #3a3a3a !important; border-color: #777 !important; color: #fff !important; }
		body.fps-admin-system .button-primary { background: #2271b1 !important; border-color: #2271b1 !important; color: #fff !important; }
		body.fps-admin-system .button-primary:hover { background: #135e96 !important; border-color: #135e96 !important; }
		body.fps-admin-system .button-link-delete { color: #f86368 !important; }

		body.fps-admin-system a { color: #72aee6 !important; }
		body.fps-admin-system a:hover { color: #93c4f5 !important; }

		body.fps-admin-system .tablenav .tablenav-pages a,
		body.fps-admin-system .tablenav-pages a.button { background: #2e2e2e !important; border-color: #555 !important; color: #72aee6 !important; }
		body.fps-admin-system .tablenav-pages span.current { background: #3a3a3a !important; border-color: #555 !important; color: #e0e0e0 !important; }
		body.fps-admin-system .tablenav .displaying-num { color: #aaa !important; }

		body.fps-admin-system .notice,
		body.fps-admin-system .updated,
		body.fps-admin-system div.error { background: #2a2a2a !important; border-left-color: #72aee6 !important; color: #e0e0e0 !important; }
		body.fps-admin-system .notice-success,
		body.fps-admin-system .updated { border-left-color: #68de7c !important; }
		body.fps-admin-system .notice-error,
		body.fps-admin-system div.error { border-left-color: #f86368 !important; }
		body.fps-admin-system .notice-warning { border-left-color: #dba617 !important; }

		body.fps-admin-system pre { background: #111 !important; color: #ccc !important; border-color: #333 !important; }
		body.fps-admin-system code { background: #333 !important; color: #e0e0e0 !important; }
	}
	</style>
	<?php
}
add_action('admin_head', 'fanspaysite_admin_darkmode_styles');

/**
 * Inject inline JS in admin footer to:
 * - Apply `fps-admin-dark` body class on load (for dark/system modes)
 * - Wire up admin bar dropdown clicks → AJAX save → instant class toggle
 */
function fanspaysite_admin_darkmode_scripts() {
	if (!is_admin_bar_showing() || !current_user_can('manage_options')) {
		return;
	}
	if (!fanspaysite_is_admin_darkmode_enabled()) {
		return;
	}

	$mode  = fanspaysite_get_admin_darkmode();
	$nonce = wp_create_nonce('fps_admin_darkmode_nonce');
	?>
	<script id="fps-admin-darkmode-js">
	(function() {
		var currentMode = <?php echo wp_json_encode($mode); ?>;
		var ajaxUrl     = <?php echo wp_json_encode(admin_url('admin-ajax.php')); ?>;
		var nonce       = <?php echo wp_json_encode($nonce); ?>;

		function applyAdminDark(mode) {
			var isDark = (mode === 'dark') ||
				(mode === 'system' && window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches);

			document.body.classList.remove('fps-admin-mode-light', 'fps-admin-mode-dark', 'fps-admin-mode-system', 'fps-admin-system');
			document.body.classList.add('fps-admin-mode-' + mode);
			if (mode === 'system') {
				document.body.classList.add('fps-admin-system');
			}
			document.body.classList.toggle('fps-admin-dark', isDark);
		}

		// Apply on load
		applyAdminDark(currentMode);

		// Watch system preference changes (only relevant when mode === 'system')
		if (window.matchMedia) {
			window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', function() {
				if (currentMode === 'system') {
					applyAdminDark('system');
				}
			});
		}

		// Update admin bar icon to reflect chosen mode
		function updateBarIcon(mode) {
			var icons = { light: '&#9728;', dark: '&#9790;', system: '&#9881;' };
			var iconEl = document.querySelector('#wp-admin-bar-fps-admin-darkmode .fps-adm-icon');
			if (iconEl) { iconEl.innerHTML = icons[mode] || icons.system; }

			// Mark active item
			var opts = document.querySelectorAll('#wp-admin-bar-fps-admin-darkmode .fps-adm-option > .ab-item');
			opts.forEach(function(el) {
				var li = el.closest('li');
				if (!li) return;
				var m = li.id.replace('wp-admin-bar-fps-admin-dm-', '');
				li.classList.toggle('fps-adm-active', m === mode);
			});
		}

		// Wire dropdown clicks
		document.addEventListener('click', function(e) {
			var li = e.target.closest('li[id^="wp-admin-bar-fps-admin-dm-"]');
			if (!li) return;
			e.preventDefault();
			var newMode = li.id.replace('wp-admin-bar-fps-admin-dm-', '');
			if (!newMode || newMode === currentMode) return;

			currentMode = newMode;
			applyAdminDark(newMode);
			updateBarIcon(newMode);

			// AJAX save
			var fd = new FormData();
			fd.append('action', 'fps_save_admin_darkmode');
			fd.append('nonce', nonce);
			fd.append('mode', newMode);
			fetch(ajaxUrl, { method: 'POST', body: fd, credentials: 'same-origin' });
		});
	})();
	</script>
	<?php
}
add_action('admin_footer', 'fanspaysite_admin_darkmode_scripts');

/**
 * AJAX handler — save admin dark mode option.
 * Requires manage_options capability and a valid nonce.
 */
function fanspaysite_ajax_save_admin_darkmode() {
	check_ajax_referer('fps_admin_darkmode_nonce', 'nonce');

	if (!current_user_can('manage_options')) {
		wp_send_json_error('Unauthorized', 403);
	}

	$mode = sanitize_key($_POST['mode'] ?? 'system');
	if (!in_array($mode, array('light', 'dark', 'system'), true)) {
		$mode = 'system';
	}

	update_option('fanspaysite_admin_darkmode', $mode);
	wp_send_json_success(array('mode' => $mode));
}
add_action('wp_ajax_fps_save_admin_darkmode', 'fanspaysite_ajax_save_admin_darkmode');
