<?php

namespace MovieEngine\Frontend;

if (! defined("ABSPATH")) {
    exit; // Exit if accessed directly
}

class Assets {

    private $plugin_name;
    private $version;
    private $player_library;

    public function __construct() {
        $this->plugin_name = 'movie-engine';
        $this->version     = MOVIE_ENGINE_VERSION;

        $player_settings = get_option('movie_engine_player_settings', []);
        $this->player_library = $player_settings['movie_engine_player_library'] ?? ($player_settings['player_library'] ?? 'plyr');
        add_action('wp_enqueue_scripts', [$this, 'enqueue_styles']);
        add_action('wp_enqueue_scripts', [$this, 'enqueue_scripts']);
        add_action('wp_head', [$this, 'silence_jquery_migrate'], 1);
        add_filter('body_class', [$this, 'add_body_class']);
    }

    public function silence_jquery_migrate() {
        echo '<script type="text/javascript">window.jQuery && (window.jQuery.migrateMute = true);</script>';
    }

    private function get_player_library() {
        $is_pro = apply_filters('movie_engine_is_pro', false);
        if (!$is_pro && in_array($this->player_library, ['shaka', 'clappr', 'artplayer'])) {
            return 'plyr';
        }
        return $this->player_library;
    }



    /**
     * Add movie-engine-page class to body
     */
    public function add_body_class($classes) {
        $classes[] = 'movie-engine-plugin';

        $post_type = get_post_type();
        if ($post_type && strpos($post_type, 'movie_engine_') === 0) {
            $type_slug = str_replace('_', '-', str_replace('movie_engine_', '', $post_type));
            $classes[] = 'movie-engine-' . $type_slug;

            if (is_singular()) {
                $classes[] = 'movie-engine-single';
            } elseif (is_post_type_archive()) {
                $classes[] = 'movie-engine-archive';
            }
        }

        if (is_singular() && $post_type && strpos($post_type, 'movie_engine_') === false) {
            global $post;
            if (isset($post->post_content)) {
                if (preg_match_all('/\[(movie_engine_[^\] ]+)/', $post->post_content, $matches)) {
                    $classes[] = 'movie-engine-shortcode-page';
                    foreach ($matches[1] as $shortcode) {
                        $shortcode_slug = str_replace('_', '-', str_replace('movie_engine_', '', $shortcode));
                        $classes[] = 'movie-engine-shortcode-' . $shortcode_slug;
                    }
                }
            }
        }

        if (is_tax()) {
            $taxonomy = get_query_var('taxonomy');
            if (strpos($taxonomy, 'movie_engine_') === 0) {
                $tax_slug = str_replace('_', '-', str_replace('movie_engine_', '', $taxonomy));
                $classes[] = 'movie-engine-tax-' . $tax_slug;
                $classes[] = 'movie-engine-taxonomy';
            }
        }

        return array_unique($classes);
    }

    public function enqueue_styles() {
        wp_enqueue_style('dashicons');
        wp_enqueue_style('movie-engine-font-body', 'https://fonts.googleapis.com/css2?family=Inter:ital,opsz,wght@0,14..32,100..900;1,14..32,100..900&display=swap', [], MOVIE_ENGINE_VERSION);
        wp_enqueue_style('movie-engine-font-heading', 'https://fonts.googleapis.com/css2?family=Sora:wght@100..800&display=swap', [], MOVIE_ENGINE_VERSION);
        wp_enqueue_style('movie-engine-fontawesome', MOVIE_ENGINE_URL . 'assets/fonts/fontawesome.min.css', [], $this->version);

        $css_deps = [];

        switch ($this->get_player_library()) {
            case 'clappr':
                break;

            case 'shaka':
                break;

            case 'artplayer':
                break;

            case 'plyr':
            default:
                wp_enqueue_style('plyr-css', MOVIE_ENGINE_URL . 'assets/css/vendor/plyr/plyr.min.css', [], '3.7.8');
                $css_deps[] = 'plyr-css';
                break;
        }

        wp_enqueue_style($this->plugin_name, MOVIE_ENGINE_URL . 'assets/css/frontend/movie-engine-frontend.min.css', $css_deps, $this->version, 'all');

        $upload_dir = wp_upload_dir();
        $cache_file_path = trailingslashit($upload_dir['basedir']) . 'movie-engine/custom-style.css';
        $cache_url = set_url_scheme(trailingslashit($upload_dir['baseurl']) . 'movie-engine/custom-style.css');
        $cache_ver = get_option('movie_engine_css_cache_version', $this->version);

        if (\MovieEngine\Core\Cache::is_enabled() && file_exists($cache_file_path)) {
            wp_enqueue_style($this->plugin_name . '-custom', $cache_url, [$this->plugin_name], $cache_ver);
        } else {
            $design_settings = get_option('movie_engine_design_settings', []);
            $custom_css = \MovieEngine\Core\Cache::generate_design_css($design_settings);

            if (!empty($custom_css)) {
                wp_add_inline_style($this->plugin_name, $custom_css);
            }
        }
    }

