<?php

/**
 * Assets Manager for Havenlytics 
 *
 * @package     Havenlytics
 * @subpackage  Frontend
 * @copyright   Copyright (c) 2025, Havenlytics
 * @license     http://opensource.org/licenses/gpl-2.0.php GNU Public License
 * @since       2.0.0
 */

namespace HvnlyNab\Frontend;

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

/**
 * Assets class
 *
 * @since 2.0.0
 */
class Assets
{
    private $is_property_archive = false;
    private $is_single_property = false;
    private $is_property_taxonomy = false;
    private $is_property_search_page = false;
    private $has_property_shortcode = false; 
    private $ajax_params = null;
    private $map_params = null;
    private $map_localize_params = null;
    private $localization_done = false; 
    
    public function __construct()
    {
        add_action('wp_enqueue_scripts', [$this, 'setup_page_conditions'], 5);
        add_action('wp_enqueue_scripts', [$this, 'enqueue_styles']);
        add_action('wp_enqueue_scripts', [$this, 'enqueue_scripts']);
        
        add_action('template_redirect', [$this, 'start_output_buffering'], 1);

        // Output preloader config in head before any scripts run
        add_action('wp_enqueue_scripts', [$this, 'output_preloader_config'], 1);
    }

    /**
     * Output preloader config in head before any scripts
     * 
     * Uses WordPress native conditional tags (available during wp_head)
     * to determine if the current page needs preloader configuration.
     *
     * @return void
     */
    public function output_preloader_config()
    {
        // Detect shortcode usage
        $has_shortcode = false;

        if (is_singular()) {
            global $post;

            if (!empty($post->post_content) && has_shortcode($post->post_content, 'hvnly_property_search')) {
                $has_shortcode = true;
            }
        }

        // Only output on property pages OR when shortcode is present
        if (
            !$has_shortcode &&
            !is_post_type_archive('hvnly_property') &&
            !is_tax(get_object_taxonomies('hvnly_property')) &&
            !is_singular('hvnly_property')
        ) {
            return;
        }

        // Get AJAX Load More status from settings
        $is_ajax_load_more_enabled = function_exists('hvnly_is_ajax_load_more_enabled') 
            ? hvnly_is_ajax_load_more_enabled() 
            : true;

        wp_add_inline_script(
            'jquery',
            'window.hvnly_ajax_load_more_enabled = ' . ($is_ajax_load_more_enabled ? 'true' : 'false') . ';',
            'before'
        );

        $settings_manager = \HvnlyNab\Core\SettingsManager::get_instance();
        $preloader_settings = $settings_manager->get_preloader_settings();
        
        $preloader_config = array(
            'enabled'      => (bool) ($preloader_settings['hvnly_enable_preloader'] ?? false),
            'min_display'  => absint($preloader_settings['hvnly_preloader_min_display'] ?? 300),
            'animation'    => sanitize_text_field($preloader_settings['hvnly_preloader_animation'] ?? 'shimmer'),
            'components'   => array(
                'filter_sidebar' => (bool) ($preloader_settings['hvnly_preloader_filter_sidebar'] ?? false),
                'top_search'     => (bool) ($preloader_settings['hvnly_preloader_top_search'] ?? false),
                'property_grid'  => (bool) ($preloader_settings['hvnly_preloader_property_grid'] ?? false),
                'property_list'  => (bool) ($preloader_settings['hvnly_preloader_property_list'] ?? false),
                'view_controls'  => (bool) ($preloader_settings['hvnly_preloader_view_controls'] ?? false),
                'load_more'      => (bool) ($preloader_settings['hvnly_preloader_load_more'] ?? false),
                'pagination'     => (bool) ($preloader_settings['hvnly_preloader_pagination'] ?? false),
                'related_properties' => false,
            ),
        );

        wp_add_inline_script(
            'jquery',
            'window.hvnly_preloader_config = ' . wp_json_encode($preloader_config) . ';',
            'before'
        );
    }

    /**
     * Setup page conditions early
     */
    public function setup_page_conditions()
    {
        $this->is_single_property = is_singular('hvnly_property');
        $this->is_property_archive = is_post_type_archive('hvnly_property');
        $this->is_property_taxonomy = is_tax(get_object_taxonomies('hvnly_property'));
        
        // Check if this is our property search page
        $this->is_property_search_page = $this->is_property_search_page();
        
        // Check if page contains property shortcodes
        $this->has_property_shortcode = $this->has_property_shortcodes();
    }
    
