<?php

namespace NeurogenesisTheme\Core\Admin\Actions;

use NeurogenesisTheme\Helpers\OnboardingNotice;
use NeurogenesisTheme\Helpers\RatingNotice;

class Assets {

    public function __construct()
    {
        add_action('admin_enqueue_scripts', [$this, 'loadOnboardingNoticeAssets']);
        add_action('admin_enqueue_scripts', [$this, 'loadRatingNoticeAssets']);

		if($this->is_neurogenesis_theme_route()){            
			add_action('admin_enqueue_scripts', [$this, 'tailwind_init']);
			add_action('admin_enqueue_scripts', [$this, 'load']);
		}
    }

    /**
     * Onboarding notice assets (all wp-admin screens except NeurogenesisTheme app page).
     *
     * @return void
     */
    public function loadOnboardingNoticeAssets()
    {
        if (!OnboardingNotice::should_render()) {
            return;
        }

        wp_register_style(
            'neurogenesis-theme-fonts',
            'https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;700;800&display=swap',
            [],
            null
        );
        wp_enqueue_style('neurogenesis-theme-fonts');

        $tokens_path = get_template_directory() . '/assets/admin/css/neurogenesis-theme-design-tokens.css';
        $tokens_ver  = file_exists($tokens_path) ? (string) filemtime($tokens_path) : NEUROGENESIS_THEME_THEME_VERSION;
        wp_enqueue_style(
            'neurogenesis-theme-design-tokens',
            $this->assets_url('admin/css/neurogenesis-theme-design-tokens.css'),
            [],
            $tokens_ver
        );

        $css_path = get_template_directory() . '/assets/admin/css/admin-onboarding-notice.css';
        $css_ver  = file_exists($css_path) ? (string) filemtime($css_path) : NEUROGENESIS_THEME_THEME_VERSION;
        wp_enqueue_style(
            'neurogenesis-theme-admin-onboarding-notice',
            $this->assets_url('admin/css/admin-onboarding-notice.css'),
            ['neurogenesis-theme-design-tokens', 'neurogenesis-theme-fonts'],
            $css_ver
        );

        $js_path = get_template_directory() . '/assets/admin/js/admin-onboarding-notice.js';
        $js_ver  = file_exists($js_path) ? (string) filemtime($js_path) : NEUROGENESIS_THEME_THEME_VERSION;
        wp_enqueue_script(
            'neurogenesis-theme-admin-onboarding-notice',
            $this->assets_url('admin/js/admin-onboarding-notice.js'),
            [],
            $js_ver,
            true
        );

        wp_localize_script(
            'neurogenesis-theme-admin-onboarding-notice',
            'neurogenesisThemeOnboardingNotice',
            [
                'debug'        => OnboardingNotice::is_debug(),
                'ajaxUrl'      => admin_url('admin-ajax.php'),
                'nonce'        => wp_create_nonce('neurogenesis_theme_onboarding_notice'),
                'installNonce' => wp_create_nonce('neurogenesis_theme_recommended_plugin'),
                'dashboardUrl' => neurogenesis_theme_generate_page_url('dashboard'),
                'importUrl'    => (string) apply_filters(
                    'neurogenesis_theme_onboarding_import_url',
                    neurogenesis_theme_generate_page_url('dashboard')
                ),
                'i18n'         => [
                    'installing' => __('Installing…', 'thinko'),
                    'activating' => __('Activating…', 'thinko'),
                    'error'      => __('Could not install the plugin. Try again.', 'thinko'),
                ],
            ]
        );
    }

    /**
     * Rating admin notice assets (eligible wp-admin screens).
     *
     * @return void
     */
    public function loadRatingNoticeAssets()
    {
        if (!RatingNotice::should_render()) {
            return;
        }

        $css_path = get_template_directory() . '/assets/admin/css/admin-rating-notice.css';
        $css_ver  = file_exists($css_path) ? (string) filemtime($css_path) : NEUROGENESIS_THEME_THEME_VERSION;
        wp_enqueue_style(
            'neurogenesis-theme-admin-rating-notice',
            $this->assets_url('admin/css/admin-rating-notice.css'),
            [],
            $css_ver
        );

        $js_path = get_template_directory() . '/assets/admin/js/admin-rating-notice.js';
        $js_ver  = file_exists($js_path) ? (string) filemtime($js_path) : NEUROGENESIS_THEME_THEME_VERSION;
        wp_enqueue_script(
            'neurogenesis-theme-admin-rating-notice',
            $this->assets_url('admin/js/admin-rating-notice.js'),
            [],
            $js_ver,
            true
        );

        $rating_context = RatingNotice::view_context();

        wp_localize_script(
            'neurogenesis-theme-admin-rating-notice',
            'neurogenesisThemeRatingNotice',
            [
                'debug'     => RatingNotice::is_debug(),
                'ajaxUrl'   => admin_url('admin-ajax.php'),
                'nonce'     => wp_create_nonce('neurogenesis_theme_rating_notice'),
                'reviewUrl' => $rating_context['review_url'] ?? '',
                'i18n'      => [
                    'highRatingHeadline' => esc_html__('You gave us %d stars!', 'thinko') . ' &#128525;',
                ],
            ]
        );
    }

