<?php
declare(strict_types=1);

namespace forge12\floating_menu\component\floatingmenu;

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

/**
 * Replaces the entire old PHP admin UI with the React dashboard.
 *
 * - Removes all old submenu pages (Dashboard, Settings)
 * - Removes "Add New" and "All Menus" CPT links
 * - Redirects post-new.php and edit.php for floating_menu to the React dashboard
 * - Registers a single React-powered admin page
 *
 * @since 1.4.0
 */
class AdminDashboard {

	/**
	 * Register hooks.
	 */
	public function __construct() {
		// Remove the old UI's admin_menu hook so it never registers pages.
		add_action( 'admin_menu', [ $this, 'unhook_old_ui' ], 1 );
		// Register our React page.
		add_action( 'admin_menu', [ $this, 'register_react_page' ], 10 );
		add_action( 'admin_enqueue_scripts', [ $this, 'enqueue_assets' ] );
		add_action( 'admin_init', [ $this, 'redirect_old_pages' ] );
		// Load the React bundle as an ES module so its scope stays isolated.
		add_filter( 'script_loader_tag', [ $this, 'script_as_module' ], 10, 3 );
	}

	/**
	 * Output the dashboard bundle as a type="module" script tag.
	 *
	 * The bundle is a self-contained ES module; loading it as a module keeps its
	 * top-level declarations out of the global scope (prevents collisions with
	 * WordPress globals such as window.wp).
	 *
	 * @param string $tag    The full HTML script tag.
	 * @param string $handle The registered script handle.
	 * @param string $src    The script source URL.
	 * @return string
	 */
	public function script_as_module( string $tag, string $handle, string $src ): string {
		if ( 'f12-floating-menu-dashboard' !== $handle ) {
			return $tag;
		}

		return sprintf(
			'<script type="module" src="%s" id="%s-js"></script>' . "\n",
			esc_url( $src ),
			esc_attr( $handle )
		);
	}

	/**
	 * Remove the old UI system's admin_menu callback so it never registers pages.
	 */
	public function unhook_old_ui(): void {
		global $wp_filter;

		if ( ! isset( $wp_filter['admin_menu'] ) ) {
			return;
		}

		foreach ( $wp_filter['admin_menu']->callbacks as $priority => $hooks ) {
			foreach ( $hooks as $key => $hook ) {
				if ( ! is_array( $hook['function'] ) ) {
					continue;
				}
				$obj = $hook['function'][0] ?? null;
				if ( $obj instanceof \forge12\floating_menu\UI && 'addSubmenuPagesToWordPress' === ( $hook['function'][1] ?? '' ) ) {
					unset( $wp_filter['admin_menu']->callbacks[ $priority ][ $key ] );
				}
			}
		}
	}

	/**
	 * Register the React dashboard as the only admin page.
	 */
	public function register_react_page(): void {
		$parent = 'edit.php?post_type=floating_menu';

		// Remove default CPT pages (All Menus, Add New).
		remove_submenu_page( $parent, $parent );
		remove_submenu_page( $parent, 'post-new.php?post_type=floating_menu' );

		// Register React dashboard.
		add_submenu_page(
			$parent,
			__( 'Dashboard', 'f12-floating-menu' ),
			__( 'Dashboard', 'f12-floating-menu' ),
			'manage_options',
			FORGE12_FLOATING_SLUG,
			[ $this, 'render' ]
		);
	}