    /**
     * Check if current page has any property shortcodes
     *
     * @return bool
     */
    private function has_property_shortcodes() {
        global $post;
        
        if (!$post || !isset($post->post_content)) {
            return false;
        }
        
        $property_shortcodes = [
            'hvnly_property_grid',
            'hvnly_property_list',
            'hvnly_property_search',
            'hvnly_featured_properties',
            'hvnly_properties'
        ];
        
        foreach ($property_shortcodes as $shortcode) {
            if (has_shortcode($post->post_content, $shortcode)) {
                return true;
            }
        }
        
        return false;
    }
    
    /**
     * Check if current page is the property search page
     *
     * @return bool
     */
    private function is_property_search_page() {
        global $post;
        
        // Check by page ID if we have the page installer class
        if (class_exists('\HvnlyNab\Setup\PageInstaller')) {
            $grid_page_id = \HvnlyNab\Setup\PageInstaller::get_page_id('property_grid');
            $lists_page_id = \HvnlyNab\Setup\PageInstaller::get_page_id('property_lists');
            
            if (($grid_page_id && is_page($grid_page_id)) || ($lists_page_id && is_page($lists_page_id))) {
                return true;
            }
        }
        
        // Fallback: Check if post content contains the shortcodes
        if ($post && isset($post->post_content)) {
            if (has_shortcode($post->post_content, 'hvnly_property_grid') || 
                has_shortcode($post->post_content, 'hvnly_property_lists') ||
                has_shortcode($post->post_content, 'hvnly_property_search')) {
                return true;
            }
        }
        
        return false;
    }

    /**
     * Start output buffering to remove source maps
     */
    public function start_output_buffering()
    {
        ob_start(function($buffer) {
            // Remove all sourceURL comments
            $buffer = preg_replace('/\/\/# sourceURL=[^\n\r]*[\n\r]*/m', '', $buffer);
            return $buffer;
        });
    }

    /**
     * Enqueue frontend styles
     */
    public function enqueue_styles()
    {
        // Register all styles
        $this->register_styles();
        
        // Always enqueue base styles
        wp_enqueue_style('hvnly-fontawesome-all-frontend');
        wp_enqueue_style('hvnly-frontend-default');
        wp_enqueue_style('hvnly-frontend-components');
        wp_enqueue_style('hvnly-frontend-global-grid');
        
        // Enqueue preloader styles on relevant pages
        if ($this->is_property_archive || $this->is_property_taxonomy || $this->is_property_search_page || $this->has_property_shortcode) {
            wp_enqueue_style('hvnly-frontend-preloader');
        }

        // Inject dynamic CSS from design settings
        $this->inject_dynamic_css();
        
        // Conditional styles
        if ($this->is_single_property) {
            wp_enqueue_style('hvnly-frontend-property-single');
            wp_enqueue_style('hvnly-frontend-widgets');
            wp_enqueue_style('hvnly-frontend-property-share');
        }
        
        // Load archive styles on archive, taxonomy, search page, OR any page with property shortcodes
        if ($this->is_property_archive || $this->is_property_taxonomy || $this->is_property_search_page || $this->has_property_shortcode) {
            wp_enqueue_style('hvnly-frontend-property-ajax-filter');
            wp_enqueue_style('hvnly-frontend-property-share');
            wp_enqueue_style('hvnly-frontend-property-archive');
        }
        
        // Enqueue filter styles on pages with potential search forms
        if (is_page() || is_home() || is_front_page() || $this->is_property_archive || $this->is_property_taxonomy || $this->is_property_search_page || $this->has_property_shortcode) {
            wp_enqueue_style('hvnly-frontend-property-ajax-filter');
        }
        
        // Always load responsive CSS last
        wp_enqueue_style('hvnly-frontend-property-responsive');
    }
    
