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

/**
 * Glance Live Search - Kadence theme integration.
 *
 * Kadence renders search as a button that opens a fullscreen modal drawer
 * (#search-drawer). The modal is injected in wp_footer via Kadence\search_modal().
 * Inside the modal, the form is rendered via get_search_form() or
 * get_product_search_form() (if WooCommerce enabled).
 *
 * Strategy:
 *   1. Replace the search form inside the modal via get_search_form filter
 *   2. Also replace WooCommerce product search form
 *   3. Style our bar to fit inside Kadence's dark drawer
 *   4. Keep Kadence's button, drawer toggle JS, and focus management intact
 *
 * Activation: Customizer → Glance Live Search → check the box.
 */
class GLSE_Compat_Kadence extends GLSE_Compat_Base {

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

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

        // Replace the search form inside Kadence's modal drawer.
        // Kadence hooks add_search_icon at priority 99 - we go higher to fully replace.
        add_filter( 'get_search_form', function () {
            return do_shortcode( '[glance_search]' );
        }, 100 );

        // Replace WooCommerce product search form if Kadence uses it.
        add_filter( 'get_product_search_form', function () {
            return do_shortcode( '[glance_search]' );
        }, 100 );

        // Style our bar inside Kadence's dark modal drawer.
        add_action( 'wp_enqueue_scripts', function (): void {
            wp_add_inline_style( 'glse-style', '
                /* Ensure our bar fits inside Kadence drawer */
                #search-drawer .glse-search-wrapper {
                    width: 100% !important;
                    max-width: 600px !important;
                    margin: 0 auto !important;
                }

                /* Hide Kadence native search icon added by filter */
                #search-drawer .kadence-search-icon-wrap {
                    display: none !important;
                }

                /* Adapt results dropdown to dark drawer background */
                #search-drawer .glse-results-container {
                    position: absolute !important;
                    z-index: 999999 !important;
                    max-height: 60vh !important;
                }

                /* Override drawer form styling that may interfere */
                #search-drawer .drawer-content form.search-form {
                    display: none !important;
                }
            ' );
        } );
    }
}