    /**
     * Load the scripts/styles
     *
     * @return void
     */
    public function load()
    {
        wp_register_style('neurogenesis-theme-fonts', 'https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;700;800&display=swap');
        wp_enqueue_style('neurogenesis-theme-fonts');

        $tokens_path = get_template_directory() . '/assets/admin/css/neurogenesis-theme-design-tokens.css';
        $tokens_ver  = file_exists($tokens_path) ? (string) filemtime($tokens_path) : NEUROGENESIS_THEME_THEME_VERSION;
        wp_enqueue_style(
            'neurogenesis-theme-design-tokens',
            $this->assets_url('admin/css/neurogenesis-theme-design-tokens.css'),
            [],
            $tokens_ver
        );

        $styles_path = get_template_directory() . '/assets/admin/css/styles.css';
        $styles_ver   = file_exists($styles_path) ? (string) filemtime($styles_path) : NEUROGENESIS_THEME_THEME_VERSION;
        wp_register_style('neurogenesis-theme-styles', $this->assets_url('admin/css/styles.css'), ['neurogenesis-theme-design-tokens', 'neurogenesis-theme-fonts'], $styles_ver);
        wp_enqueue_style('neurogenesis-theme-styles');

        if ($this->is_neurogenesis_theme_route() && neurogenesis_theme_active_page('dashboard')) {
            $dashboard_js = get_template_directory() . '/assets/admin/js/dashboard.js';
            $dashboard_ver = file_exists($dashboard_js) ? (string) filemtime($dashboard_js) : NEUROGENESIS_THEME_THEME_VERSION;
            wp_enqueue_script(
                'neurogenesis-theme-dashboard',
                $this->assets_url('admin/js/dashboard.js'),
                [],
                $dashboard_ver,
                true
            );

            wp_localize_script(
                'neurogenesis-theme-dashboard',
                'neurogenesisThemeDashboard',
                [
                    'ajaxUrl' => admin_url('admin-ajax.php'),
                    'nonce' => wp_create_nonce('neurogenesis_theme_recommended_plugin'),
                    'dashboardUrl' => neurogenesis_theme_generate_page_url('dashboard'),
                    'importUrl' => (string) apply_filters(
                        'neurogenesis_theme_onboarding_import_url',
                        neurogenesis_theme_generate_page_url('dashboard')
                    ),
                    'checkIconHtml' => neurogenesis_theme_svg_icon('check'),
                    'i18n' => [
                        'installing' => __('Installing…', 'thinko'),
                        'activating' => __('Activating…', 'thinko'),
                        'active' => __('Active', 'thinko'),
                        'activate' => __('Activate', 'thinko'),
                        'error' => __('Could not install the plugin. Try again.', 'thinko'),
                        'stepsCompleted' => __('%1$d of %2$d steps completed', 'thinko'),
                    ],
                ]
            );
        }
    }

    /**
     * Get the admin assets url
     *
     * @param  mixed $filename
     * @return string
     */
    public function assets_url($filename)
    {
        return get_template_directory_uri() . '/assets/'.$filename;
    }

    /**
     * Loads an asset for specific routes.
     *
     * @param string $asset_url The URL of the asset to load.
     * @param array $routes An array of routes for which the asset should be loaded.
     * @param array $deps An array of dependencies for the asset.
     * @param array $args Additional arguments for loading the asset.
     * @return void
     */
    public function load_asset_for_routes($asset_url, $routes = [], $deps = [], $args = [])
    {
        if(!$this->is_neurogenesis_theme_route($routes)) {
            return;
        }        
        
        $version = time();
        $args = wp_parse_args($args, [
            'in_footer' => true
        ]);
        
        if(empty($deps)){            
            // get filename without the extension from the path
            $filename = pathinfo($asset_url, PATHINFO_FILENAME);
            // get the folder path from the $asset_path
            $asset_path = pathinfo($asset_url, PATHINFO_DIRNAME);
            $asset_file_deps = neurogenesis_theme_plugin_path( 'assets/'.$asset_path ) . '/'.$filename.'.asset.php';            

            if ( file_exists( $asset_file_deps ) ) {
                $asset = include $asset_file_deps;
                $deps = $asset['dependencies'];
                $version = $asset['version'];
            }            
        }
        

        wp_enqueue_script('neurogenesis-theme-admin-asset', $this->assets_url($asset_url), $deps, $version, $args);
        
    }

    /**
     * Checks if the current route is a NeurogenesisTheme route.
     *
     * @param array $routes An array of routes to check against.
     * @param int $page_id The ID of the NeurogenesisTheme Architect page.
     * @return bool True when the NeurogenesisTheme admin page matches; if $routes is non-empty, the `route` query var must be listed.
     */
    public function is_neurogenesis_theme_route($routes = [], $page_id = NEUROGENESIS_THEME_PAGE_ID)
    {        
        if( !isset($_GET['page']) || $_GET['page'] !== $page_id ){
            return false;
        }

        // Empty whitelist: any screen under this admin page (e.g. default ?page=neurogenesis-theme with no route).
        if ( empty( $routes ) ) {
            return true;
        }

        if ( isset( $_GET['route'] ) && in_array( $_GET['route'], $routes, true ) ) {
            return true;
        }

        return false;
    }

    /**
     * Initializes the tailwind.
     *
     * This method is responsible for initializing the tailwind process in the `Assets` class.
     * It is called during the theme initialization to load and enqueue necessary assets.
     */
	public function tailwind_init()
	{
		$tailwind_path = get_template_directory() . '/assets/admin/css/tailwind.css';
		$ver            = file_exists($tailwind_path) ? (string) filemtime($tailwind_path) : NEUROGENESIS_THEME_THEME_VERSION;
		wp_register_style('neurogenesis-theme-tailwind', $this->assets_url('admin/css/tailwind.css'), [], $ver);
		wp_enqueue_style('neurogenesis-theme-tailwind');
	}

}
