<?php
/**
 * File Path: includes/helpers/class-mbs-dark-mode-manager.php
 *
 * My Book Showroom — Dark Mode Manager
 *
 * Outputs the blocking inline script that applies data-mbs-theme="dark"
 * before first paint (FOUC prevention). Extracted from MBS_Front_Assets
 * (RF-007) to separate the asset-enqueue concern from the head-injection
 * concern.
 *
 * @package MyBookShowroom
 * @since   1.0.0
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

class MBS_Dark_Mode_Manager {

	/**
	 * Register the wp_head hook.
	 *
	 * Called from MBS_Plugin::load_core_services(). Hook is registered here
	 * rather than inside MBS_Front_Assets::enqueue() to avoid the wp_head
	 * priority-1 trap: WordPress fires do_action('wp_enqueue_scripts') at
	 * priority 1 of wp_head, so any add_action('wp_head', ..., 1) called
	 * during enqueue() is silently skipped. Registering at instantiation
	 * guarantees the callback is queued before wp_head fires.
	 */
	public function __construct() {
		add_action( 'wp_head', array( $this, 'output_dark_mode_attribute' ), 1 );
	}

	/**
	 * Output a blocking inline script that sets data-mbs-theme="dark" on
	 * <html> before first paint, preventing FOUC on dark-mode pages.
	 *
	 * Per-book override: a 'light' override suppresses the attribute even when
	 * the global dark mode option is enabled; a 'dark' override forces it even
	 * when the global option is off.
	 *
	 * Hooked to wp_head at priority 1.
	 *
	 * @return void
	 */
	public function output_dark_mode_attribute(): void {
		// V6-D-004: Skip DB reads entirely on non-MBS pages (contact pages,
		// WooCommerce, home page, etc.) to avoid unnecessary DB queries.
		$is_mbs_page = is_singular( MBS_POST_TYPE ) || is_tax( array(
			MBS_TAX_AUTHOR, MBS_TAX_SERIES, MBS_TAX_GENRE, MBS_TAX_TAG,
			MBS_TAX_COLLECTION, MBS_TAX_UNIVERSE, MBS_TAX_THEME,
			MBS_TAX_CONTENT_WARNING, MBS_TAX_PUBLISHER,
			MBS_TAX_IMPRINT, MBS_TAX_CONTRIBUTOR,
		) );
		if ( ! $is_mbs_page && ! is_admin() ) {
			return;
		}

		$override = '';
		if ( is_singular( MBS_POST_TYPE ) ) {
			$post_id  = get_queried_object_id();
			$override = get_post_meta( $post_id, 'mbs_theme_override', true );
		}

		$global_dark = (bool) get_option( 'mbs_setting_appearance_dark_mode' );

		if ( 'light' === $override ) {
			return; // Suppress — do not set the attribute.
		}
		if ( 'dark' === $override || $global_dark ) {
			echo '<script>document.documentElement.setAttribute("data-mbs-theme","dark");</script>' . "\n";
		}
	}
}