	/**
	 * Redirect old CPT pages (edit, add new, single edit) to the React dashboard.
	 */
	public function redirect_old_pages(): void {
		global $pagenow;

		if ( ! isset( $_GET['post_type'] ) && ! isset( $_GET['post'] ) ) {
			return;
		}

		$post_type = $_GET['post_type'] ?? '';

		// Redirect edit.php?post_type=floating_menu (list page)
		if ( 'edit.php' === $pagenow && 'floating_menu' === $post_type ) {
			if ( ! isset( $_GET['page'] ) ) {
				wp_safe_redirect( admin_url( 'edit.php?post_type=floating_menu&page=' . FORGE12_FLOATING_SLUG ) );
				exit;
			}
		}

		// Redirect post-new.php?post_type=floating_menu (add new)
		if ( 'post-new.php' === $pagenow && 'floating_menu' === $post_type ) {
			wp_safe_redirect( admin_url( 'edit.php?post_type=floating_menu&page=' . FORGE12_FLOATING_SLUG ) );
			exit;
		}

		// Redirect post.php?post=X (single edit) if post type is floating_menu
		if ( 'post.php' === $pagenow && isset( $_GET['post'] ) ) {
			$post_id = absint( $_GET['post'] );
			$post    = get_post( $post_id );
			if ( $post && 'floating_menu' === $post->post_type ) {
				wp_safe_redirect( admin_url( 'edit.php?post_type=floating_menu&page=' . FORGE12_FLOATING_SLUG . '#/menus/' . $post_id ) );
				exit;
			}
		}
	}

	/**
	 * Render the mount point for the React app.
	 */
	public function render(): void {
		echo '<div id="f12-floating-menu-root" style="background:#fff;margin:-1px -20px 0 0;padding:0;min-height:calc(100vh - 32px);"></div>';
	}

	/**
	 * Enqueue React dashboard assets only on the dashboard page.
	 */
	public function enqueue_assets( string $hook ): void {
		if ( 'floating_menu_page_' . FORGE12_FLOATING_SLUG !== $hook ) {
			return;
		}

		$base_url  = plugin_dir_url( __FILE__ ) . '../../admin/dashboard/';
		$base_path = plugin_dir_path( __FILE__ ) . '../../admin/dashboard/';

		if ( ! file_exists( $base_path . 'index.js' ) ) {
			return;
		}

		// Dequeue ALL old admin styles/scripts that would conflict.
		wp_dequeue_style( FORGE12_FLOATING_SLUG . '-admin' );
		wp_dequeue_style( 'f12_floating_menu_admin' );
		wp_dequeue_style( 'f12_floating_menu_plugin' );
		wp_dequeue_style( 'f12_floating_menu_icon_box' );
		wp_dequeue_style( 'f12_floating_menu_button' );
		wp_dequeue_style( 'f12_floating_menu_select2' );
		wp_dequeue_style( 'f12_floating_menu_select2_vendor' );
		wp_dequeue_style( 'f12_floating_menu_fontawesome' );
		wp_dequeue_script( FORGE12_FLOATING_SLUG . '-toggle' );
		wp_dequeue_script( 'f12_floating_menu_social_share' );
		wp_dequeue_script( 'f12_floating_menu_icon_box' );
		wp_dequeue_script( 'f12_floating_menu_tab_container' );
		wp_dequeue_script( 'f12_floating_menu_control_menu' );
		wp_dequeue_script( 'f12_floating_menu_control_post_types' );
		wp_dequeue_script( 'f12_floating_menu_select2' );
		wp_dequeue_script( 'f12_floating_menu_select2_vendor' );
		wp_dequeue_script( 'f12_floating_menu_items_sorting' );
		wp_dequeue_script( 'f12_floating_menu_items_upload' );
		wp_dequeue_script( 'f12_floating_menu_items_add' );
		wp_dequeue_script( 'f12_floating_menu_items_remove' );
		wp_dequeue_script( 'f12_floating_menu_color_picker' );

		wp_enqueue_style(
			'f12-floating-menu-dashboard',
			$base_url . 'assets/index.css',
			[],
			FORGE12_FLOATING_VERSION
		);

		wp_enqueue_script(
			'f12-floating-menu-dashboard',
			$base_url . 'index.js',
			[],
			FORGE12_FLOATING_VERSION,
			true
		);

		wp_localize_script( 'f12-floating-menu-dashboard', 'f12FloatingMenu', [
			'restUrl'   => esc_url_raw( rest_url( 'f12-floating-menu/v1' ) ),
			'nonce'     => wp_create_nonce( 'wp_rest' ),
			'adminUrl'  => esc_url_raw( admin_url() ),
			'pluginUrl' => esc_url_raw( plugin_dir_url( __FILE__ ) . '../../' ),
		] );

		wp_enqueue_media();
	}
}
