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

use ShopyPress\Hooks\IHook;
use ShopyPress\Config\Config;
use ShopyPress\Models\ShopyPressProduct;
use ShopyPress\Views\Frontend\ProductSingle;

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('shopypress-admin-settings', SHOPYPRESS_APP_PUBLIC_URL . '/assets/admin/shopypress-settings/dist/index.js', ['jquery'], 'v1', true);
        wp_localize_script('shopypress-admin-settings', 'SHOPYPRESS_ADMIN_SETTINGS', [
            'labels' => [
                'confirmReset' => esc_html__('Are you sure you want to reset the sync? This will stop any work in progress.', 'synckube-products-sync-for-shopify'),
                'fetchCollectionsBtn' => esc_html__('Fetch Collections', 'synckube-products-sync-for-shopify'),
                'fetchingText' => esc_html__('Fetching...', 'synckube-products-sync-for-shopify'),
                'fetchingCollections' => esc_html__('Fetching collections from Shopify...', 'synckube-products-sync-for-shopify'),
                'successText' => esc_html__('Success!', 'synckube-products-sync-for-shopify'),
                'collectionsFetched' => esc_html__('collections fetched.', 'synckube-products-sync-for-shopify'),
                'collectionsSuccess' => esc_html__('collections fetched successfully', 'synckube-products-sync-for-shopify'),
                'fetchError' => esc_html__('Failed to fetch collections', 'synckube-products-sync-for-shopify'),
                'errorText' => esc_html__('Error:', 'synckube-products-sync-for-shopify'),
                'fetchingError' => esc_html__('Error fetching collections', 'synckube-products-sync-for-shopify'),
                'noImage' => esc_html__('No image', 'synckube-products-sync-for-shopify'),
                'noDescription' => esc_html__('No description', 'synckube-products-sync-for-shopify'),
                'importCollection' => esc_html__('Import', 'synckube-products-sync-for-shopify'),
                'collectionSelected' => esc_html__('selected for import', 'synckube-products-sync-for-shopify'),
                'collectionDeselected' => esc_html__('deselected', 'synckube-products-sync-for-shopify'),
                'saveFailed' => esc_html__('Failed to save selection', 'synckube-products-sync-for-shopify'),
                'saveError' => esc_html__('Error saving selection', 'synckube-products-sync-for-shopify'),
                'syncStarted' => esc_html__('Sync started', 'synckube-products-sync-for-shopify'),
                'syncCompleted' => esc_html__('Sync completed successfully', 'synckube-products-sync-for-shopify'),
                'syncError' => esc_html__('Sync error:', 'synckube-products-sync-for-shopify'),
                'autoSyncEnabled' => esc_html__('Auto-sync enabled', 'synckube-products-sync-for-shopify'),
                'autoSyncDisabled' => esc_html__('Auto-sync disabled', 'synckube-products-sync-for-shopify'),
                'productsProcessed' => esc_html__('products processed', 'synckube-products-sync-for-shopify'),
                'of' => esc_html__('of', 'synckube-products-sync-for-shopify'),
            ],
            'urls' => [
                'publicUrl' => SHOPYPRESS_APP_PUBLIC_URL,
            ],
            'ajax_url' => admin_url('admin-ajax.php'),
            'nonce' => wp_create_nonce('shopypress_app_settings_nonce'),
            'shop_domain' => \ShopyPress\Utils\OptionUtils::getInstance()->getOption('shop_domain', ''),
            'selected_collections' => \ShopyPress\Utils\OptionUtils::getInstance()->getOption('selected_collections', []),
        ]);

        wp_enqueue_script('shopypress-admin-settings');
        wp_enqueue_style('shopypress-admin-settings', SHOPYPRESS_APP_PUBLIC_URL . '/assets/admin/shopypress-settings/dist/index.css', NULL, 'v1');


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

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

	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);
    }

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

        $hasOwnShortcodes = isset($post->post_content) && strpos( $post->post_content, '[synckube_all_products_grid' ) !== false;
        $isProductSingle = is_singular(ShopyPressProduct::PRODUCT_SLUG);
        if ( $hasOwnShortcodes || $isProductSingle) {

            wp_enqueue_script('jquery');

            // Enqueue Swiper JS
            wp_enqueue_script(
                'shopypress-swiper',
                SHOPYPRESS_APP_PUBLIC_URL . '/app/Views/Frontend/assets/vendor/swiper/swiper_11.2.10.js',
                [],
                '11.0.0',
                true
            );

            // Enqueue ShopyPress JS
            wp_enqueue_script(
                'shopypress-js-app',
                SHOPYPRESS_APP_PUBLIC_URL . '/app/Views/Frontend/assets/dist/index.js',
                ['jquery', 'shopypress-swiper'],
                '1.0.0',
                true
            );

            // // Enqueue Swiper CSS
            wp_enqueue_style('shopypress-swiper', SHOPYPRESS_APP_PUBLIC_URL . '/app/Views/Frontend/assets/vendor/swiper/swiper_11.2.10.css', [], '11.2.10');
            wp_enqueue_style('shopypress-css', SHOPYPRESS_APP_PUBLIC_URL . '/app/Views/Frontend/assets/dist/index.css', ['shopypress-swiper'], '1.0.0');

            if ($isProductSingle) {
                // Get product ID
                $product_id = get_the_ID();

                // Retrieve all product meta data
                $product_data = ProductSingle::getProductData($product_id);
                // Prepare product data for JavaScript
                $js_product_data = [
                    'id' => $product_data['id'],
                    'title' => $product_data['title'],
                    'images' => ProductSingle::prepareGalleryImages($product_data),
                    'options' => $product_data['options'],
                    'priceMin' => $product_data['price_min'],
                    'priceMax' => $product_data['price_max'],
                ];
                wp_localize_script('shopypress-js-app', 'shopyPressProductData', $js_product_data);
            }
            
            // Enqueue Shopify Web Components library on all pages
            // This enables cart functionality site-wide
            wp_enqueue_script(
                'shopify-web-components',
                'https://cdn.shopify.com/storefront/web-components.js',
                [],
                null,  // Shopify manages versioning
                true   // Load in footer
            );

            wp_enqueue_style('shopypress-cart-css', SHOPYPRESS_APP_PUBLIC_URL . '/app/Views/Frontend/assets/dist/cart.css', [], '1.0.0');
        }
    }
}