    /**
     * Register all CSS files
     */
    private function register_styles()
    {
        $styles = [
            'hvnly-fontawesome-all-frontend' => [
                'path' => HVNLYNAB_ASSETS_URL . '/admin/css/fontawesome-all.min.css',
                'deps' => [],
                'ver' => HVNLYNAB_VERSION,
                'media' => 'all'
            ],
            'hvnly-frontend-default' => [
                'path' => HVNLYNAB_ASSETS_URL . '/frontend/css/hvnly-frontend-default.css',
                'deps' => [],
                'ver' => HVNLYNAB_VERSION,
                'media' => 'all'
            ],
            'hvnly-frontend-components' => [
                'path' => HVNLYNAB_ASSETS_URL . '/frontend/css/hvnly-frontend-components.css',
                'deps' => [],
                'ver' => HVNLYNAB_VERSION,
                'media' => 'all'
            ],
            'hvnly-frontend-global-grid' => [
                'path' => HVNLYNAB_ASSETS_URL . '/frontend/css/hvnly-frontend-global-grid.css',
                'deps' => [],
                'ver' => HVNLYNAB_VERSION,
                'media' => 'all'
            ],
            'hvnly-frontend-property-ajax-filter' => [
                'path' => HVNLYNAB_ASSETS_URL . '/frontend/css/property-search/hvnly-frontend-property-ajax-filter-search.css',
                'deps' => [],
                'ver' => HVNLYNAB_VERSION,
                'media' => 'all'
            ],
            'hvnly-frontend-property-single' => [
                'path' => HVNLYNAB_ASSETS_URL . '/frontend/css/hvnly-frontend-property-single.css',
                'deps' => ['hvnly-frontend-default'],
                'ver' => HVNLYNAB_VERSION,
                'media' => 'all'
            ],
            'hvnly-frontend-widgets' => [
                'path' => HVNLYNAB_ASSETS_URL . '/frontend/css/hvnly-frontend-widgets.css',
                'deps' => [],
                'ver' => HVNLYNAB_VERSION,
                'media' => 'all'
            ],
            'hvnly-frontend-property-share' => [
                'path' => HVNLYNAB_ASSETS_URL . '/frontend/css/hvnly-frontend-property-share.css',
                'deps' => [],
                'ver' => HVNLYNAB_VERSION,
                'media' => 'all'
            ],
            'hvnly-frontend-property-archive' => [
                'path' => HVNLYNAB_ASSETS_URL . '/frontend/css/property-search/hvnly-frontend-property-archive.css',
                'deps' => ['hvnly-frontend-global-grid'],
                'ver' => HVNLYNAB_VERSION,
                'media' => 'all'
            ],
            'hvnly-frontend-property-responsive' => [
                'path' => HVNLYNAB_ASSETS_URL . '/frontend/css/hvnly-frontend-property-responsive.css',
                'deps' => [],
                'ver' => HVNLYNAB_VERSION,
                'media' => 'all'
            ],
            'hvnly-frontend-preloader' => [
                'path' => HVNLYNAB_ASSETS_URL . '/frontend/css/hvnly-frontend-preloader.css',
                'deps' => [],
                'ver' => HVNLYNAB_VERSION,
                'media' => 'all'
            ]

        ];
        
        foreach ($styles as $handle => $style) {
            wp_register_style(
                $handle,
                $style['path'],
                $style['deps'],
                $style['ver'],
                $style['media']
            );
        }
    }
    
    /**
     * Inject dynamic CSS from design settings
     * This method generates and injects dynamic CSS based on design settings
     *
     * @return void
     */
    private function inject_dynamic_css()
    {
        // Check if DynamicStyleGenerator class exists
        if (class_exists('HvnlyNab\Core\DynamicStyleGenerator')) {
            $generator = \HvnlyNab\Core\DynamicStyleGenerator::get_instance();
            $generator->inject_dynamic_styles();
        }
    }

    /**
     * Enqueue frontend scripts
     */
    public function enqueue_scripts()
    {
        // Register all scripts first
        $this->register_scripts();
        
        // Always enqueue jQuery
        wp_enqueue_script('jquery');
        
        // Enqueue preloader script on relevant pages
        if ($this->is_property_archive || $this->is_property_taxonomy || $this->is_property_search_page || $this->has_property_shortcode) {
            wp_enqueue_script('hvnly-frontend-preloader');
        }

        // Only enqueue filter search on archive/taxonomy/search pages OR pages with shortcodes
        if ($this->is_property_archive || $this->is_property_taxonomy || $this->is_property_search_page || $this->has_property_shortcode) {
            wp_enqueue_script('hvnly-frontend-property-ajax-filter-search');
        }
        
        // Enqueue modular AJAX system for archive/taxonomy/search pages OR pages with shortcodes
        if ($this->is_property_archive || $this->is_property_taxonomy || $this->is_property_search_page || $this->has_property_shortcode) {
            $this->enqueue_modular_ajax_system();
            $this->localize_ajax_scripts_once(); 
        }
        
        // Enqueue single property scripts (without filter search)
        if ($this->is_single_property) {
            $this->enqueue_single_property_scripts();
            
            // Even if AJAX system is not loaded, we need map params for the single map
            $map_localize_params = $this->get_map_localize_params();
            wp_localize_script('hvnly-frontend-property-single-map', 'hvnly_map_params', $map_localize_params);
        }
       
        // Enqueue map assets where needed
        if ($this->should_load_maps()) {
            $this->enqueue_map_assets();
        }
    }
    
