<?php
if ( ! defined( 'ABSPATH' ) ) { exit; }

/**
 * Glance Live Search - Astra theme integration.
 *
 * Replaces the entire Astra search component (icon + form + live search)
 * with the Glance search bar. Neutralizes all Astra search JS/CSS to
 * prevent any conflict with our bar.
 *
 * Activation: Customizer → Glance Live Search → check the box.
 */
class GLSE_Compat_Astra extends GLSE_Compat_Base {

    public function register_customizer( WP_Customize_Manager $wp_customize ): void {
        $this->generic_customizer( $wp_customize, 'astra', 'Astra' );
    }

    public function maybe_override(): void {
        if ( ! $this->generic_setting_enabled( 'astra' ) ) {
            return;
        }
        $this->force_load_assets();

        // 1. Replace the entire Astra search output (icon + form) with our bar.
        add_filter( 'astra_get_search', function () {
            return do_shortcode( '[glance_search]' );
        }, 20, 3 );

        // 2. Replace get_search_form() calls (widgets, templates, legacy headers).
        add_filter( 'astra_get_search_form', function () {
            return do_shortcode( '[glance_search]' );
        } );

        // 3. Disable Astra native live search completely.
        add_filter( 'astra_get_option_live-search', '__return_false' );
        add_action( 'wp_enqueue_scripts', function (): void {
            wp_dequeue_script( 'astra-live-search' );
        }, 20 );

        // 4. Clean up leftover Astra search elements and neutralize JS.
        add_action( 'wp_enqueue_scripts', function (): void {
            wp_add_inline_style( 'glse-style', '
                .ast-live-search-results { display: none !important; }
                .ast-search-menu-icon .search-form,
                .ast-search-menu-icon .ast-search-icon { display: none !important; }
            ' );

            wp_add_inline_script( 'glse-script', '
            (function(){
                var icons = document.getElementsByClassName("astra-search-icon");
                for (var i = 0; i < icons.length; i++) {
                    icons[i].onclick = null;
                }
                document.querySelectorAll(".ast-search-menu-icon").forEach(function(el){
                    el.classList.remove("ast-dropdown-active");
                    el.classList.remove("slide-search");
                });
            })();
            ', 'after' );
        } );
    }
}
