<?php
namespace FuseCommerce\Hooks;
if ( ! defined( 'ABSPATH' ) ) exit;

use FuseCommerce\Hooks\IHook;
use FuseCommerce\Config\Config;
use FuseCommerce\Models\IndexingState;

class ActionEnqueueScripts implements IHook {

    static function register() {
        add_action('admin_enqueue_scripts', [self::class, 'loadAdminScripts']);
        add_action('wp_enqueue_scripts', [self::class, 'loadFrontendAssets']);
    }

    static function loadAdminScripts() {
        $current_screen = get_current_screen();
        $isAdminSettingsPage = $current_screen->id === 'toplevel_page_' . Config::getInstance()->getSetting('main_settings_page_slug');

        
        if ($isAdminSettingsPage) {
            wp_enqueue_script('jquery');
            wp_enqueue_script('jquery-ui-sortable'); // jQuery UI Sortable for drag-drop
            self::loadAdminAssets();
            self::loadBootstrap();
        }
    }

    private static function loadAdminAssets() {
        wp_register_script('fusecom-admin-settings', FUSE_COM_APP_PUBLIC_URL . '/assets/admin/fuse-settings/dist/index.js', ['jquery'], 'v1', true);
        wp_localize_script('fusecom-admin-settings', 'FUSE_COM_ADMIN_SETTINGS', [
            'labels' => [
                'confirmReset' => esc_html__('Are you sure you want to reset the indexing process? This will delete any work in progress.', 'ftlcommerce-instant-product-search'),
                'indexingStarted' => esc_html__('Indexing started successfully', 'ftlcommerce-instant-product-search'),
                'indexingComplete' => esc_html__('Indexing completed successfully', 'ftlcommerce-instant-product-search'),
                'indexingReset' => esc_html__('Indexing process reset successfully', 'ftlcommerce-instant-product-search'),
                'failedToLoad' => esc_html__('Failed to load indexing status', 'ftlcommerce-instant-product-search'),
                'failedToStart' => esc_html__('Failed to start indexing', 'ftlcommerce-instant-product-search'),
                'failedToReset' => esc_html__('Failed to reset indexing', 'ftlcommerce-instant-product-search'),
                'errorStarting' => esc_html__('Error starting indexing', 'ftlcommerce-instant-product-search'),
                'errorResetting' => esc_html__('Error resetting indexing', 'ftlcommerce-instant-product-search'),
                'statusNoProcess' => esc_html__('No indexing process running', 'ftlcommerce-instant-product-search'),
                'statusLastIndex' => esc_html__('Last index was generated previously', 'ftlcommerce-instant-product-search'),
                'statusInProgress' => esc_html__('Indexing in progress', 'ftlcommerce-instant-product-search'),
                'statusCompleted' => esc_html__('Indexing completed successfully', 'ftlcommerce-instant-product-search'),
                'statusError' => esc_html__('Error occurred during indexing', 'ftlcommerce-instant-product-search'),
                'labelStatus' => esc_html__('Status:', 'ftlcommerce-instant-product-search'),
                'labelPhase' => esc_html__('Phase:', 'ftlcommerce-instant-product-search'),
                'labelProgress' => esc_html__('Progress:', 'ftlcommerce-instant-product-search'),
                'labelTotalProducts' => esc_html__('Total Products:', 'ftlcommerce-instant-product-search'),
                'labelStarted' => esc_html__('Started:', 'ftlcommerce-instant-product-search'),
                'labelCompleted' => esc_html__('Completed:', 'ftlcommerce-instant-product-search'),
                'labelErrors' => esc_html__('Errors:', 'ftlcommerce-instant-product-search'),
                'phaseCategories' => esc_html__('Categories & Attributes', 'ftlcommerce-instant-product-search'),
                'phaseProducts' => esc_html__('Products', 'ftlcommerce-instant-product-search'),
                'warningStale' => esc_html__('Warning: Process appears stale (no updates for over 1 hour)', 'ftlcommerce-instant-product-search'),
                'products' => esc_html__('products', 'ftlcommerce-instant-product-search'),
                'confirmRefresh' => esc_html__('This will reload the configuration from index data. Any unsaved changes will be lost. Continue?', 'ftlcommerce-instant-product-search'),
                'configRefreshed' => esc_html__('Configuration refreshed from index data', 'ftlcommerce-instant-product-search'),
                'noIndexData' => esc_html__('Please run indexing first to configure filters.', 'ftlcommerce-instant-product-search'),
                'errorLoading' => esc_html__('Error loading filter configuration', 'ftlcommerce-instant-product-search'),
                'showInFrontend' => esc_html__('Show in Frontend', 'ftlcommerce-instant-product-search'),
                'typeCategory' => esc_html__('Category', 'ftlcommerce-instant-product-search'),
                'typeTag' => esc_html__('Tag', 'ftlcommerce-instant-product-search'),
                'typeAttribute' => esc_html__('Attribute', 'ftlcommerce-instant-product-search'),
                'typePrice' => esc_html__('Price', 'ftlcommerce-instant-product-search'),
            ],
            'urls' => [
                'publicUrl' => FUSE_COM_APP_PUBLIC_URL,
            ],
            'ajax_url' => admin_url('admin-ajax.php'),
            'nonce' => wp_create_nonce('fusecomm_app_settings_nonce'),
        ]);

        wp_enqueue_script('fusecom-admin-settings');
        wp_enqueue_style('fusecom-admin-settings', FUSE_COM_APP_PUBLIC_URL . '/assets/admin/fuse-settings/dist/index.css', NULL, 'v1');


        wp_enqueue_script('oxyleaf-toastr', FUSE_COM_APP_PUBLIC_URL . '/assets/vendor/toastr/toastr.min.js', ['fusecom-admin-settings'], 'v1', true);
        wp_enqueue_style('oxyleaf-toastr', FUSE_COM_APP_PUBLIC_URL . '/assets/vendor/toastr/toastr.min.css', ['fusecom-admin-settings'], 'v1');
    }