    /**
     * Register all JavaScript files
     */
    private function register_scripts()
    {
        // Main property scripts
        $scripts = [
            'hvnly-frontend-property-map-search' => [
                'path' => HVNLYNAB_ASSETS_URL . '/frontend/js/property-search/hvnly-frontend-property-map-search.js',
                'deps' => ['jquery'],
                'ver' => HVNLYNAB_VERSION,
                'in_footer' => true
            ],
            'hvnly-frontend-property-ajax-filter-search' => [
                'path' => HVNLYNAB_ASSETS_URL . '/frontend/js/property-search/hvnly-frontend-property-ajax-filter-search.js',
                'deps' => ['jquery', 'hvnly-frontend-property-map-search'],
                'ver' => HVNLYNAB_VERSION,
                'in_footer' => true
            ],
            // 'hvnly-frontend-property-image-optimizer' => [
            //     'path' => HVNLYNAB_ASSETS_URL . '/frontend/js/hvnly-frontend-property-image-optimizer.js',
            //     'deps' => ['jquery'],
            //     'ver' => HVNLYNAB_VERSION,
            //     'in_footer' => true
            // ],
            'hvnly-frontend-property-single-gallery' => [
                'path' => HVNLYNAB_ASSETS_URL . '/frontend/js/hvnly-frontend-property-single-gallery.js',
                'deps' => ['jquery'],
                'ver' => HVNLYNAB_VERSION,
                'in_footer' => true
            ],
            // 'hvnly-frontend-property-mortgage-calculator' => [
            //     'path' => HVNLYNAB_ASSETS_URL . '/frontend/js/hvnly-frontend-property-mortgage-calculator.js',
            //     'deps' => ['jquery'],
            //     'ver' => HVNLYNAB_VERSION,
            //     'in_footer' => true
            // ],
            // 'hvnly-frontend-property-favorite' => [
            //     'path' => HVNLYNAB_ASSETS_URL . '/frontend/js/property-search/hvnly-frontend-property-favorite.js',
            //     'deps' => ['jquery'],
            //     'ver' => HVNLYNAB_VERSION,
            //     'in_footer' => true
            // ],
            'hvnly-frontend-property-single-video' => [
                'path' => HVNLYNAB_ASSETS_URL . '/frontend/js/hvnly-frontend-property-single-video.js',
                'deps' => ['jquery'],
                'ver' => HVNLYNAB_VERSION,
                'in_footer' => true
            ],
            'hvnly-frontend-property-single-map' => [
                'path' => HVNLYNAB_ASSETS_URL . '/frontend/js/hvnly-frontend-property-single-map.js',
                'deps' => ['jquery'],
                'ver' => HVNLYNAB_VERSION,
                'in_footer' => true
            ],
            'hvnly-frontend-property-single' => [
                'path' => HVNLYNAB_ASSETS_URL . '/frontend/js/hvnly-frontend-property-single.js',
                'deps' => ['jquery'],
                'ver' => HVNLYNAB_VERSION,
                'in_footer' => true
            ],
            // Preloader script
            'hvnly-frontend-preloader' => [
                'path' => HVNLYNAB_ASSETS_URL . '/frontend/js/hvnly-frontend-preloader.js',
                'deps' => ['jquery'],
                'ver' => HVNLYNAB_VERSION,
                'in_footer' => true
            ]

        ];
        
        foreach ($scripts as $handle => $script) {
            wp_register_script(
                $handle,
                $script['path'],
                $script['deps'],
                $script['ver'],
                $script['in_footer']
            );
        }
        
        // Register modular AJAX scripts
        $this->register_modular_ajax_scripts();
    }
    
