<?php
/**
 * WordPress admin shell for Order From DM v2 (Reborn Labs).
 * Enqueues the React bundle from admin-app/dist/ — see docs/repository-map.md.
 */
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

class DC_V2_Admin {

	const MENU_GLOW_LS_KEY = 'dc_v2_menu_glow_seen';

	private static $resolved_js  = '';
	private static $resolved_css = '';

	public static function init() {
		add_action( 'admin_menu', array( __CLASS__, 'menu' ) );
		add_action( 'admin_head', array( __CLASS__, 'menu_brand_styles' ) );
		add_action( 'admin_footer', array( __CLASS__, 'menu_glow_script' ) );
		add_action( 'admin_enqueue_scripts', array( __CLASS__, 'enqueue_core_packages' ), 1 );
		add_action( 'admin_enqueue_scripts', array( __CLASS__, 'assets' ), 10 );
		add_action( 'admin_enqueue_scripts', array( __CLASS__, 'dequeue_unused_scripts' ), 100 );
		add_action( 'admin_notices', array( __CLASS__, 'duplicate_install_notice' ) );
	}

	public static function duplicate_install_notice() {
		if ( ! current_user_can( 'activate_plugins' ) || ! function_exists( 'dc_v2_duplicate_install_paths' ) ) {
			return;
		}
		$paths = dc_v2_duplicate_install_paths();
		if ( count( $paths ) < 2 ) {
			return;
		}
		$screen = function_exists( 'get_current_screen' ) ? get_current_screen() : null;
		if ( ! $screen || ! in_array( $screen->id, array( 'plugins', 'toplevel_page_' . DC_V2_PLUGIN_SLUG ), true ) ) {
			return;
		}
		$active = plugin_basename( DC_V2_FILE );
		$others = array_values( array_diff( $paths, array( $active ) ) );
		if ( ! $others ) {
			return;
		}
		echo '<div class="notice notice-warning"><p><strong>' . esc_html( dc_v2_plugin_title() ) . ':</strong> ';
		echo esc_html__( 'Two copies of the plugin are installed. Keep only plugins/order-from-dm/ active and delete the other folder (amispet-direct-checkout-v2) from Plugins to avoid update issues.', 'order-from-dm' );
		echo ' <code>' . esc_html( implode( '</code>, <code>', $others ) ) . '</code></p></div>';
	}

	public static function enqueue_core_packages( $hook ) {
		$expected_hook = 'toplevel_page_' . DC_V2_PLUGIN_SLUG;
		if ( $hook !== $expected_hook && ! self::is_plugin_page() ) {
			return;
		}
		$packages = array(
			'wp-i18n',
			'wp-hooks',
			'wp-api-fetch',
			'wp-url',
			'lodash',
			'wp-element',
			'wp-data',
		);
		foreach ( $packages as $handle ) {
			wp_enqueue_script( $handle );
		}
	}

	public static function dequeue_unused_scripts( $hook ) {
		$expected_hook = 'toplevel_page_' . DC_V2_PLUGIN_SLUG;
		if ( $hook !== $expected_hook && ! self::is_plugin_page() ) {
			return;
		}
		foreach ( array( 'color-picker', 'iris', 'svg-painter' ) as $handle ) {
			wp_dequeue_script( $handle );
			wp_deregister_script( $handle );
		}
		foreach ( array( 'wp-color-picker' ) as $handle ) {
			wp_dequeue_style( $handle );
			wp_deregister_style( $handle );
		}
	}

	public static function menu() {
		add_menu_page(
			dc_v2_plugin_title(),
			dc_v2_plugin_title(),
			'manage_woocommerce',
			DC_V2_PLUGIN_SLUG,
			array( __CLASS__, 'render' ),
			dc_v2_menu_icon(),
			dc_v2_menu_position()
		);
	}