    private static function loadBootstrap() {
        wp_enqueue_script('fusecomm-bootstrap', FUSE_COM_APP_PUBLIC_URL . '/assets/vendor/bootstrap/bootstrap.min.js', NULL, 'v1', true);
        wp_enqueue_style('fusecomm-bootstrap', FUSE_COM_APP_PUBLIC_URL . '/assets/vendor/bootstrap/bootstrap.min.css', NULL, 'v1');
    }

    static function loadFrontendAssets() {
        // Only enqueue on pages that contain our shortcode (simple approach)
        global $post;

        if ( isset( $post->post_content ) && strpos( $post->post_content, '[ftlcommerce' ) !== false ) {
            
            $is_woocommerce_active = is_plugin_active('woocommerce/woocommerce.php');
            if (!$is_woocommerce_active) {
                return;
            }

            wp_enqueue_script('jquery');
            wp_enqueue_script('fuse-latest-js', FUSE_COM_APP_PUBLIC_URL . '/app/Views/Frontend/assets/vendor/fuse.js@7.1.0.js', [], '6.6.2', true );
            wp_enqueue_script('fuse-commerce-search', FUSE_COM_APP_PUBLIC_URL . '/app/Views/Frontend/assets/dist/index.js', ['fuse-latest-js', 'jquery'], '1.0.0', true );

            // Get currency settings from indexing state
            $currencySettings = IndexingState::getCurrencySettings();

            wp_localize_script('fuse-commerce-search', 'FuseCommerceSearch', array(
                'rest_url'         => esc_url_raw( rest_url( 'fuse-commerce/v1' ) ),
                'currency_settings' => $currencySettings,
                'labels'           => \FuseCommerce\Views\Frontend\CommerceView::getFeLabels()
            ) );
            wp_enqueue_style('fuse-commerce-search', FUSE_COM_APP_PUBLIC_URL . '/app/Views/Frontend/assets/dist/index.css', [], '1.0.0' );
        }
    }

    
	static function enqueRemoteStyle($key, $url, $version = 'v1'): void {
        $protocol = is_ssl() ? 'https' : 'http';
        wp_enqueue_style($key, $protocol . $url, NULL, $version);
    }

	static function enqueRemoteScript($key, $url, array $dependencies = [], string $version = 'v1', bool $inFooter = true): void {
        $protocol = is_ssl() ? 'https' : 'http';
        wp_enqueue_script($key, $protocol . $url, $dependencies, $version, $inFooter);
    }
}