<?php

namespace WeDevs\AppBridge;

use WeDevs\AppBridge\Core\Contracts\Hookable;

class Assets implements Hookable {

	public function register_hooks(): void {
		add_action( 'init', [ $this, 'register_all_scripts' ] );
		add_action( 'admin_enqueue_scripts', [ $this, 'enqueue_admin_assets' ] );
	}

	public function register_all_scripts(): void {
		$scripts = $this->get_scripts();
		$styles  = $this->get_styles();

		foreach ( $scripts as $handle => $script ) {
			$deps = $script['deps'] ?? [];

			wp_register_script( $handle, $script['src'], $deps, $script['version'], true );
			wp_set_script_translations( $handle, 'app-bridge' );
		}

		foreach ( $styles as $handle => $style ) {
			$deps = $style['deps'] ?? [];

			wp_register_style( $handle, $style['src'], $deps, $style['version'] );
		}
	}

	public function enqueue_admin_assets( string $hook_suffix ): void {
		// Only enqueue on Mobile App menu pages
		if ( ! $this->is_mobile_app_page( $hook_suffix ) ) {
			return;
		}

		wp_enqueue_script( 'app-bridge-script' );
		wp_enqueue_style( 'app-bridge-style' );
		wp_enqueue_media();

		wp_localize_script(
			'app-bridge-script',
			'appBridge',
			[
				'admin_url' => admin_url(),
				'logo_url'  => APP_BRIDGE_ASSETS . '/images/appbridge_logo.svg',
				'version'   => app_bridge()->version,
			]
		);
	}

	/**
	 * Check if the current admin page is a Mobile App page.
	 */
	private function is_mobile_app_page( string $hook_suffix ): bool {
		return strpos( $hook_suffix, 'app-bridge' ) !== false;
	}

	private function get_scripts(): array {
		$scripts = [];

		$admin_assets = APP_BRIDGE_DIR . 'assets/main.asset.php';
		if ( file_exists( $admin_assets ) ) {
			$admin_assets = require $admin_assets;

			$scripts['app-bridge-script'] = [
				'src'     => APP_BRIDGE_ASSETS . '/main.js',
				'version' => $admin_assets['version'],
				'deps'    => $admin_assets['dependencies'],
			];
		}

		return $scripts;
	}


	private function get_styles(): array {
		$css_file = APP_BRIDGE_DIR . 'assets/main.css';
		$version  = file_exists( $css_file ) ? filemtime( $css_file ) : APP_BRIDGE_VERSION;

		return [
			'app-bridge-style' => [
				'src'     => APP_BRIDGE_ASSETS . '/main.css',
				'version' => $version,
				'deps'    => [ 'wp-components' ],
			],
		];
	}
}