	public static function menu_brand_styles() {
		$menu_id    = '#toplevel_page_' . esc_attr( DC_V2_PLUGIN_SLUG );
		$row        = '#adminmenu ' . $menu_id . ' > a.menu-top';
		$folded_row = '.folded #adminmenu ' . $menu_id . ' > a.menu-top';
		?>
		<style>
			<?php echo $row; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Built from a sanitized plugin slug. ?>,
			#adminmenu <?php echo $menu_id; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Built from a sanitized plugin slug. ?>.wp-has-current-submenu > a.menu-top,
			<?php echo $row; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Built from a sanitized plugin slug. ?>:hover,
			<?php echo $row; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Built from a sanitized plugin slug. ?>:focus {
				position: relative;
				border-radius: 6px;
				margin: 2px 6px;
				background: linear-gradient(135deg, rgba(139, 92, 246, .28) 0%, rgba(168, 85, 247, .18) 100%) !important;
				box-shadow: inset 0 0 0 1px rgba(192, 132, 252, .28);
			}
			<?php echo $folded_row; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Built from a sanitized plugin slug. ?> {
				margin: 2px 2px;
			}
			@keyframes dc-v2-menu-row-pulse {
				0%, 100% {
					box-shadow:
						0 0 4px 1px rgba(168, 85, 247, .35),
						inset 0 0 0 1px rgba(192, 132, 252, .35);
				}
				50% {
					box-shadow:
						0 0 14px 4px rgba(192, 132, 252, .75),
						inset 0 0 0 1px rgba(216, 180, 254, .55);
				}
			}
			<?php echo $row; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Built from a sanitized plugin slug. ?>.dc-v2-menu-glow-active {
				animation: dc-v2-menu-row-pulse 2.4s ease-in-out infinite;
			}
			@media (prefers-reduced-motion: reduce) {
				<?php echo $row; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Built from a sanitized plugin slug. ?>.dc-v2-menu-glow-active {
					animation: none;
					box-shadow:
						0 0 8px 2px rgba(168, 85, 247, .55),
						inset 0 0 0 1px rgba(192, 132, 252, .4);
				}
			}
		</style>
		<?php
	}

	public static function menu_glow_script() {
		$update  = class_exists( 'DC_V2_Plugin_Updater', false )
			&& DC_V2_Plugin_Updater::is_update_available_cached();
		$on_page = self::is_plugin_page();
		?>
		<script>
		(function () {
			var menuId = <?php echo wp_json_encode( 'toplevel_page_' . DC_V2_PLUGIN_SLUG ); ?>;
			var lsKey = <?php echo wp_json_encode( self::MENU_GLOW_LS_KEY ); ?>;
			var updateAvailable = <?php echo $update ? 'true' : 'false'; ?>;
			var isPluginPage = <?php echo $on_page ? 'true' : 'false'; ?>;

			function shouldGlow() {
				if (updateAvailable) {
					return true;
				}
				try {
					return !window.localStorage.getItem(lsKey);
				} catch (e) {
					return false;
				}
			}

			function applyGlow() {
				var item = document.getElementById(menuId);
				if (!item) {
					return;
				}
				var link = item.querySelector(':scope > a.menu-top');
				if (!link) {
					return;
				}
				link.classList.toggle('dc-v2-menu-glow-active', shouldGlow());
			}

			if (isPluginPage) {
				try {
					window.localStorage.setItem(lsKey, '1');
				} catch (e) {}
			}

			if (document.readyState === 'loading') {
				document.addEventListener('DOMContentLoaded', applyGlow);
			} else {
				applyGlow();
			}
		})();
		</script>
		<?php
	}

	public static function is_plugin_page() {
		return is_admin()
			&& isset( $_GET['page'] )
			&& sanitize_key( wp_unslash( $_GET['page'] ) ) === DC_V2_PLUGIN_SLUG;
	}

	private static function resolve_assets() {
		if ( self::$resolved_js ) {
			return array(
				'js'  => self::$resolved_js,
				'css' => self::$resolved_css,
			);
		}
		$manifest = DC_V2_PATH . 'admin-app/dist/.vite/manifest.json';
		$js       = 'admin-app/dist/assets/index.js';
		$css      = 'admin-app/dist/assets/index.css';
		if ( file_exists( $manifest ) ) {
			$data = json_decode( file_get_contents( $manifest ), true );
			if ( is_array( $data ) ) {
				if ( ! empty( $data['index.html']['file'] ) ) {
					$js = 'admin-app/dist/' . $data['index.html']['file'];
				}
				if ( ! empty( $data['index.html']['css'][0] ) ) {
					$css = 'admin-app/dist/' . $data['index.html']['css'][0];
				} elseif ( ! empty( $data['style.css']['file'] ) ) {
					// Vite IIFE build emits CSS as a separate manifest entry.
					$css = 'admin-app/dist/' . $data['style.css']['file'];
				}
			}
		}
		self::$resolved_js  = $js;
		self::$resolved_css = $css;
		return array( 'js' => $js, 'css' => $css );
	}