    /**
     * Register frontend CSS for the library block editor preview. Must run during register_block_type()
     * (e.g. on init), not on enqueue_block_assets priority 20: WordPress enqueues block editor_style at
     * enqueue_block_assets priority 10, so the main stylesheet must already be registered as a dependency.
     *
     * Uses handles separate from the public `movie-engine` bundle to avoid conflicting deps (e.g. Plyr).
     *
     * @return string Leaf style handle (`movie-engine-editor-custom` or `movie-engine-editor-main`).
     */
    public static function register_block_editor_preview_styles(): string
    {
        $version = MOVIE_ENGINE_VERSION;

        if (!wp_style_is('movie-engine-font-body', 'registered')) {
            wp_register_style('movie-engine-font-body', 'https://fonts.googleapis.com/css2?family=Inter:ital,opsz,wght@0,14..32,100..900;1,14..32,100..900&display=swap', [], $version);
        }
        if (!wp_style_is('movie-engine-font-heading', 'registered')) {
            wp_register_style('movie-engine-font-heading', 'https://fonts.googleapis.com/css2?family=Sora:wght@100..800&display=swap', [], $version);
        }
        if (!wp_style_is('movie-engine-fontawesome', 'registered')) {
            wp_register_style('movie-engine-fontawesome', MOVIE_ENGINE_URL . 'assets/fonts/fontawesome.min.css', [], $version);
        }

        $main_deps = ['dashicons', 'wp-block-library', 'movie-engine-font-body', 'movie-engine-font-heading', 'movie-engine-fontawesome'];

        wp_register_style(
            'movie-engine-editor-main',
            MOVIE_ENGINE_URL . 'assets/css/frontend/movie-engine-frontend.min.css',
            $main_deps,
            $version,
            'all'
        );
        wp_add_inline_style('movie-engine-editor-main', '.wp-block-cine-movie-engine-library,.wp-block-cine-movie-engine-search-bar,.wp-block-cine-movie-engine-grid,.wp-block-cine-movie-engine-search,.wp-block-cine-movie-engine-hero,.wp-block-cine-movie-engine-live-search,.wp-block-cine-movie-engine-person-list,.wp-block-cine-movie-engine-user-menu,.wp-block-cine-movie-engine-taxonomies{min-width:0;}');

        $upload_dir = wp_upload_dir();
        $cache_file_path = trailingslashit($upload_dir['basedir']) . 'movie-engine/custom-style.css';
        $cache_url = set_url_scheme(trailingslashit($upload_dir['baseurl']) . 'movie-engine/custom-style.css');
        $cache_ver = get_option('movie_engine_css_cache_version', $version);

        if (\MovieEngine\Core\Cache::is_enabled() && file_exists($cache_file_path)) {
            wp_register_style('movie-engine-editor-custom', $cache_url, ['movie-engine-editor-main'], $cache_ver);

            return 'movie-engine-editor-custom';
        }

        $design_settings = get_option('movie_engine_design_settings', []);
        $custom_css = \MovieEngine\Core\Cache::generate_design_css($design_settings);

        if (!empty($custom_css)) {
            wp_add_inline_style('movie-engine-editor-main', $custom_css);
        }

        return 'movie-engine-editor-main';
    }