    /**
     * Register modular AJAX scripts
     */
    private function register_modular_ajax_scripts()
    {
        $ajax_modules = [
            'hvnly-frontend-property-ajax-utils' => [
                'path' => HVNLYNAB_ASSETS_URL . '/frontend/js/property-search/modules/hvnly-frontend-property-ajax-utils.js',
                'deps' => ['jquery'],
                'ver' => HVNLYNAB_VERSION,
                'in_footer' => true
            ],
            'hvnly-frontend-property-ajax-filters' => [
                'path' => HVNLYNAB_ASSETS_URL . '/frontend/js/property-search/modules/hvnly-frontend-property-ajax-filters.js',
                'deps' => ['jquery', 'hvnly-frontend-property-ajax-utils'],
                'ver' => HVNLYNAB_VERSION,
                'in_footer' => true
            ],
            'hvnly-frontend-property-ajax-search' => [
                'path' => HVNLYNAB_ASSETS_URL . '/frontend/js/property-search/modules/hvnly-frontend-property-ajax-search.js',
                'deps' => ['jquery', 'hvnly-frontend-property-ajax-utils', 'hvnly-frontend-property-ajax-filters'],
                'ver' => HVNLYNAB_VERSION,
                'in_footer' => true
            ],
            'hvnly-frontend-property-ajax-pagination' => [
                'path' => HVNLYNAB_ASSETS_URL . '/frontend/js/property-search/modules/hvnly-frontend-property-ajax-pagination.js',
                'deps' => ['jquery', 'hvnly-frontend-property-ajax-utils'],
                'ver' => HVNLYNAB_VERSION,
                'in_footer' => true
            ],
            'hvnly-frontend-property-ajax-url' => [
                'path' => HVNLYNAB_ASSETS_URL . '/frontend/js/property-search/modules/hvnly-frontend-property-ajax-url.js',
                'deps' => ['jquery', 'hvnly-frontend-property-ajax-utils'],
                'ver' => HVNLYNAB_VERSION,
                'in_footer' => true
            ],
            'hvnly-frontend-property-ajax-ui' => [
                'path' => HVNLYNAB_ASSETS_URL . '/frontend/js/property-search/modules/hvnly-frontend-property-ajax-ui.js',
                'deps' => ['jquery', 'hvnly-frontend-property-ajax-utils'],
                'ver' => HVNLYNAB_VERSION,
                'in_footer' => true
            ],
            'hvnly-frontend-property-ajax-root' => [
                'path' => HVNLYNAB_ASSETS_URL . '/frontend/js/property-search/hvnly-frontend-property-ajax-root.js',
                'deps' => [
                    'jquery',
                    'hvnly-frontend-property-ajax-utils',
                    'hvnly-frontend-property-ajax-filters',
                    'hvnly-frontend-property-ajax-search',
                    'hvnly-frontend-property-ajax-pagination',
                    'hvnly-frontend-property-ajax-url',
                    'hvnly-frontend-property-ajax-ui'
                ],
                'ver' => HVNLYNAB_VERSION,
                'in_footer' => true
            ]
        ];
        
        foreach ($ajax_modules as $handle => $module) {
            wp_register_script(
                $handle,
                $module['path'],
                $module['deps'],
                $module['ver'],
                $module['in_footer']
            );
        }
    }
    
    /**
     * Get AJAX parameters (cached)
     */
    private function get_ajax_params()
    {
        if ($this->ajax_params === null) {
            global $wp_query;
            
            // Get custom properties per page from settings
            $properties_per_page = 6;
            if (function_exists('hvnly_get_properties_per_page')) {
                $properties_per_page = hvnly_get_properties_per_page();
            }
            
            // Sanitize view_type from URL
            $view_type = 'grid';
            if (isset($_GET['view_type'])) {
                $view_type = sanitize_text_field(wp_unslash($_GET['view_type']));
                // Allow only specific values
                $allowed_view_types = ['grid', 'list', 'map'];
                if (!in_array($view_type, $allowed_view_types, true)) {
                    $view_type = 'grid';
                }
            }
            
            $this->ajax_params = [
                'ajax_url'           => esc_url(admin_url('admin-ajax.php')),
                'nonce'              => '', // Will be set in localization with fresh nonce
                'current_page'       => max(1, absint(get_query_var('paged'))),
                'max_pages'          => absint($wp_query->max_num_pages ?? 1),
                'found_posts'        => absint($wp_query->found_posts ?? 0),
                'post_count'         => absint($wp_query->post_count ?? 0),
                'per_page'           => absint($properties_per_page),
                'properties_per_page'=> absint($properties_per_page),
                'loading_text'       => esc_html__('Loading...', 'havenlytics'),
                'load_more_text'     => esc_html__('Load More Properties', 'havenlytics'),
                'error_text'         => esc_html__('An error occurred. Please try again.', 'havenlytics'),
                'properties_found_text' => esc_html__('properties found', 'havenlytics'),
                'view_type'          => $view_type,
                'debug'              => (defined('WP_DEBUG') && WP_DEBUG) ? '1' : '0',
                'is_archive'         => $this->is_property_archive,
                'is_taxonomy'        => $this->is_property_taxonomy,
                'has_shortcode'      => $this->has_property_shortcode 
            ];
        }
        
        return $this->ajax_params;
    }
    
    /**
     * Get map parameters (cached)
     */
    private function get_map_params()
    {
        if ($this->map_params === null) {
            $this->map_params = [
                'default_lat' => $this->sanitize_coordinate(get_option('hvnly_default_lat', '40.7128')),
                'default_lng' => $this->sanitize_coordinate(get_option('hvnly_default_lng', '-74.0060')),
                'zoom_level' => absint(get_option('hvnly_map_zoom', 12)),
                'cluster_markers' => (bool) get_option('hvnly_cluster_markers', true),
                'map_provider' => sanitize_text_field(get_option('hvnly_map_provider', 'leaflet')),
                'api_key' => sanitize_text_field(get_option('hvnly_map_api_key', '')),
            ];
        }
        
        return $this->map_params;
    }
    
