<?php
/**
 * Admin menu page for the feature flags list.
 *
 * @package   Myrk
 * @author    Bjorn Holine <bjorn@myrk.build>
 * @license   GPL-2.0-or-later
 * @link      https://myrk.build/
 * @copyright 2026 Bjorn Holine
 */

declare( strict_types=1 );

namespace Myrk\Admin;

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

/**
 * Admin menu page for the DataViews flags list.
 * Slug: `myrk` → `admin.php?page=myrk`
 *
 * The same JS bundle also powers the edit/create view — React routes
 * between views based on URL search params.
 */
class FlagsScreen {

	private const MENU_SLUG     = 'myrk';
	private const SCRIPT_HANDLE = 'myrk-admin-flags';
	private const STYLE_HANDLE  = 'myrk-admin';

	/**
	 * Hook suffix assigned by add_menu_page, used to scope enqueue.
	 *
	 * @var string
	 */
	private string $hook_suffix = '';

	/**
	 * Register the admin menu page and enqueue hook.
	 */
	public function register(): void {
		$this->hook_suffix = (string) add_menu_page(
			__( 'Myrk — Feature Flags', 'myrk-feature-flags' ),
			__( 'Myrk', 'myrk-feature-flags' ),
			'manage_options',
			self::MENU_SLUG,
			[ $this, 'render' ],
			self::menu_icon(),
			75
		);

		// Rename the auto-created first submenu entry.
		add_submenu_page(
			self::MENU_SLUG,
			__( 'Feature Flags', 'myrk-feature-flags' ),
			__( 'Feature Flags', 'myrk-feature-flags' ),
			'manage_options',
			self::MENU_SLUG,
			[ $this, 'render' ]
		);

		add_action( 'admin_enqueue_scripts', [ $this, 'enqueue_scripts' ] );
	}

	/**
	 * Admin sidebar icon as a base64 SVG data URI.
	 *
	 * WordPress renders data-URI icons as a CSS background-image, which prevents
	 * external CSS from reaching fill attributes. All shapes use fill so the icon
	 * is visible across admin colour schemes. #a7aaad is the WP default icon grey.
	 */
	private static function menu_icon(): string {
		$svg = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20">'
			. '<path fill="#a7aaad" d="'
			. 'M3.25 2h1.5v16h-1.5z'
			. 'M15.25 2h1.5v16h-1.5z'
			. 'M4.34 3.33L16.34 9.33 15.66 10.67 3.66 4.67z'
			. 'M15.66 3.33L16.34 4.67 4.34 10.67 3.66 9.33z'
			. '"/>'
			. '</svg>';

		// phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode -- base64 SVG data URI is the standard WP pattern for menu icons.
		return 'data:image/svg+xml;base64,' . base64_encode( $svg );
	}

	/**
	 * Enqueue admin JS and CSS on the flags list screen only.
	 *
	 * @param string $hook Current admin page hook suffix.
	 */
	public function enqueue_scripts( string $hook ): void {
		if ( $hook !== $this->hook_suffix ) {
			return;
		}

		$this->enqueue_bundle();

		wp_localize_script(
			self::SCRIPT_HANDLE,
			'myrkAdminFlags',
			[
				'restUrl'    => rest_url( 'myrk/v1/' ),
				'nonce'      => wp_create_nonce( 'wp_rest' ),
				'currentEnv' => wp_get_environment_type(),
				'editUrl'    => admin_url( 'admin.php?page=myrk-edit-flag' ),
				'editMode'   => false,
				'flagKey'    => '',
			]
		);
	}

	/**
	 * Render the React mount point for the flags list.
	 */
	public function render(): void {
		echo '<div class="wrap"><div id="myrk-flags-root"></div></div>';
	}

	// -------------------------------------------------------------------------
	// Internal helpers.
	// -------------------------------------------------------------------------

	/**
	 * Enqueue the JS and CSS bundles built by @wordpress/scripts.
	 */
	private function enqueue_bundle(): void {
		$asset_file = MYRK_DIR . 'build/admin/flags.asset.php';

		if ( file_exists( $asset_file ) ) {
			$asset = require $asset_file;
		} else {
			$asset = [
				'dependencies' => [ 'wp-element', 'wp-components', 'wp-api-fetch', 'wp-i18n', 'wp-dataviews' ],
				'version'      => MYRK_VERSION,
			];
		}

		wp_enqueue_script(
			self::SCRIPT_HANDLE,
			MYRK_URL . 'build/admin/flags.js',
			$asset['dependencies'],
			$asset['version'],
			true
		);

		// Built CSS (generated by @wordpress/scripts alongside the JS bundle).
		$css_path = MYRK_DIR . 'build/admin/flags.css';
		if ( file_exists( $css_path ) ) {
			wp_enqueue_style(
				self::SCRIPT_HANDLE . '-built',
				MYRK_URL . 'build/admin/flags.css',
				[ 'wp-components' ],
				$asset['version']
			);
		}

		// DataViews component stylesheet (vendored from @wordpress/dataviews).
		wp_enqueue_style(
			self::STYLE_HANDLE . '-dataviews',
			MYRK_URL . 'assets/css/dataviews.css',
			[ 'wp-components' ],
			MYRK_VERSION
		);

		// Hand-authored admin CSS.
		wp_enqueue_style(
			self::STYLE_HANDLE,
			MYRK_URL . 'assets/css/admin.css',
			[ self::STYLE_HANDLE . '-dataviews' ],
			MYRK_VERSION
		);
	}
}
