<?php

namespace CouponsPlus\App\Handlers;

use CouponsPlus\App\Components\WelcomeDevelopmentScripts;
use CouponsPlus\Original\Collections\Collection;
use CouponsPlus\Original\Environment\Env;
use CouponsPlus\Original\Events\Handler\EventHandler;

#[\AllowDynamicProperties]
class WelcomePageScriptsHandler extends EventHandler
{
    protected $numberOfArguments = 1;
    protected $priority = 10;

    public function execute(string $hook)
    {
        $screen = get_current_screen();
        
        if (!$screen || !$this->isWelcomePage($hook, $screen)) {
            return;
        }

        $this->enqueueFont();
        $this->enqueueScripts();
    }

    protected function isWelcomePage(string $hook, $screen): bool
    {
        $pageSlug = Env::getWithPrefix('welcome');
        
        return $hook === 'marketing_page_' . $pageSlug;
    }

    protected function enqueueFont()
    {
        wp_enqueue_style(
            Env::getwithPrefix('welcome-font'), 
            'https://fonts.googleapis.com/css2?family=Host+Grotesk:ital,wght@0,100;0,200;0,300;0,400;0,500;0,600;0,700;0,800;0,900;1,100;1,200;1,300;1,400;1,500;1,600;1,700;1,800;1,900&display=swap',
            null,
            '1.0.0'
        );
    }

    protected function enqueueScripts()
    {
        (boolean) $loadProduction = Env::settings()->environment === 'production';
        (string) $welcomeID = Env::getwithPrefix('welcome');

        if ($loadProduction) {
            $this->enqueueProductionScripts($welcomeID);
        } else {
            $this->enqueueDevelopmentScripts($welcomeID);
        }

        wp_localize_script(
            $welcomeID,
            'CouponsPlusWelcome',
            [
                'urls' => [
                    'storage' => Env::directoryURI() . 'storage',
                    'coupons' => esc_url(admin_url('edit.php?post_type=shop_coupon')),
                    'API' => class_exists(\CouponsPlusPro\Original\Environment\Env::class) ? [
                        'activate' => rest_url('coupons-plus/v1/license/activate'),
                        'deactivate' => rest_url('coupons-plus/v1/license/deactivate'),
                        'status' => rest_url('coupons-plus/v1/activation/status'),
                    ] : []
                ],
                'security' => [
                    'nonces' => [
                        'wp' => wp_create_nonce('wp_rest')
                    ]
                ],
                'hasCouponsPlusPro' => class_exists(\CouponsPlusPro\Original\Environment\Env::class),
                'licenseKey' => get_option(Env::getWithPrefix(
                    'license_key'), ''),
            ]
        );
    }

    protected function enqueueProductionScripts(string $welcomeID)
    {
        (object) $assetsData = $this->getAssetsData();
        (object) $mainEntry = $assetsData->get('src/main.tsx');

        if (!$mainEntry) {
            return;
        }

        // Enqueue main CSS from Vite build
        if (property_exists($mainEntry, 'css') && !empty($mainEntry->css)) {
            wp_enqueue_style(
                Env::getwithPrefix('welcome-main'),
                Env::directoryURI() . "app/scripts/welcome/dist/{$mainEntry->css[0]}",
                null,
                '1.0.0'
            );
        }

        // Enqueue main JS from Vite build
        wp_enqueue_script(
            $welcomeID,
            Env::directoryURI() . "app/scripts/welcome/dist/{$mainEntry->file}",
            [],
            '1.0.0',
            true
        );
    }

    protected function enqueueDevelopmentScripts(string $welcomeID)
    {
        if (Env::settings()->environment === 'development') {
            (object) $welcomeDevelopmentScripts = new WelcomeDevelopmentScripts($welcomeID);
            
            $welcomeDevelopmentScripts->render();
        }
    }

    protected function getAssetsData(): Collection
    {
        return new Collection((array) json_decode(
            file_get_contents(Env::getAppDirectory('scripts').'welcome/dist/manifest.json')
        ));
    }
}