    /**
     * Sanitize coordinate values (lat/lng)
     */
    private function sanitize_coordinate($coord)
    {
        $coord = sanitize_text_field($coord);
        if (is_numeric($coord)) {
            return (float) $coord;
        }
        return $coord;
    }
    
    /**
     * Get extended map parameters (cached)
     */
    private function get_map_localize_params()
    {
        if ($this->map_localize_params === null) {
            $settings_manager = \HvnlyNab\Core\SettingsManager::get_instance();
            $map_settings = $settings_manager->get_map_settings();
            
            $map_provider = isset($map_settings['hvnly_map_provider']) ? $map_settings['hvnly_map_provider'] : 'leaflet';
            $api_key = isset($map_settings['hvnly_map_api_key']) ? $map_settings['hvnly_map_api_key'] : '';
            $enable_fallback = isset($map_settings['hvnly_enable_google_fallback']) ? (bool) $map_settings['hvnly_enable_google_fallback'] : true;
            
            $final_provider = $map_provider;
            if ($map_provider === 'google' && empty($api_key)) {
                $final_provider = 'leaflet';
            }
            
            $this->map_localize_params = [
                'provider' => $final_provider,
                'api_key' => $api_key,
                'enable_google_fallback' => $enable_fallback, // NEW
                'default_lat' => isset($map_settings['hvnly_default_lat']) ? (float) $map_settings['hvnly_default_lat'] : 51.514939,
                'default_lng' => isset($map_settings['hvnly_default_lng']) ? (float) $map_settings['hvnly_default_lng'] : -0.091839,
                'zoom_level' => isset($map_settings['hvnly_map_zoom']) ? absint($map_settings['hvnly_map_zoom']) : 12,
                'cluster_markers' => isset($map_settings['hvnly_cluster_markers']) ? (bool) $map_settings['hvnly_cluster_markers'] : true,
                'map_style' => isset($map_settings['hvnly_map_style']) ? sanitize_text_field($map_settings['hvnly_map_style']) : 'standard',
                'custom_marker' => isset($map_settings['hvnly_custom_marker']) ? (bool) $map_settings['hvnly_custom_marker'] : false,
                'marker_color' => isset($map_settings['hvnly_marker_color']) ? sanitize_text_field($map_settings['hvnly_marker_color']) : '#6C60FE',
                'show_fullscreen' => isset($map_settings['hvnly_show_fullscreen']) ? (bool) $map_settings['hvnly_show_fullscreen'] : true,
                'show_zoom_control' => isset($map_settings['hvnly_show_zoom_control']) ? (bool) $map_settings['hvnly_show_zoom_control'] : true,
                'show_scroll_wheel' => isset($map_settings['hvnly_show_scroll_wheel']) ? (bool) $map_settings['hvnly_show_scroll_wheel'] : true,
                'google_map_type' => isset($map_settings['hvnly_google_map_type']) ? sanitize_text_field($map_settings['hvnly_google_map_type']) : 'roadmap',
                'osm_tile_url' => isset($map_settings['hvnly_osm_tile_url']) ? sanitize_text_field($map_settings['hvnly_osm_tile_url']) : 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
                'osm_attribution' => isset($map_settings['hvnly_osm_attribution']) ? sanitize_textarea_field($map_settings['hvnly_osm_attribution']) : '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors',
                'plugin_url' => esc_url(HVNLYNAB_URL),
                'assets_url' => esc_url(HVNLYNAB_ASSETS_URL),
                'is_single_property' => $this->is_single_property,
                'is_property_archive' => $this->is_property_archive,
                'debug' => (defined('WP_DEBUG') && WP_DEBUG) ? '1' : '0',
            ];
        }
        
        return $this->map_localize_params;
    }
    
    /**
     * Enqueue modular AJAX system
     */
    private function enqueue_modular_ajax_system()
    {
        wp_enqueue_script('hvnly-frontend-property-map-search');
        wp_enqueue_script('hvnly-frontend-property-ajax-utils');
        wp_enqueue_script('hvnly-frontend-property-ajax-filters');
        wp_enqueue_script('hvnly-frontend-property-ajax-search');
        wp_enqueue_script('hvnly-frontend-property-ajax-pagination');
        wp_enqueue_script('hvnly-frontend-property-ajax-url');
        wp_enqueue_script('hvnly-frontend-property-ajax-ui');
        wp_enqueue_script('hvnly-frontend-property-ajax-root');
        // wp_enqueue_script('hvnly-frontend-property-favorite');
    }
    
