<?php
/**
 * Enqueue child styles.
 */
function child_enqueue_styles() {
    wp_enqueue_style( 'child-theme', get_stylesheet_directory_uri() . '/style.css', array(), 100 );
}

add_action( 'wp_enqueue_scripts', 'child_enqueue_styles' );


/**
 * Add "current-menu-item" class to Kadence Advanced Buttons if URL matches.
 */
function add_active_class_to_kadence_buttons( $block_content, $block ) {
    // 1. Target only Kadence Single Button blocks to avoid performance impact
    if ( 'kadence/singlebtn' !== $block['blockName'] ) {
        return $block_content;
    }

    // 2. Get the current page URL
    global $wp;
    // Construct the current URL
    $current_url = home_url( add_query_arg( array(), $wp->request ) );
    
    // 3. Extract the link (href) from the button's HTML using Regex
    // This finds the url inside href="..."
    if ( preg_match( '/href=["\']?([^"\'>]+)["\']?/', $block_content, $matches ) ) {
        $button_url = $matches[1];

        // 4. Normalize URLs (remove trailing slashes) for accurate comparison
        // This ensures "site.com/news" matches "site.com/news/"
        if ( untrailingslashit( $button_url ) === untrailingslashit( $current_url ) ) {
            
            // 5. Inject the custom class into the HTML
            // We search for 'class="' and add our custom class right after it.
            $block_content = str_replace( 'class="', 'class="current-btn-active ', $block_content );
        }
    }

    return $block_content;
}
add_filter( 'render_block', 'add_active_class_to_kadence_buttons', 10, 2 );

/**
 * Team Grid: Make image overlay clickable to open corresponding modal
 * Triggers the modal button click instead of manipulating modal attributes directly
 */
function archipelago_team_image_modal_script() {
    ?>
    <script>
    document.addEventListener('DOMContentLoaded', function () {
        // Select all query loop items
        var items = document.querySelectorAll('li.kb-query-item, .kb-query-item');

        items.forEach(function (item, index) {
            try {
                // Find modal trigger inside this item (button with data-modal-open)
                var modalTrigger = item.querySelector('[data-modal-open]');

                // Find the image overlay wrap
                var imgOverlay = item.querySelector('.wp-block-kadence-imageoverlay .kt-image-overlay-wrap');

                if (!modalTrigger || !imgOverlay) {
                    return;
                }

                // Add pointer cursor
                imgOverlay.style.cursor = 'pointer';

                var handleClick = function (evt) {
                    evt.preventDefault();
                    evt.stopPropagation();

                    // Focus on modal trigger for accessibility
                    try { modalTrigger.focus({preventScroll: true}); } catch (e) {}

                    // Trigger the click on the modal trigger button
                    modalTrigger.click();
                };

                // Attach click listener (only once)
                if (!imgOverlay.modalListenerAttached) {
                    imgOverlay.addEventListener('click', handleClick);
                    imgOverlay.modalListenerAttached = true;
                }

                // Keyboard accessibility (Enter / Space)
                imgOverlay.setAttribute('tabindex', imgOverlay.getAttribute('tabindex') || '0');
                imgOverlay.addEventListener('keydown', function (e) {
                    if (e.key === 'Enter' || e.key === ' ') {
                        e.preventDefault();
                        handleClick(e);
                    }
                });

            } catch (err) {
                console.error('Team modal binding error for item', index, err);
            }
        });
    });
    </script>
    <?php
}
add_action( 'wp_footer', 'archipelago_team_image_modal_script' );

/**
 * Register ACF field for Hero Header Text on pages.
 */
function archipelago_register_hero_header_field() {
    if ( ! function_exists( 'acf_add_local_field_group' ) ) {
        return;
    }

    acf_add_local_field_group( array(
        'key'      => 'group_hero_header_text',
        'title'    => 'Hero Header Text',
        'fields'   => array(
            array(
                'key'          => 'field_hero_header_text',
                'label'        => 'Header Text',
                'name'         => 'hero_header_text',
                'type'         => 'textarea',
                'instructions' => 'Text displayed below the page title in the hero banner.',
                'rows'         => 3,
                'new_lines'    => 'br',
            ),
        ),
        'location' => array(
            array(
                array(
                    'param'    => 'post_type',
                    'operator' => '==',
                    'value'    => 'page',
                ),
            ),
        ),
        'position'            => 'normal',
        'style'               => 'default',
        'menu_order'          => 0,
        'hide_on_screen'      => '',
    ) );
}
add_action( 'acf/init', 'archipelago_register_hero_header_field' );

/**
 * Display Hero Header Text after the page title in Kadence hero section.
 */
function archipelago_hero_header_text( $post_type, $location ) {
    if ( 'above' !== $location ) {
        return;
    }
    if ( ! is_singular( 'page' ) ) {
        return;
    }
    $header_text = get_field( 'hero_header_text' );
    if ( ! $header_text ) {
        return;
    }
    echo '<p class="hero-header-subtitle">' . wp_kses_post( $header_text ) . '</p>';
}
add_action( 'kadence_entry_hero', 'archipelago_hero_header_text', 20, 2 );