	public static function assets( $hook ) {
		$expected_hook = 'toplevel_page_' . DC_V2_PLUGIN_SLUG;
		if ( $hook !== $expected_hook && ! self::is_plugin_page() ) {
			return;
		}
		$assets = self::resolve_assets();
		if ( file_exists( DC_V2_PATH . $assets['css'] ) ) {
			$css_ver = (string) filemtime( DC_V2_PATH . $assets['css'] );
			wp_enqueue_style( 'dc-v2-admin', dc_v2_asset_url( $assets['css'] ), array(), $css_ver );
		}
		if ( ! file_exists( DC_V2_PATH . $assets['js'] ) ) {
			return;
		}
		$js_ver  = (string) filemtime( DC_V2_PATH . $assets['js'] );
		$payload = self::admin_config_payload();
		wp_register_script(
			'dc-v2-admin',
			dc_v2_asset_url( $assets['js'] ),
			array(),
			$js_ver,
			true
		);
		wp_add_inline_script(
			'dc-v2-admin',
			'window.DCV2Admin=' . wp_json_encode( $payload ) . ';',
			'before'
		);
		wp_enqueue_script( 'dc-v2-admin' );

		add_action( 'admin_head', array( __CLASS__, 'preload_hero_images' ), 1 );

		$fields_runtime = isset( $payload['fieldsEditorRuntime'] ) && is_array( $payload['fieldsEditorRuntime'] )
			? $payload['fieldsEditorRuntime']
			: DC_V2_Fields_Editor_Runtime::resolve();
		if ( ! empty( $fields_runtime['ready'] ) && ! empty( $fields_runtime['url'] ) ) {
			wp_enqueue_script(
				'dc-v2-fields-editor',
				$fields_runtime['url'],
				array(),
				$fields_runtime['ver'],
				true
			);
			wp_localize_script(
				'dc-v2-fields-editor',
				'DCV2FieldsEditorBoot',
				array(
					'mode'    => 'composer',
					'restUrl' => esc_url_raw( rest_url( DC_V2_REST::NS ) ),
					'nonce'   => wp_create_nonce( 'wp_rest' ),
					'i18n'    => DC_V2_Product_Fields::editor_i18n(),
				)
			);
		}
	}

	/**
	 * Early <link rel="preload"> for versioned hero PNGs (long-cached via assets/admin/.htaccess).
	 */
	public static function preload_hero_images() {
		static $done = false;
		if ( $done || ! self::is_plugin_page() ) {
			return;
		}
		$done = true;

		$primary = function_exists( 'wp_is_mobile' ) && wp_is_mobile()
			? array(
				dc_v2_admin_hero_main_mobile_url(),
				dc_v2_admin_hero_fields_mobile_url(),
			)
			: array(
				dc_v2_admin_hero_main_desktop_url(),
				dc_v2_admin_hero_fields_desktop_url(),
			);

		foreach ( array_filter( $primary ) as $url ) {
			printf(
				'<link rel="preload" as="image" href="%s" />' . "\n",
				esc_url( $url )
			);
		}
	}

