<?php
/**
 * Admin Asset Handler
 *
 * @package ZenoChatbot\Hooks\Handler\Admin
 */

namespace ZenoChatbot\Hooks\Handler\Admin;

use ZenoChatbot\App;
use ZenoChatbot\Framework\Asset\Vite;
use ZenoChatbot\Hooks\Handler\BaseHandler;
use ZenoChatbot\Support\Hooks;

// Prevent direct access
if (!defined('ABSPATH')) {
    exit;
}

/**
 * Handles admin asset loading and localization
 */
class AssetHandler extends BaseHandler
{
    /**
     * Handle admin asset loading
     */
    public function handle(...$args)
    {
        $hook = $args[0] ?? '';

        // Only load on our admin pages
        if (strpos($hook, 'zeno-chatbot-ai') === false) {
            return;
        }

        $this->enqueueAdminAssets();
    }

    private function enqueueAdminAssets(): void
    {
        $this->enqueueExtensionSdk();

        Vite::enqueue(
            'zeno-chatbot-ai-admin',
            'resources/Admin/js/main.js',
            ['wp-element', 'zeno-chatbot-ai-ext-sdk'],
            false
        );

        $this->localizeAdminScript();
        $this->enqueueExtensionScripts();
    }

    private function enqueueExtensionSdk(): void
    {
        $sdkPath = ZENOCHATBOT_PLUGIN_DIR . 'assets/admin/js/extension-sdk.js';
        $sdkUrl  = ZENOCHATBOT_PLUGIN_URL . 'assets/admin/js/extension-sdk.js';
        $version = file_exists($sdkPath) ? (string) filemtime($sdkPath) : $this->app->version();

        wp_enqueue_script('zeno-chatbot-ai-ext-sdk', $sdkUrl, [], $version, true);
    }

    private function enqueueExtensionScripts(): void
    {
        $scripts = Hooks::applyFilters(Hooks::ADMIN_EXTENSION_SCRIPTS, []);

        foreach ($scripts as $script) {
            if (empty($script['handle']) || empty($script['src'])) {
                continue;
            }

            wp_enqueue_script(
                $script['handle'],
                $script['src'],
                ['zeno-chatbot-ai-ext-sdk', 'zeno-chatbot-ai-admin'],
                $script['version'] ?? $this->app->version(),
                true
            );

            $handle = $script['handle'];
            add_filter('script_loader_tag', static function ($tag, $tagHandle) use ($handle) {
                if ($tagHandle === $handle) {
                    return str_replace('<script ', '<script type="module" ', $tag);
                }
                return $tag;
            }, 10, 2);

            foreach ($script['css'] ?? [] as $index => $cssUrl) {
                wp_enqueue_style(
                    $handle . '-style-' . $index,
                    $cssUrl,
                    [],
                    $script['version'] ?? $this->app->version()
                );
            }
        }
    }

    /**
     * Localize admin runtime payload.
     * @return void
     */
    private function localizeAdminScript(): void
    {
        $countries = App::config('countries', []);
        $countries = Hooks::applyFilters(Hooks::SETTINGS_COUNTRIES, $countries);

        $extensions = Hooks::applyFilters(Hooks::ADMIN_EXTENSIONS, []);

        $extensionFields = Hooks::applyFilters(Hooks::ADMIN_EXTENSION_FIELDS, []);

        wp_localize_script('zeno-chatbot-ai-admin', 'zenochatbot_admin', [
            'api_url' => rest_url('zeno-chatbot-ai/v1/'),
            'nonce' => wp_create_nonce('wp_rest'),
            'ajax_url' => admin_url('admin-ajax.php'),
            'ajax_nonce' => wp_create_nonce('zenochatbot_admin'),
            'strings' => $this->app->config('str', []),
            'version' => $this->app->version(),
            'languages' => $countries,
            'timezone' => wp_timezone_string(),
            'extensions' => $extensions,
            'extension_fields' => $extensionFields,
            'is_pro' => Hooks::applyFilters(Hooks::ADMIN_IS_PRO, false),
        ]);
    }
}
