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

namespace ZenoChatbot\Hooks\Handler\Frontend;

use ZenoChatbot\Helper\Settings;
use ZenoChatbot\Hooks\Handler\BaseHandler;
use ZenoChatbot\Framework\Asset\Vite;
use ZenoChatbot\Support\Hooks;

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

/**
 * Handles frontend asset loading and widget rendering
 */
class AssetHandler extends BaseHandler
{
    /**
     * Handle frontend asset loading
     */
    public function handle(...$args)
    {

        if (is_admin()) {
            return;
        }

        // Widget disabled: ship no JS/CSS/config to the page at all
        $chatSettings = Settings::getChatSettings();
        if ((string) ($chatSettings['floating_widget_enabled'] ?? 'yes') !== 'yes') {
            return;
        }

        $this->enqueueAssets();
        $this->localizeScript();
    }

    /**
     * Enqueue frontend assets
     */
    private function enqueueAssets()
    {
        // Enqueue the main public script using Vite
        Vite::enqueue(
            'zeno-chatbot-ai',
            'resources/Public/js/main.js',
            ['wp-element', 'jquery'],
            null,
            true
        );
    }

    /**
     * Localize script with configuration
     */
    private function localizeScript()
    {
        $defaultErrorResponse = Settings::get(
            'general.on_error_response',
            'I apologize, but I encountered an issue processing your request. Please try again or contact our support team if the problem persists.'
        );

        $payload = [
            'ajax_url'     => admin_url('admin-ajax.php'),
            'nonce'       => wp_create_nonce('zenochatbot_nonce'),
            'is_authenticated'  => is_user_logged_in() ? 'yes' : 'no',
            'widget'      => Settings::getWidgetSettings(),
            'error_response' => $defaultErrorResponse,
            'strings'     => [
                'title'       => __('Zeno Chatbot', 'zeno-chatbot-ai'),
                'placeholder' => __('Type your message...', 'zeno-chatbot-ai'),
                'send'        => __('Send', 'zeno-chatbot-ai'),
                'error'       => __('Something went wrong. Please try again.', 'zeno-chatbot-ai'),
                'connecting'  => __('Connecting...', 'zeno-chatbot-ai'),
                'offline'     => __('Chat is currently offline', 'zeno-chatbot-ai'),
            ]
        ];

        $payload = Hooks::applyFilters(Hooks::PUBLIC_WIDGET_CONFIG, $payload);

        wp_localize_script('zeno-chatbot-ai', 'zenoChatbot', $payload);
    }
}