    /**
     * Enqueue single property scripts
     */
    private function enqueue_single_property_scripts()
    {
        // enqueue filter search script on single property pages
        wp_enqueue_script('hvnly-frontend-property-single-gallery');
       // wp_enqueue_script('hvnly-frontend-property-mortgage-calculator');
        // wp_enqueue_script('hvnly-frontend-property-favorite');
        wp_enqueue_script('hvnly-frontend-property-single-video');
        
        // Ensure Leaflet is loaded before map script
        $this->enqueue_leaflet_assets();
        wp_enqueue_script('hvnly-frontend-property-single-map');
        wp_enqueue_script('hvnly-frontend-property-single');
        
        // Localize property data for single property pages
        $property_id = get_the_ID();
        wp_localize_script('hvnly-frontend-property-single-gallery', 'hvnly_property_data', [
            'property_id' => absint($property_id),
            'gallery_images' => $this->get_property_gallery_images($property_id)
        ]);
    }
    
    /**
     * Get property gallery images
     */
    private function get_property_gallery_images($property_id)
    {
        // Implement your gallery images retrieval logic here
        return [];
    }
    
    /**
     * Localize scripts for AJAX - ONCE ONLY
     * All scripts share the same global data via the root script
     */
    private function localize_ajax_scripts_once()
    {
        // Use property instead of static variable to support multiple instances
        if ($this->localization_done === true) {
            return;
        }

        // Create a fresh nonce for this page load
        $ajax_nonce = wp_create_nonce('hvnly_ajax_request');
        
        // Get current query for accurate pagination data
        global $wp_query;

        // Get cached parameters
        $ajax_params = $this->get_ajax_params();
        $map_localize_params = $this->get_map_localize_params();
        
        // Set the nonce in ajax_params
        $ajax_params['nonce'] = $ajax_nonce;
        
        // Ensure pagination data is accurate
        $ajax_params['current_page'] = max(1, absint(get_query_var('paged')));
        $ajax_params['max_pages'] = absint($wp_query->max_num_pages ?? 1);
        $ajax_params['found_posts'] = absint($wp_query->found_posts ?? 0);
        $ajax_params['post_count'] = absint($wp_query->post_count ?? 0);

        // ONLY localize the ROOT script with main data
        // Other scripts will access this data via window.hvnly_PROPERTY_ajax
        if (wp_script_is('hvnly-frontend-property-ajax-root', 'enqueued')) {
            // Localize main AJAX params to root script only
            wp_localize_script('hvnly-frontend-property-ajax-root', 'hvnly_PROPERTY_ajax', $ajax_params);
            
            // Localize map params to root script only
            wp_localize_script('hvnly-frontend-property-ajax-root', 'hvnly_map_params', $map_localize_params);
        }
        
        // For backward compatibility - add minimal data to map-search script
        // but NOT the full duplicate data
        if (wp_script_is('hvnly-frontend-property-map-search', 'enqueued')) {
            wp_localize_script('hvnly-frontend-property-map-search', 'hvnlyFrontend', [
                'ajax_url' => esc_url(admin_url('admin-ajax.php')),
                'ajax_nonce' => $ajax_nonce,
                'plugin_url' => esc_url(HVNLYNAB_URL)
            ]);
        }
        
        $this->localization_done = true;
    }
    
    /**
     * Check if maps should be loaded
     */
    private function should_load_maps()
    {
        // Always load on property archive/taxonomy/search pages OR pages with shortcodes
        if ($this->is_property_archive || $this->is_property_taxonomy || $this->is_property_search_page || $this->has_property_shortcode) {
            return true;
        }
        
        // Load on single property pages with map coordinates
        if ($this->is_single_property) {
            $property_id = get_the_ID();
            
            // Check multiple meta key locations for coordinates with sanitization
            $lat = $this->get_property_coordinate($property_id, 'latitude');
            $lng = $this->get_property_coordinate($property_id, 'longitude');
            
            $has_location = !empty($lat) && !empty($lng);
            
            return $has_location;
        }
        
        return false;
    }
    
    /**
     * Get property coordinate safely
     */
    private function get_property_coordinate($property_id, $type)
    {
        $coord = '';
        
        // Try standard meta keys
        if ($type === 'latitude') {
            $coord = get_post_meta($property_id, '_hvnly_property_location_Latitude', true);
            if (empty($coord)) {
                $coord = get_post_meta($property_id, '_hvnly_property_latitude', true);
            }
        } else {
            $coord = get_post_meta($property_id, '_hvnly_property_location_Longitude', true);
            if (empty($coord)) {
                $coord = get_post_meta($property_id, '_hvnly_property_longitude', true);
            }
        }
        
        // If still empty, check dynamic fields
        if (empty($coord)) {
            $all_meta = get_post_meta($property_id);
            $search_term = $type === 'latitude' ? 'latitude' : 'longitude';
            $alt_terms = $type === 'latitude' ? ['lat', '_lat'] : ['lng', '_lng', 'long'];
            
            foreach ($all_meta as $meta_key => $meta_value) {
                $key_lower = strtolower($meta_key);
                if ((strpos($key_lower, $search_term) !== false || in_array($key_lower, $alt_terms)) && !empty($meta_value[0])) {
                    $coord = $meta_value[0];
                    break;
                }
            }
        }
        
        // Sanitize coordinate
        if (!empty($coord) && is_numeric($coord)) {
            return (float) $coord;
        }
        
        return '';
    }
    
