<?php
namespace HTMegaPro;
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly

 /**
 * Assets Manager
 */
 class HTMega_Scripts{

    private static $instance = null;

    public static function instance() {
        if ( is_null( self::$instance ) ) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    function __construct(){
        $this->init();
    }

    public function init() {
        // Frontend Scripts
        add_action( 'wp_enqueue_scripts', [ $this, 'frontend_scripts' ] );
        // After free/pro script registration; ensure Chart / Lottie / Flip Carousel libraries load in the preview iframe.
        add_action( 'wp_enqueue_scripts', [ $this, 'prepare_elementor_preview_pro_widget_assets' ], 11 );
        add_action( 'elementor/preview/enqueue_scripts', [ $this, 'preview_enqueue_pro_widget_libraries' ], 5 );
        add_action( 'admin_enqueue_scripts', [ $this, 'htmega_pro_admin_scripts'],20 );
        // Elementor Editor Style
        add_action( 'elementor/editor/after_enqueue_styles', [ $this, 'editor_pro_scripts' ] );

    }

    /**
     * Elementor preview iframe only collected scripts from the first paint; imported blocks need echarts / lottie /
     * flipster available before htmega-pro-active runs. Hook at 11 so free HT Mega has registered handles (priority 10).
     * Runs only for {@see htmega_is_elementor_preview_request()} — never on normal visitor page loads.
     */
    public function prepare_elementor_preview_pro_widget_assets() {
        if ( ! $this->is_elementor_preview_request() ) {
            return;
        }
        if ( ! apply_filters( 'htmega_pro_prepare_preview_widget_libraries', true ) ) {
            return;
        }
        $wp_scripts = wp_scripts();
        $bundle     = 'htmega-pro-active';
        $libs       = $this->get_elementor_preview_pro_script_handles();
        foreach ( $libs as $handle ) {
            if ( isset( $wp_scripts->registered[ $handle ] ) && isset( $wp_scripts->registered[ $bundle ] ) ) {
                $wp_scripts->registered[ $bundle ]->deps[] = $handle;
            }
        }
        if ( isset( $wp_scripts->registered[ $bundle ] ) ) {
            $wp_scripts->registered[ $bundle ]->deps = array_values(
                array_unique( array_merge( [ 'jquery' ], $wp_scripts->registered[ $bundle ]->deps ) )
            );
        }
        foreach ( $libs as $handle ) {
            if ( wp_script_is( $handle, 'registered' ) ) {
                wp_enqueue_script( $handle );
            }
        }
        foreach ( $this->get_elementor_preview_pro_style_handles() as $style_handle ) {
            if ( wp_style_is( $style_handle, 'registered' ) ) {
                wp_enqueue_style( $style_handle );
            }
        }
    }

    /**
     * Second pass after Elementor preview core enqueues (priority 20) — keeps Pro widget libraries in the print queue.
     */
    public function preview_enqueue_pro_widget_libraries() {
        if ( ! $this->is_elementor_preview_request() ) {
            return;
        }
        if ( ! apply_filters( 'htmega_pro_prepare_preview_widget_libraries', true ) ) {
            return;
        }
        foreach ( $this->get_elementor_preview_pro_script_handles() as $handle ) {
            if ( wp_script_is( $handle, 'registered' ) ) {
                wp_enqueue_script( $handle );
            }
        }
        foreach ( $this->get_elementor_preview_pro_style_handles() as $style_handle ) {
            if ( wp_style_is( $style_handle, 'registered' ) ) {
                wp_enqueue_style( $style_handle );
            }
        }
    }

    /**
     * @return string[]
     */
    private function get_elementor_preview_pro_script_handles() {
        return apply_filters(
            'htmega_pro_elementor_preview_script_deps',
            [ 'echarts', 'lottie', 'htmega-flipster' ]
        );
    }

    /**
     * @return string[]
     */
    private function get_elementor_preview_pro_style_handles() {
        return apply_filters(
            'htmega_pro_elementor_preview_style_handles',
            [ 'htmega-chart', 'lottie', 'htmega-flipster' ]
        );
    }

    /**
     * True only for the Elementor preview iframe request (shared with HT Mega free: htmega_is_elementor_preview_request).
     */
    private function is_elementor_preview_request() {
        if ( function_exists( 'htmega_is_elementor_preview_request' ) ) {
            return htmega_is_elementor_preview_request();
        }
        if ( ! class_exists( '\Elementor\Plugin', false ) ) {
            return false;
        }
        $preview = \Elementor\Plugin::$instance->preview;

        return $preview && $preview->is_preview_mode();
    }

    /**
     * Enqueue frontend scripts
     */
    public function frontend_scripts() {

        wp_register_style(
            'htmega-pro-global-style',
            HTMEGA_ADDONS_PL_URL_PRO . 'assets/css/htmega-pro-global-style.css',
            [],
            HTMEGA_VERSION_PRO
        );
        wp_register_script(
            'htmega-pro-conditionals-script',
            HTMEGA_ADDONS_PL_URL_PRO . 'assets/js/htmega-pro-conditional.js',
            array( 'jquery' ),
            HTMEGA_VERSION_PRO,
            true
        );

        $htmega_free_version = get_option( 'htmega_elementor_addons_version', '0' );

        if ( version_compare( (string) $htmega_free_version, '2.6.7', '>' ) ) {
            if ( ! \is_plugin_active( 'elementor/elementor.php' ) ) {
                return;
            }

            // Phase 3 (HT Mega Core): defer Pro bundle unless global gate or mega-menu companion applies.
            $allow_global = ! function_exists( 'htmega_should_enqueue_global_assets' ) || htmega_should_enqueue_global_assets();
            $mega_active  = function_exists( 'htmega_has_active_mega_menu' ) && htmega_has_active_mega_menu();

            // Extra Pro widget CSS for editor contexts only — not on slim front-end when gate is off (avoids unused CSS).
            $preview_iframe = function_exists( 'htmega_is_elementor_preview_request' ) && htmega_is_elementor_preview_request();
            $pro_editor_styles_needed = $preview_iframe
                || ( function_exists( 'htmega_is_editing_mode' ) && htmega_is_editing_mode() && ( $allow_global || $mega_active ) );

            if ( $pro_editor_styles_needed ) {
                wp_enqueue_style( 'htmega-pro-widgets-style' );
                foreach ( [ 'htmega-chart', 'lottie', 'htmega-flipster' ] as $pro_style_handle ) {
                    if ( wp_style_is( $pro_style_handle, 'registered' ) ) {
                        wp_enqueue_style( $pro_style_handle );
                    }
                }
            }

            if ( ! $allow_global && ! $mega_active ) {
                // Performance gate: skip full Pro pack on front-end, but the Elementor preview iframe must still
                // load htmega-pro-active or Pro widgets never initialize after import / live edit.
                if ( ! $this->is_elementor_preview_request() ) {
                    return;
                }
            }

            if ( $mega_active && ! $allow_global && function_exists( 'htmega_enqueue_mega_menu_companion_pack' ) ) {
                htmega_enqueue_mega_menu_companion_pack();
            }
        }

        wp_enqueue_script( 'htmega-pro-active' );
        wp_enqueue_style( 'htmega-pro-global-style' );

        $regenerate_elementor_file = get_option( 'htmega_pro_elementor_regenerate_file' );

        if ( ! $regenerate_elementor_file && class_exists( '\Elementor\Plugin' ) && isset( \Elementor\Plugin::$instance->files_manager ) ) {
            \Elementor\Plugin::$instance->files_manager->clear_cache();
            update_option( 'htmega_pro_elementor_regenerate_file', HTMEGA_VERSION_PRO );
        }
    }
    /**
     * Enqueue admin scripts
     */
    public function htmega_pro_admin_scripts() {

        $url_data = array(
            'site_url' => site_url(),
        );
        wp_localize_script( 'htmega-admin', 'site_url_data', $url_data );

    }

    /**
     * [editor_scripts]
     * @return [void] Load Editor Scripts
     */
    public function editor_pro_scripts() {
        wp_enqueue_style('htmega-pro-element-editor', HTMEGA_ADDONS_PL_URL_PRO . 'assets/css/htmega-pro-elementor-editor.css',['elementor-editor'], HTMEGA_VERSION_PRO );
    }
}

HTMega_Scripts::instance();