	private static function admin_config_payload() {
		// Non-blocking: only enqueue WP-Cron for the one-shot snapshot (never collect here).
		$snapshot_pending = false;
		if ( class_exists( 'DC_V2_Store_Snapshot', false ) && DC_V2_Store_Snapshot::is_pending() ) {
			DC_V2_Store_Snapshot::schedule_background();
			$snapshot_pending = true;
		}

		// Single resolve() for enqueue + boot payload (avoids double remote calls).
		$fields_runtime = DC_V2_Fields_Editor_Runtime::resolve();

		return array(
			'restUrl'               => esc_url_raw( rest_url( DC_V2_REST::NS ) ),
			'nonce'                 => wp_create_nonce( 'wp_rest' ),
			'homeUrl'               => home_url( '/' ),
			'adminEmail'            => wp_get_current_user()->user_email,
			'adminName'             => wp_get_current_user()->display_name,
			'siteName'              => get_bloginfo( 'name' ),
			'siteUrl'               => home_url( '/' ),
			'pluginTitle'           => dc_v2_plugin_title(),
			'pluginName'            => dc_v2_plugin_name(),
			'heroImageUrl'          => dc_v2_admin_hero_image_url(),
			'heroMainDesktopUrl'    => dc_v2_admin_hero_main_desktop_url(),
			'heroMainMobileUrl'     => dc_v2_admin_hero_main_mobile_url(),
			'heroFieldsDesktopUrl'  => dc_v2_admin_hero_fields_desktop_url(),
			'heroFieldsMobileUrl'   => dc_v2_admin_hero_fields_mobile_url(),
			'docsUrl'               => dc_v2_docs_url(),
			'letsBuildUrl'          => dc_v2_lets_build_url(),
			'supportEmail'          => dc_v2_support_email(),
			'siteFaviconUrl'        => dc_v2_site_favicon_url( 32 ),
			'pluginBrandMarkUrl'    => dc_v2_plugin_brand_mark_url(),
			'pluginVersion'         => DC_V2_VERSION,
			'pageUrl'               => admin_url( 'admin.php?page=' . DC_V2_PLUGIN_SLUG ),
			'adminUrl'              => admin_url( '/' ),
			'locale'                => dc_v2_plugin_locale(),
			'i18n'                  => DC_V2_I18n::admin_strings(),
			'i18nPacks'             => DC_V2_I18n::admin_i18n_packs(),
			'defaultCopy'           => dc_v2_default_copy(),
			'featureRequestOptions' => DC_V2_I18n::feature_request_options(),
			'appearancePresets'     => DC_V2_I18n::appearance_presets(),
			'license'               => DC_V2_License::admin_state_boot(),
			'freeOrderLimit'        => dc_v2_free_order_limit(),
			'checkoutUrl'           => dc_v2_ls_checkout_url(),
			'checkoutUrlYearly'     => dc_v2_ls_checkout_url_yearly(),
			'storeSnapshotPending'  => $snapshot_pending,
			'storeCurrency'         => dc_v2_store_currency(),
			'updates'               => DC_V2_Plugin_Updater::admin_state(),
			'fieldsEditorRuntime'   => $fields_runtime,
			'fieldsEditorReady'     => ! empty( $fields_runtime['ready'] ),
			'canUpdatePlugins'      => class_exists( 'DC_V2_Plugin_Updater', false )
				? DC_V2_Plugin_Updater::can_run_upgrade()
				: current_user_can( 'update_plugins' ),
			'canCorePluginUpdate'   => current_user_can( 'update_plugins' ),
		);
	}

	public static function render() {
		$title = esc_html( dc_v2_plugin_title() );
		echo '<div class="wrap dc-v2-admin-page">';
		echo '<div id="dc-v2-root" class="dc-v2-admin-root">';
		echo '<div class="dc-v2-boot" role="status" aria-live="polite" aria-busy="true">';
		echo '<div class="dc-v2-boot__panel">';
		echo '<span class="dc-v2-boot__spinner" aria-hidden="true"></span>';
		echo '<span class="dc-v2-boot__label">' . esc_html__( 'Loading…', 'order-from-dm' ) . '</span>';
		echo '<span class="screen-reader-text">' . $title . '</span>';
		echo '</div></div>';
		echo '<style id="dc-v2-boot-css">'
			. '#dc-v2-root.dc-v2-admin-root{min-height:calc(100vh - 132px);position:relative}'
			. '.dc-v2-boot{position:absolute;inset:0;display:flex;align-items:center;justify-content:center;'
			. 'padding:48px 20px;box-sizing:border-box;'
			. 'background:radial-gradient(120% 80% at 50% 0%,rgba(237,233,254,.95) 0%,rgba(250,248,255,.98) 45%,#f6f3fb 100%)}'
			. '.dc-v2-boot__panel{display:flex;flex-direction:column;align-items:center;gap:16px}'
			. '.dc-v2-boot__spinner{width:40px;height:40px;border-radius:999px;'
			. 'border:3px solid rgba(124,58,237,.14);border-top-color:#7c3aed;border-right-color:#a855f7;'
			. 'animation:dc-v2-boot-spin .68s linear infinite;'
			. 'box-shadow:0 0 0 8px rgba(124,58,237,.05)}'
			. '.dc-v2-boot__label{font:600 12px/1.3 ui-sans-serif,system-ui,-apple-system,sans-serif;'
			. 'letter-spacing:.08em;text-transform:uppercase;color:#7c3aed}'
			. '@keyframes dc-v2-boot-spin{to{transform:rotate(360deg)}}'
			. '@media (prefers-reduced-motion:reduce){.dc-v2-boot__spinner{animation:none;opacity:.9}}'
			. '</style>';
		echo '</div>';
		echo '</div>';
		echo '<noscript><p class="notice notice-error"><strong>' . $title . '</strong> '
			. esc_html__( 'requires JavaScript.', 'order-from-dm' )
			. '</p></noscript>';
	}
}
