<?php

declare(strict_types=1);

namespace Australcode\Rewards\Admin;

defined( 'ABSPATH' ) || exit;

/**
 * Enqueues the admin CSS only on this plugin's pages.
 *
 * Loads the Australcode Admin Kit (acds — hub `wp-plugin-design/starter/`,
 * installed by `acds-sync.sh`; Verde Austral identity, decision 8.109) plus the
 * plugin's own domain CSS (layered on top of the kit — never editing
 * `admin-kit.css`). Matching by `str_contains` of the slug is robust to
 * menu_title changes (which change the hook prefix).
 *
 * Cache-busted by `filemtime` so a CDN/page cache picks up CSS edits without a
 * version bump; the kit files carry the manifest version (bumped only by
 * `acds-sync.sh`).
 */
final class AssetLoader {

	public const HANDLE            = 'acrwd-admin';
	public const HANDLE_ACDS_FONTS = 'acrwd-acds-fonts';
	public const HANDLE_ACDS_KIT   = 'acrwd-acds-kit';
	public const HANDLE_CALC       = 'acrwd-settings-calc';
	public const HANDLE_ROLES      = 'acrwd-role-multipliers';
	public const HANDLE_TABS       = 'acrwd-settings-tabs';

	public function register(): void {
		add_action( 'admin_enqueue_scripts', array( $this, 'enqueue' ) );
	}

	public function enqueue( string $hook ): void {
		if ( ! str_contains( $hook, 'acrwd' ) ) {
			return;
		}

		wp_enqueue_style(
			self::HANDLE_ACDS_FONTS,
			ACRWD_URL . 'assets/acds/fonts.css',
			array(),
			$this->file_version( 'assets/acds/fonts.css' )
		);
		wp_enqueue_style(
			self::HANDLE_ACDS_KIT,
			ACRWD_URL . 'assets/acds/admin-kit.css',
			array( self::HANDLE_ACDS_FONTS ),
			$this->file_version( 'assets/acds/admin-kit.css' )
		);
		wp_enqueue_style(
			self::HANDLE,
			ACRWD_URL . 'assets/admin/admin.css',
			array( self::HANDLE_ACDS_KIT ),
			$this->file_version( 'assets/admin/admin.css' )
		);

		if ( str_contains( $hook, 'acrwd-settings' ) ) {
			wp_enqueue_script(
				self::HANDLE_CALC,
				ACRWD_URL . 'assets/admin/admin-settings-calc.js',
				array(),
				$this->file_version( 'assets/admin/admin-settings-calc.js' ),
				true
			);
			wp_enqueue_script(
				self::HANDLE_ROLES,
				ACRWD_URL . 'assets/admin/role-multipliers.js',
				array(),
				$this->file_version( 'assets/admin/role-multipliers.js' ),
				true
			);
			wp_enqueue_script(
				self::HANDLE_TABS,
				ACRWD_URL . 'assets/admin/settings-tabs.js',
				array(),
				$this->file_version( 'assets/admin/settings-tabs.js' ),
				true
			);
		}
	}

	/** Cache-busting version: the file's mtime, or the plugin version. */
	private function file_version( string $relative ): string {
		$path = ACRWD_PATH . $relative;
		return file_exists( $path ) ? (string) filemtime( $path ) : ACRWD_VERSION;
	}
}