    public function enqueue_scripts() {
        $player_settings = get_option('movie_engine_player_settings', []);
        $js_deps = ['jquery'];

        switch ($this->get_player_library()) {
            case 'clappr':
                break;

            case 'shaka':
                break;

            case 'artplayer':
                break;

            case 'plyr':
            default:
                wp_enqueue_script('hls-js', MOVIE_ENGINE_URL . 'assets/js/vendor/plyr/hls.min.js', [], '1.5.8', true);
                wp_enqueue_script('plyr-js', MOVIE_ENGINE_URL . 'assets/js/vendor/plyr/plyr.min.js', [], '3.7.8', true);
                $js_deps[] = 'plyr-js';
                $js_deps[] = 'hls-js';
                break;
        }

        $monetization_settings = get_option('movie_engine_monetization_settings', []);
        $video_settings = get_option('movie_engine_monetization_video_settings', []);
        $monetization_settings = array_merge($video_settings, $monetization_settings);

        $is_admin = current_user_can('manage_options');
        $is_premium = \MovieEngine\Payments\Membership::is_premium();
        $ads_enabled = isset($monetization_settings['movie_engine_enable_video_ads'])
            ? (string) $monetization_settings['movie_engine_enable_video_ads'] === '1'
            : (isset($monetization_settings['enable_video_ads']) && (string) $monetization_settings['enable_video_ads'] === '1');

        if ($ads_enabled) {
            $show_for_admin = !empty($monetization_settings['movie_engine_show_ads_for_admin']) || !empty($monetization_settings['show_ads_for_admin']);

            if ($is_premium || ($is_admin && !$show_for_admin)) {
                $ads_enabled = false;
            }
        }

        if ($ads_enabled) {
            wp_enqueue_script('google-ima-sdk', 'https://imasdk.googleapis.com/js/sdkloader/ima3.js', [], '3.0', true);
            $js_deps[] = 'google-ima-sdk';

            wp_add_inline_script('google-ima-sdk', "
                (function() {
                    function setVpaidMode() {
                        if (typeof google !== 'undefined' && google.ima && google.ima.settings && google.ima.ImaSdkSettings && google.ima.ImaSdkSettings.VpaidMode) {
                            try { google.ima.settings.setVpaidMode(google.ima.ImaSdkSettings.VpaidMode.INSECURE); } catch(e) {}
                            return true;
                        }
                        return false;
                    }
                    if (!setVpaidMode()) {
                        var check = setInterval(function() { if (setVpaidMode()) clearInterval(check); }, 50);
                        setTimeout(function() { clearInterval(check); }, 3000);
                    }
                })();
            ", 'after');
        }

        wp_enqueue_script(
            $this->plugin_name . '-selectors',
            MOVIE_ENGINE_URL . 'assets/js/frontend/me-selectors.min.js',
            [],
            $this->version,
            true
        );

        $js_deps[] = $this->plugin_name . '-selectors';
        $main_js_path = MOVIE_ENGINE_PATH . 'assets/js/frontend/movie-engine-frontend.min.js';
        $main_js_ver = file_exists($main_js_path) ? filemtime($main_js_path) : $this->version;
        wp_enqueue_script($this->plugin_name, MOVIE_ENGINE_URL . 'assets/js/frontend/movie-engine-frontend.min.js', $js_deps, $main_js_ver, true);

        wp_enqueue_script($this->plugin_name . '-slider-nav', MOVIE_ENGINE_URL . 'assets/js/frontend/slider-navigation.min.js', ['jquery', $this->plugin_name], $this->version, true);

        wp_enqueue_script($this->plugin_name . '-filters', MOVIE_ENGINE_URL . 'assets/js/frontend/advanced-filters.min.js', ['jquery', $this->plugin_name], $this->version, true);
        if (is_singular('movie_engine_person')) {
            wp_add_inline_script($this->plugin_name, "
            jQuery(function($) {
                var \$bio = $('#person-bio');
                var \$readMoreBtn = $('#me-read-more-btn');
                
                if (\$bio.length && \$readMoreBtn.length) {
                    var checkBioHeight = function() {
                        if (\$bio[0].scrollHeight > 160) {
                            \$readMoreBtn.css('display', 'inline-block');
                        }
                    };
                    checkBioHeight();
                    setTimeout(checkBioHeight, 500);

                    \$readMoreBtn.on('click', function(e) {
                        e.preventDefault();
                        \$bio.toggleClass('expanded');
                        var readMoreText = \$readMoreBtn.attr('data-read-more') || 'Read More';
                        var readLessText = \$readMoreBtn.attr('data-read-less') || 'Read Less';
                        \$readMoreBtn.text(\$bio.hasClass('expanded') ? readLessText : readMoreText);
                    });
                }

                $(document).on('click', '.me-history-tabs .me-tab-btn', function (e) {
                    e.preventDefault();
                    var \$tab = \$(this);
                    var filter = \$tab.attr('data-filter');

                    $('.me-history-tabs .me-tab-btn').removeClass('active');
                    \$tab.addClass('active');

                    if (filter === 'all') {
                        $('.me-person-history-card').fadeIn(300);
                    } else {
                        $('.me-person-history-card').hide();
                        $('.me-person-history-card[data-type=\"' + filter + '\"]').fadeIn(300);
                    }
                });
            });
            ", 'after');
        }

        $fresh_midroll_offset = isset($monetization_settings['movie_engine_midroll_offset']) && $monetization_settings['movie_engine_midroll_offset'] !== ''
            ? intval($monetization_settings['movie_engine_midroll_offset'])
            : (isset($monetization_settings['midroll_offset']) && $monetization_settings['midroll_offset'] !== ''
                ? intval($monetization_settings['midroll_offset'])
                : 300);
        $fresh_midroll_repeat = isset($monetization_settings['movie_engine_midroll_repeat']) && $monetization_settings['movie_engine_midroll_repeat'] !== ''
            ? intval($monetization_settings['movie_engine_midroll_repeat'])
            : (isset($monetization_settings['midroll_repeat']) && $monetization_settings['midroll_repeat'] !== ''
                ? intval($monetization_settings['midroll_repeat'])
                : 1);
        $fresh_skip_offset = isset($monetization_settings['movie_engine_skip_offset']) && $monetization_settings['movie_engine_skip_offset'] !== ''
            ? intval($monetization_settings['movie_engine_skip_offset'])
            : (isset($monetization_settings['skip_offset']) && $monetization_settings['skip_offset'] !== ''
                ? intval($monetization_settings['skip_offset'])
                : 5);

        $current_user = wp_get_current_user();
        $user_data = null;
        if ($current_user->ID > 0) {
            $user_data = [
                'id' => $current_user->ID,
                'display_name' => $current_user->display_name,
                'email' => $current_user->user_email,
                'username' => $current_user->user_login,
            ];
        }


        wp_localize_script($this->plugin_name, 'movieEngineDashboard', apply_filters('movie_engine_dashboard_data', [
            'ajax_url' => esc_url(admin_url('admin-ajax.php')),
            'saving_text' => esc_html__('Saving...', 'cine-movie-engine'),
            'save_text' => esc_html__('Save All Changes', 'cine-movie-engine'),
            'login_url' => wp_login_url(get_permalink()),
            'logged_in' => is_user_logged_in(),
            'nonce' => wp_create_nonce('movie-engine-nonce'),
        ]));

        wp_localize_script($this->plugin_name, 'movieEngineData', apply_filters('movie_engine_frontend_data', [
            'ajax_url' => esc_url(admin_url('admin-ajax.php')),
            'rest_url' => get_rest_url(null, 'movie-engine/v1/'),
            'stream_url' => get_rest_url(null, 'movie-engine/v1/stream/'),
            'nonce'    => wp_create_nonce('movie_engine_nonce'),
            'rest_nonce' => wp_create_nonce('wp_rest'),
            'user'     => $user_data,
            'is_premium' => \MovieEngine\Payments\Membership::is_premium(),
            'poster'   => is_singular(['movie_engine_movie', 'movie_engine_series', 'movie_engine_episode']) ? get_the_post_thumbnail_url(get_the_ID(), 'full') : '',
            'video_ads' => [
                'enabled' => $ads_enabled,
                'ad_status' => $ads_enabled ? 'Ready' : ($is_premium ? 'Disabled (Premium User)' : ($is_admin ? 'Disabled (Administrator)' : 'Disabled')),
                'vast_tag_url' => $monetization_settings['movie_engine_vast_tag_url'] ?? ($monetization_settings['vast_tag_url'] ?? ''),
                'preroll' => isset($monetization_settings['movie_engine_enable_preroll']) ? !empty($monetization_settings['movie_engine_enable_preroll']) : !empty($monetization_settings['enable_preroll']),
                'midroll' => isset($monetization_settings['movie_engine_enable_midroll']) ? !empty($monetization_settings['movie_engine_enable_midroll']) : !empty($monetization_settings['enable_midroll']),
                'midroll_offset' => $fresh_midroll_offset,
                'midroll_repeat' => $fresh_midroll_repeat,
                'postroll' => isset($monetization_settings['movie_engine_enable_postroll']) ? !empty($monetization_settings['movie_engine_enable_postroll']) : !empty($monetization_settings['enable_postroll']),
                'skip_offset' => $fresh_skip_offset,
                'mute_ads' => isset($monetization_settings['movie_engine_mute_ads']) ? !empty($monetization_settings['movie_engine_mute_ads']) : !empty($monetization_settings['mute_ads']),
                'force_multiple_ads' => isset($monetization_settings['movie_engine_force_multiple_ads']) ? !empty($monetization_settings['movie_engine_force_multiple_ads']) : !empty($monetization_settings['force_multiple_ads']),
            ],
            // 'i18n' merged below
            'player_settings' => [
                'player_library' => $this->get_player_library(),
                'autoplay' => isset($player_settings['movie_engine_autoplay']) ? !empty($player_settings['movie_engine_autoplay']) : !empty($player_settings['autoplay']),
                'autoplay_next' => (isset($player_settings['movie_engine_autoplay_next']) ? !empty($player_settings['movie_engine_autoplay_next']) : !empty($player_settings['autoplay_next'])) ? 1 : 0,
                'next_ep_countdown' => isset($player_settings['movie_engine_next_ep_countdown']) ? intval($player_settings['movie_engine_next_ep_countdown']) : (isset($player_settings['next_ep_countdown']) ? intval($player_settings['next_ep_countdown']) : 10),
                'show_next_ep_card' => isset($player_settings['movie_engine_show_next_ep_card']) ? !empty($player_settings['movie_engine_show_next_ep_card']) : !empty($player_settings['show_next_ep_card']),
                'next_ep_card_time' => isset($player_settings['movie_engine_next_ep_card_time']) ? intval($player_settings['movie_engine_next_ep_card_time']) : (isset($player_settings['next_ep_card_time']) ? intval($player_settings['next_ep_card_time']) : 10),
                'auto_mark_watched' => isset($player_settings['movie_engine_auto_mark_watched']) ? !empty($player_settings['movie_engine_auto_mark_watched']) : !empty($player_settings['auto_mark_watched']),
                'resume_playback' => isset($player_settings['movie_engine_resume_playback']) ? !empty($player_settings['movie_engine_resume_playback']) : !empty($player_settings['resume_playback']),
                'default_volume' => isset($player_settings['movie_engine_default_volume']) ? intval($player_settings['movie_engine_default_volume']) / 100 : (isset($player_settings['default_volume']) ? intval($player_settings['default_volume']) / 100 : 0.8),
                'mute_on_start' => isset($player_settings['movie_engine_mute_on_start']) ? !empty($player_settings['movie_engine_mute_on_start']) : !empty($player_settings['mute_on_start']),
                'controls_timeout' => isset($player_settings['movie_engine_controls_timeout']) ? intval($player_settings['movie_engine_controls_timeout']) : (isset($player_settings['controls_timeout']) ? intval($player_settings['controls_timeout']) : 3),
                'keyboard_shortcuts' => isset($player_settings['movie_engine_keyboard_shortcuts']) ? !empty($player_settings['movie_engine_keyboard_shortcuts']) : !empty($player_settings['keyboard_shortcuts']),
                'theater_mode' => isset($player_settings['movie_engine_theater_mode']) ? !empty($player_settings['movie_engine_theater_mode']) : !empty($player_settings['theater_mode']),
                'pip_mode' => (isset($player_settings['movie_engine_pip_mode']) ? !empty($player_settings['movie_engine_pip_mode']) : !empty($player_settings['pip_mode'])) && (empty($player_settings['movie_engine_disable_pip_security']) && empty($player_settings['disable_pip_security'])),
                'mini_player' => isset($player_settings['movie_engine_mini_player']) ? !empty($player_settings['movie_engine_mini_player']) : !empty($player_settings['mini_player']),
                'download_button' => isset($player_settings['movie_engine_download_button']) ? !empty($player_settings['movie_engine_download_button']) : !empty($player_settings['download_button']),
                'enable_quality_selector' => isset($player_settings['movie_engine_enable_quality_selector']) ? !empty($player_settings['movie_engine_enable_quality_selector']) : !empty($player_settings['enable_quality_selector']),
                'default_quality' => $player_settings['movie_engine_default_quality'] ?? ($player_settings['default_quality'] ?? 'auto'),
                'auto_quality' => isset($player_settings['movie_engine_auto_quality']) ? !empty($player_settings['movie_engine_auto_quality']) : !empty($player_settings['auto_quality']),
                'enable_subtitles' => isset($player_settings['movie_engine_enable_subtitles']) ? !empty($player_settings['movie_engine_enable_subtitles']) : !empty($player_settings['enable_subtitles']),
                'default_subtitle_lang' => $player_settings['movie_engine_default_subtitle_lang'] ?? ($player_settings['default_subtitle_lang'] ?? 'en'),
                'subtitle_state' => $player_settings['movie_engine_subtitle_state'] ?? ($player_settings['subtitle_state'] ?? 'off'),
                'subtitle_size' => $player_settings['movie_engine_subtitle_size'] ?? ($player_settings['subtitle_size'] ?? 'medium'),
                'subtitle_color' => $player_settings['movie_engine_subtitle_color'] ?? ($player_settings['subtitle_color'] ?? '#ffffff'),
                'subtitle_bg_color' => $player_settings['movie_engine_subtitle_bg_color'] ?? ($player_settings['subtitle_bg_color'] ?? '#000000'),
                'subtitle_bg_opacity' => isset($player_settings['movie_engine_subtitle_bg_opacity']) ? intval($player_settings['movie_engine_subtitle_bg_opacity']) : (isset($player_settings['subtitle_bg_opacity']) ? intval($player_settings['subtitle_bg_opacity']) : 50),
                'subtitle_shadow' => isset($player_settings['movie_engine_subtitle_shadow']) ? !empty($player_settings['movie_engine_subtitle_shadow']) : !empty($player_settings['subtitle_shadow']),
                'user_upload' => isset($player_settings['movie_engine_user_upload']) ? !empty($player_settings['movie_engine_user_upload']) : !empty($player_settings['user_upload']),
                'enable_audio_selection' => isset($player_settings['movie_engine_enable_audio_selection']) ? !empty($player_settings['movie_engine_enable_audio_selection']) : !empty($player_settings['enable_audio_selection']),
                'default_audio_lang' => $player_settings['movie_engine_default_audio_lang'] ?? ($player_settings['default_audio_lang'] ?? 'en'),
                'dual_audio' => isset($player_settings['movie_engine_dual_audio']) ? !empty($player_settings['movie_engine_dual_audio']) : !empty($player_settings['dual_audio']),
                'show_audio_btn' => isset($player_settings['movie_engine_show_audio_btn']) ? !empty($player_settings['movie_engine_show_audio_btn']) : !empty($player_settings['show_audio_btn']),
                'audio_delay' => isset($player_settings['movie_engine_audio_delay']) ? intval($player_settings['movie_engine_audio_delay']) : (isset($player_settings['audio_delay']) ? intval($player_settings['audio_delay']) : 0),
                'show_replay' => isset($player_settings['movie_engine_show_replay']) ? !empty($player_settings['movie_engine_show_replay']) : !empty($player_settings['show_replay']),
                'skip_intro' => isset($player_settings['movie_engine_skip_intro']) ? !empty($player_settings['movie_engine_skip_intro']) : !empty($player_settings['skip_intro']),
                'skip_recap' => isset($player_settings['movie_engine_skip_recap']) ? !empty($player_settings['movie_engine_skip_recap']) : !empty($player_settings['skip_recap']),
                'start_poster' => isset($player_settings['movie_engine_start_poster']) ? !empty($player_settings['movie_engine_start_poster']) : !empty($player_settings['start_poster']),
                'enable_watermark' => isset($player_settings['movie_engine_enable_watermark']) ? !empty($player_settings['movie_engine_enable_watermark']) : !empty($player_settings['enable_watermark']),
                'watermark_url' => $player_settings['movie_engine_watermark_url'] ?? ($player_settings['watermark_url'] ?? ''),
                'watermark_pos' => $player_settings['movie_engine_watermark_pos'] ?? ($player_settings['watermark_pos'] ?? 'top-right'),
                'watermark_opacity' => isset($player_settings['movie_engine_watermark_opacity']) ? intval($player_settings['movie_engine_watermark_opacity']) / 100 : (isset($player_settings['watermark_opacity']) ? intval($player_settings['watermark_opacity']) / 100 : 0.8),
                'watermark_width' => $player_settings['movie_engine_watermark_width'] ?? ($player_settings['watermark_width'] ?? ''),
                'watermark_height' => $player_settings['movie_engine_watermark_height'] ?? ($player_settings['watermark_height'] ?? ''),
                'dynamic_watermark' => isset($player_settings['movie_engine_dynamic_watermark']) ? !empty($player_settings['movie_engine_dynamic_watermark']) : !empty($player_settings['dynamic_watermark']),
                'rotating_watermark' => isset($player_settings['movie_engine_rotating_watermark']) ? !empty($player_settings['movie_engine_rotating_watermark']) : !empty($player_settings['rotating_watermark']),
                'player_theme' => $player_settings['movie_engine_player_theme'] ?? ($player_settings['player_theme'] ?? 'auto'),
                'primary_color' => $player_settings['movie_engine_primary_color'] ?? ($player_settings['primary_color'] ?? '#e50914'),
                'control_bar_style' => $player_settings['movie_engine_control_bar_style'] ?? ($player_settings['control_bar_style'] ?? 'full'),
                'disable_right_click' => isset($player_settings['movie_engine_disable_right_click']) ? !empty($player_settings['movie_engine_disable_right_click']) : !empty($player_settings['disable_right_click']),
                'disable_download_keys' => isset($player_settings['movie_engine_disable_download_keys']) ? !empty($player_settings['movie_engine_disable_download_keys']) : !empty($player_settings['disable_download_keys']),
                'hide_video_url' => isset($player_settings['movie_engine_hide_video_url']) ? !empty($player_settings['movie_engine_hide_video_url']) : !empty($player_settings['hide_video_url']),
                'enable_hls' => isset($player_settings['movie_engine_enable_hls']) ? !empty($player_settings['movie_engine_enable_hls']) : !empty($player_settings['enable_hls']),
                'enable_dash' => isset($player_settings['movie_engine_enable_dash']) ? !empty($player_settings['movie_engine_enable_dash']) : !empty($player_settings['enable_dash']),
                'hardware_accel' => isset($player_settings['movie_engine_hardware_accel']) ? !empty($player_settings['movie_engine_hardware_accel']) : !empty($player_settings['hardware_accel']),
                'max_buffer' => isset($player_settings['movie_engine_max_buffer']) ? intval($player_settings['movie_engine_max_buffer']) : (isset($player_settings['max_buffer']) ? intval($player_settings['max_buffer']) : 30),
                'preload_strategy' => $player_settings['movie_engine_preload_strategy'] ?? ($player_settings['preload_strategy'] ?? 'metadata'),
                'buffering_strategy' => $player_settings['movie_engine_buffering_strategy'] ?? ($player_settings['buffering_strategy'] ?? 'conservative'),
                'low_latency' => isset($player_settings['movie_engine_low_latency']) ? !empty($player_settings['movie_engine_low_latency']) : !empty($player_settings['low_latency']),
                'enable_chromecast' => isset($player_settings['movie_engine_enable_chromecast']) ? !empty($player_settings['movie_engine_enable_chromecast']) : !empty($player_settings['enable_chromecast']),
                'enable_airplay' => isset($player_settings['movie_engine_enable_airplay']) ? !empty($player_settings['movie_engine_enable_airplay']) : !empty($player_settings['enable_airplay']),
                'mobile_double_tap' => isset($player_settings['movie_engine_mobile_double_tap']) ? !empty($player_settings['movie_engine_mobile_double_tap']) : !empty($player_settings['mobile_double_tap']),
                'tablet_ui' => isset($player_settings['movie_engine_tablet_ui']) ? !empty($player_settings['movie_engine_tablet_ui']) : !empty($player_settings['tablet_ui']),
                'prevent_iframe' => isset($player_settings['movie_engine_prevent_iframe']) ? !empty($player_settings['movie_engine_prevent_iframe']) : !empty($player_settings['prevent_iframe']),
                'secure_tokens' => isset($player_settings['movie_engine_secure_tokens']) ? !empty($player_settings['movie_engine_secure_tokens']) : !empty($player_settings['secure_tokens']),
                'anti_screen_record' => isset($player_settings['movie_engine_anti_screen_record']) ? !empty($player_settings['movie_engine_anti_screen_record']) : !empty($player_settings['anti_screen_record']),
                'disable_pip_security' => isset($player_settings['movie_engine_disable_pip_security']) ? !empty($player_settings['movie_engine_disable_pip_security']) : !empty($player_settings['disable_pip_security']),
                'ep_title_overlay' => isset($player_settings['movie_engine_ep_title_overlay']) ? !empty($player_settings['movie_engine_ep_title_overlay']) : !empty($player_settings['ep_title_overlay']),
                'prev_ep_btn' => isset($player_settings['movie_engine_prev_ep_btn']) ? !empty($player_settings['movie_engine_prev_ep_btn']) : !empty($player_settings['prev_ep_btn']),
                'show_playlist_btn' => isset($player_settings['movie_engine_show_playlist_btn']) ? !empty($player_settings['movie_engine_show_playlist_btn']) : !empty($player_settings['show_playlist_btn']),
                'skip_intro_start' => isset($player_settings['movie_engine_skip_intro_start']) ? intval($player_settings['movie_engine_skip_intro_start']) : (isset($player_settings['skip_intro_start']) ? intval($player_settings['skip_intro_start']) : 0),
                'skip_intro_end' => isset($player_settings['movie_engine_skip_intro_end']) ? intval($player_settings['movie_engine_skip_intro_end']) : (isset($player_settings['skip_intro_end']) ? intval($player_settings['skip_intro_end']) : 90),
                'skip_recap_start' => isset($player_settings['movie_engine_skip_recap_start']) ? intval($player_settings['movie_engine_skip_recap_start']) : (isset($player_settings['skip_recap_start']) ? intval($player_settings['skip_recap_start']) : 0),
                'skip_recap_end' => isset($player_settings['movie_engine_skip_recap_end']) ? intval($player_settings['movie_engine_skip_recap_end']) : (isset($player_settings['skip_recap_end']) ? intval($player_settings['skip_recap_end']) : 30),
            ],
            'i18n'     => [
                'copied' => esc_html__('Copied!', 'cine-movie-engine'),
                'error'  => esc_html__('An error occurred.', 'cine-movie-engine'),
                'all_genres' => esc_html__('All Genres', 'cine-movie-engine'),
                'all_years'  => esc_html__('All Years', 'cine-movie-engine'),
                'add_to_watchlist' => esc_html__('Add to Watchlist', 'cine-movie-engine'),
                'remove_from_watchlist' => esc_html__('Remove Watchlist', 'cine-movie-engine'),
                'watchlist_empty' => esc_html__('Your watchlist is empty.', 'cine-movie-engine'),
                'play' => esc_html__('Play', 'cine-movie-engine'),
                'pause' => esc_html__('Pause', 'cine-movie-engine'),
                'mute' => esc_html__('Mute', 'cine-movie-engine'),
                'unmute' => esc_html__('Unmute', 'cine-movie-engine'),
                'enter_fullscreen' => esc_html__('Enter Fullscreen', 'cine-movie-engine'),
                'exit_fullscreen' => esc_html__('Exit Fullscreen', 'cine-movie-engine'),
                'settings' => esc_html__('Settings', 'cine-movie-engine'),
                'pip' => esc_html__('PIP', 'cine-movie-engine'),
                'airplay' => esc_html__('AirPlay', 'cine-movie-engine'),
                'download' => esc_html__('Download', 'cine-movie-engine'),
                'speed' => esc_html__('Speed', 'cine-movie-engine'),
                'quality' => esc_html__('Quality', 'cine-movie-engine'),
                'captions' => esc_html__('Captions', 'cine-movie-engine'),
                'audio' => esc_html__('Audio', 'cine-movie-engine'),
                'normal' => esc_html__('Normal', 'cine-movie-engine'),
                'login_required' => esc_html__('Login Required', 'cine-movie-engine'),
                'login_to_watch' => esc_html__('Please login or create an account to watch this content.', 'cine-movie-engine'),
                'login' => esc_html__('Login', 'cine-movie-engine'),
                'register' => esc_html__('Register', 'cine-movie-engine'),
                'processing' => esc_html__('Processing...', 'cine-movie-engine'),
                'error_checkout' => esc_html__('Error creating checkout session.', 'cine-movie-engine'),
                'like' => esc_html__('like', 'cine-movie-engine'),
                'likes' => esc_html__('likes', 'cine-movie-engine'),
                'load_more' => esc_html__('Load More', 'cine-movie-engine'),
                'confirm_delete' => esc_html__('Are you sure you want to delete this?', 'cine-movie-engine'),
            ],
            'login_url' => wp_login_url(get_permalink()),
            'payments' => [
                'stripe' => [
                    'enabled' => isset(get_option('movie_engine_payments_settings', [])['movie_engine_stripe_enabled']) ? !empty(get_option('movie_engine_payments_settings', [])['movie_engine_stripe_enabled']) : !empty(get_option('movie_engine_payments_settings', [])['stripe_enabled']),
                    'publishable_key' => get_option('movie_engine_payments_settings', [])['movie_engine_stripe_publishable_key'] ?? (get_option('movie_engine_payments_settings', [])['stripe_publishable_key'] ?? ''),
                ],
                'mode' => get_option('movie_engine_payments_settings', [])['movie_engine_mode'] ?? (get_option('movie_engine_payments_settings', [])['mode'] ?? 'test'),
                'checkout_url' => rest_url('movie-engine/v1/payments/checkout'),
            ],
            'free_trial' => [
                'enabled' => apply_filters('movie_engine_free_trial_enabled', false),
                'in_trial' => \MovieEngine\Payments\Membership::is_in_trial_period(),
                'days_remaining' => \MovieEngine\Payments\Membership::get_remaining_trial_days(),
                'trial_days' => apply_filters('movie_engine_trial_days', 0),
            ],
            '_cache_buster' => time(),
            'current_progress' => (is_singular(['movie_engine_movie', 'movie_engine_episode']) && is_user_logged_in())
                ? \MovieEngine\Frontend\Users\WatchHistory::get_progress(get_current_user_id(), get_the_ID())
                : 0,
            'post_type' => get_post_type(),
            'is_series' => is_singular(['movie_engine_series', 'movie_engine_episode']),
            'is_movie'  => is_singular('movie_engine_movie'),
        ]));
    }
}