    /**
     * Enqueue map assets
     */
    private function enqueue_map_assets()
    {
        // Use SettingsManager to get map settings
        $settings_manager = \HvnlyNab\Core\SettingsManager::get_instance();
        $map_settings = $settings_manager->get_map_settings();
        
        $map_provider = isset($map_settings['hvnly_map_provider']) ? $map_settings['hvnly_map_provider'] : 'leaflet';
        $api_key = isset($map_settings['hvnly_map_api_key']) ? $map_settings['hvnly_map_api_key'] : '';
        
        // Debug log
        // if (defined('WP_DEBUG') && WP_DEBUG) {
        //     error_log('Havenlytics Map Assets: Provider=' . $map_provider . ', API Key=' . (empty($api_key) ? 'MISSING' : 'PRESENT'));
        // }
        
        // This ensures consistent popup styling across all map providers
        wp_enqueue_style(
            'hvnly-frontend-property-map',
            esc_url(HVNLYNAB_ASSETS_URL . '/frontend/css/property-search/hvnly-frontend-property-map.css'),
            [],
            HVNLYNAB_VERSION
        );

        // Force Google Maps if API key is provided AND provider is set to google
        if ($map_provider === 'google' && !empty($api_key)) {
            // Google Maps with proper escaping
            wp_enqueue_script(
                'hvnly-google-maps',
                'https://maps.googleapis.com/maps/api/js?key=' . urlencode($api_key) . '&libraries=places&loading=async&callback=initHvnlyMap',
                array(),
                HVNLYNAB_VERSION,
                ['strategy' => 'async']  // This adds async loading
            );
            
            // Add initialization script
            wp_add_inline_script('hvnly-google-maps', '
                function initHvnlyMap() {
                    window.dispatchEvent(new Event("hvnlyGoogleMapsLoaded"));
                    if (window.HavenlyticsPropertyMap && typeof window.HavenlyticsPropertyMap.onGoogleMapsReady === "function") {
                        window.HavenlyticsPropertyMap.onGoogleMapsReady();
                    }
                }
            ');
            
        } else {
            // Leaflet maps (default)
            $this->enqueue_leaflet_assets();
        }
    }
    
    /**
     * Enqueue Leaflet map assets
     */
    private function enqueue_leaflet_assets()
    {
        // Main Leaflet CSS & JS
        wp_enqueue_style(
            'hvnly-frontend-property-leaflet',
            esc_url(HVNLYNAB_ASSETS_URL . '/frontend/lib/leaflet/css/leaflet.css'),
            [],
            '1.9.4'
        );
        wp_enqueue_script(
            'hvnly-frontend-property-leaflet',
            esc_url(HVNLYNAB_ASSETS_URL . '/frontend/lib/leaflet/js/leaflet.js'),
            [],
            '1.9.4',
            true
        );
        
        // MarkerCluster
        wp_enqueue_style(
            'hvnly-frontend-property-leaflet-markercluster',
            esc_url(HVNLYNAB_ASSETS_URL . '/frontend/lib/leaflet/css/MarkerCluster.css'),
            [],
            '1.5.3'
        );
        wp_enqueue_style(
            'hvnly-frontend-property-leaflet-markercluster-default',
            esc_url(HVNLYNAB_ASSETS_URL . '/frontend/lib/leaflet/css/MarkerCluster.Default.css'),
            [],
            '1.5.3'
        );
        wp_enqueue_script(
            'hvnly-frontend-property-leaflet-markercluster',
            esc_url(HVNLYNAB_ASSETS_URL . '/frontend/lib/leaflet/js/leaflet.markercluster.js'),
            ['hvnly-frontend-property-leaflet'],
            '1.5.3',
            true
        );
        
        // Fullscreen control
        wp_enqueue_style(
            'hvnly-frontend-property-leaflet-fullscreen',
            esc_url(HVNLYNAB_ASSETS_URL . '/frontend/lib/leaflet/css/Control.FullScreen.css'),
            [],
            '2.4.0'
        );
        wp_enqueue_script(
            'hvnly-frontend-property-leaflet-fullscreen',
            esc_url(HVNLYNAB_ASSETS_URL . '/frontend/lib/leaflet/js/Control.FullScreen.min.js'),
            ['hvnly-frontend-property-leaflet'],
            '2.4.0',
            true
        );
        
       
    }
}