<?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' );

function bw_enqueue_scripts() {
    
    // Enqueue BW Slide Content styles with cache busting - ALWAYS load
    wp_enqueue_style(
        'bw-slide-content-frontend', 
        get_stylesheet_directory_uri() . '/blocks/bw-slide-content/style.css',
        array(),
        filemtime(get_stylesheet_directory() . '/blocks/bw-slide-content/style.css')
    );
    
    // BW Slider Production Script
    wp_enqueue_script(
        'bw-slider-production',
        get_stylesheet_directory_uri() . '/js/bw-slider-production.js',
        array(), // No dependencies - standalone
        filemtime(get_stylesheet_directory() . '/js/bw-slider-production.js'),
        true // Load in footer
    );
    
    // Add critical inline CSS to ensure slides work
    wp_add_inline_style('bw-slide-content-frontend', '
        /* CRITICAL: Force hide inactive slides */
        .bw-slide-content .bw-slide-content__slide:not(.active) {
            display: none !important;
            opacity: 0 !important;
            visibility: hidden !important;
            pointer-events: none !important;
        }
        
        /* CRITICAL: Force show active slides */
        .bw-slide-content .bw-slide-content__slide.active {
            display: flex !important;
            opacity: 1 !important;
            visibility: visible !important;
            pointer-events: auto !important;
        }
        
        /* Ensure indicators are clickable */
        .bw-slide-content__indicator {
            cursor: pointer !important;
            pointer-events: auto !important;
            z-index: 999 !important;
        }
        
        /* Ensure next preview is clickable */
        .bw-slide-content__next-preview {
            cursor: pointer !important;
            pointer-events: auto !important;
            z-index: 10 !important;
        }
    ');
}
add_action('wp_enqueue_scripts', 'bw_enqueue_scripts');




/**
 * Force update term counts for gallery-category taxonomy.
 */
function update_gallery_category_counts() {
    $taxonomy = 'gallery-category';
    $terms = get_terms(array('taxonomy' => $taxonomy, 'hide_empty' => false));
    
    if (is_wp_error($terms) || empty($terms)) {
        return;
    }
    
    foreach ($terms as $term) {
        if (is_object($term) && isset($term->term_id)) {
            wp_update_term_count_now(array($term->term_id), $taxonomy);
        } elseif (is_array($term) && isset($term['term_id'])) {
            wp_update_term_count_now(array($term['term_id']), $taxonomy);
        }
    }
}
add_action('admin_init', 'update_gallery_category_counts');

/**
 * Shortcode for Filterable Gallery with Lightbox
 */
function bw_filterable_gallery($atts) {
    $atts = shortcode_atts(array(
        'columns' => 3, 
        'thumb_size' => 350 
    ), $atts, 'bw_gallery');

    // Get all media categories in gallery-category taxonomy
    $categories = get_terms(array(
        'taxonomy' => 'gallery-category',
        'hide_empty' => false, // Set to false to ensure all terms are loaded
    ));

    ob_start();
    ?>

    <div id="gallery-filters">
        <button class="filter-button" data-filter="all">All</button>
        <?php foreach ($categories as $category) : ?>
            <button class="filter-button" data-filter="<?php echo esc_attr($category->slug); ?>">
                <?php echo esc_html($category->name); ?>
            </button>
        <?php endforeach; ?>
    </div>

    <div id="gallery-items" style="grid-template-columns: repeat(<?php echo intval($atts['columns']); ?>, 1fr);">
        <?php
        $media_items = get_posts(array(
            'post_type' => 'attachment',
            'post_status' => 'inherit',
            'posts_per_page' => -1,
            'tax_query' => array(
                array(
                    'taxonomy' => 'gallery-category',
                    'field' => 'slug',
                    'terms' => wp_list_pluck($categories, 'slug'),
                ),
            ),
        ));

        foreach ($media_items as $item) :
            $item_categories = wp_get_post_terms($item->ID, 'gallery-category');
            $item_category_slugs = join(' ', wp_list_pluck($item_categories, 'slug'));
            $full_image_url = wp_get_attachment_image_url($item->ID, 'full'); 
            $image_title = get_the_title($item->ID);
            ?>
            <div class="gallery-item" data-category="<?php echo esc_attr($item_category_slugs); ?>">
                <a href="<?php echo esc_url($full_image_url); ?>" class="lightbox-link" data-title="<?php echo esc_attr($image_title); ?>">
                    <?php echo wp_get_attachment_image($item->ID, array($atts['thumb_size'], $atts['thumb_size']), false, array('style' => 'aspect-ratio: 1/1; object-fit: cover; width: 100%;')); ?>
                </a>
            </div>
        <?php endforeach; ?>
    </div>

    <style>
        #gallery-filters { text-align: center; margin-bottom: 20px; }
        .filter-button { cursor: pointer; padding: 10px 20px; margin: 5px; transition: all 0.3s ease; }
        #gallery-items { display: grid; gap: 15px; }
        .gallery-item img { width: 100%; aspect-ratio: 1 / 1; object-fit: cover; transition: transform 0.3s ease; }
        
        .lightbox-overlay {
            display: none;
            position: fixed;
            top: 0; left: 0; right: 0; bottom: 0;
            background: rgba(0, 0, 0, 0.8);
            justify-content: center;
            align-items: center;
            z-index: 9999;
            flex-direction: column;
            opacity: 0;
            transition: opacity 0.3s ease;
        }
        .lightbox-overlay.show { display: flex; opacity: 1; }
        .lightbox-image { max-width: 90%; max-height: 80%; margin-bottom: 15px; transition: all 0.3s ease; }
        .lightbox-title { color: #fff; text-align: center; font-size: 18px; }
        
        .lightbox-arrow { position: absolute; top: 50%; transform: translateY(-50%); color: #fff; font-size: 30px; cursor: pointer; user-select: none; transition: all 0.3s ease; }
        .lightbox-arrow.left { left: 20px; }
        .lightbox-arrow.right { right: 20px; }
        .lightbox-close { position: absolute; top: 20px; right: 20px; color: #fff; font-size: 30px; cursor: pointer; transition: all 0.3s ease; }
    </style>

    <div class="lightbox-overlay" id="lightbox-overlay">
        <span class="lightbox-arrow left" id="lightbox-prev">&#10094;</span>
        <img src="" alt="Lightbox Image" class="lightbox-image" id="lightbox-image">
        <div class="lightbox-title" id="lightbox-title"></div>
        <span class="lightbox-arrow right" id="lightbox-next">&#10095;</span>
        <span class="lightbox-close" id="lightbox-close">&#10005;</span>
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', function () {
            var filterButtons = document.querySelectorAll('.filter-button');
            var galleryItems = document.querySelectorAll('.gallery-item');
            var lightboxOverlay = document.getElementById('lightbox-overlay');
            var lightboxImage = document.getElementById('lightbox-image');
            var lightboxTitle = document.getElementById('lightbox-title');
            var currentIndex = -1;
            var lightboxLinks = Array.from(document.querySelectorAll('.lightbox-link'));

            function disableScroll() { document.body.style.overflow = 'hidden'; }
            function enableScroll() { document.body.style.overflow = ''; }

            filterButtons.forEach(function (button) {
                button.addEventListener('click', function () {
                    var filter = this.getAttribute('data-filter');
                    galleryItems.forEach(function (item) {
                        if (filter === 'all' || item.getAttribute('data-category').includes(filter)) {
                            item.style.display = 'inline-block';
                        } else {
                            item.style.display = 'none';
                        }
                    });
                });
            });

            lightboxLinks.forEach(function (link, index) {
                link.addEventListener('click', function (event) {
                    event.preventDefault();
                    currentIndex = index;
                    openLightbox(link);
                });
            });

            function openLightbox(link) {
                lightboxImage.src = link.href;
                lightboxTitle.textContent = link.getAttribute('data-title');
                lightboxOverlay.classList.add('show');
                disableScroll();
            }

            document.getElementById('lightbox-next').addEventListener('click', function () {
                currentIndex = (currentIndex + 1) % lightboxLinks.length;
                openLightbox(lightboxLinks[currentIndex]);
            });
            document.getElementById('lightbox-prev').addEventListener('click', function () {
                currentIndex = (currentIndex - 1 + lightboxLinks.length) % lightboxLinks.length;
                openLightbox(lightboxLinks[currentIndex]);
            });

            function closeLightbox() {
                lightboxOverlay.classList.remove('show');
                lightboxImage.src = '';
                enableScroll();
            }
            document.getElementById('lightbox-close').addEventListener('click', closeLightbox);
            lightboxOverlay.addEventListener('click', function (e) {
                if (e.target === lightboxOverlay) closeLightbox();
            });
        });
    </script>
    <?php

    return ob_get_clean();
}
add_shortcode('bw_gallery', 'bw_filterable_gallery');

/**
 * Register custom Gutenberg blocks
 */
function bw_register_blocks() {
    // Check if block is already registered to prevent duplicate registration
    $registry = WP_Block_Type_Registry::get_instance();
    
    if ( ! $registry->is_registered( 'bw/step-layout' ) ) {
        // Include native block with minimal JS (this is the main registration)
        require_once get_stylesheet_directory() . '/blocks/bw-step-layout/native-block.php';
    }
    
    // Include the Step Layout pattern (this doesn't register the block, just patterns)
    require_once get_stylesheet_directory() . '/blocks/bw-step-layout/pattern.php';
    
    // Include BW Slide Content block (working version)
    require_once get_stylesheet_directory() . '/blocks/bw-slide-content/block.php';

    // Include BW Separator block
    if ( ! $registry->is_registered( 'bw/separator' ) ) {
        require_once get_stylesheet_directory() . '/blocks/bw-separator/block.php';
    }
}
add_action('init', 'bw_register_blocks', 5);

/**
 * Enqueue block styles for frontend and editor
 */
function bw_enqueue_block_styles() {
    // Enqueue Step Layout styles
    wp_enqueue_style(
        'bw-step-layout-style',
        get_stylesheet_directory_uri() . '/blocks/bw-step-layout/style-index.css',
        array(),
        filemtime(get_stylesheet_directory() . '/blocks/bw-step-layout/style-index.css')
    );
}
add_action('wp_enqueue_scripts', 'bw_enqueue_block_styles');
add_action('enqueue_block_editor_assets', 'bw_enqueue_block_styles');

/**
 * Shortcode for Step Layout
 */
function bw_step_layout_shortcode($atts) {
    $atts = shortcode_atts(array(
        'direction' => 'low-to-high',
        'card1_title' => 'Dining',
        'card1_desc' => 'Hartling Group Resorts showcase the very best in Turks and Caicos restaurant experiences.',
        'card1_button' => 'DISCOVER MORE',
        'card1_url' => '#',
        'card1_image' => '',
        'card2_title' => 'Retail & Spa',
        'card2_desc' => 'Each of the Hartling Group resorts comes complete with exceptional, on-site shopping opportunities.',
        'card2_button' => 'EXPLORE',
        'card2_url' => '#',
        'card2_image' => '',
        'card3_title' => 'PRIVE Fine Ocean Charters',
        'card3_desc' => 'Offering a variety of exclusive services like offshore fishing and diving.',
        'card3_button' => 'LEARN MORE',
        'card3_url' => '#',
        'card3_image' => '',
    ), $atts, 'bw_step_layout');

    $cards = array(
        array(
            'title' => $atts['card1_title'],
            'description' => $atts['card1_desc'],
            'buttonText' => $atts['card1_button'],
            'buttonUrl' => $atts['card1_url'],
            'backgroundImage' => $atts['card1_image'],
        ),
        array(
            'title' => $atts['card2_title'],
            'description' => $atts['card2_desc'],
            'buttonText' => $atts['card2_button'],
            'buttonUrl' => $atts['card2_url'],
            'backgroundImage' => $atts['card2_image'],
        ),
        array(
            'title' => $atts['card3_title'],
            'description' => $atts['card3_desc'],
            'buttonText' => $atts['card3_button'],
            'buttonUrl' => $atts['card3_url'],
            'backgroundImage' => $atts['card3_image'],
        ),
    );

    ob_start();
    ?>
    <div class="bw-step-layout bw-step-layout--<?php echo esc_attr($atts['direction']); ?>">
        <div class="bw-step-layout__inner">
            <?php 
            foreach ($cards as $index => $card) : 
                $card_class = 'bw-step-layout__card bw-step-layout__card--' . ($index + 1);
                $has_image = !empty($card['backgroundImage']);
            ?>
                <div class="<?php echo esc_attr($card_class); ?>" <?php if ($has_image) : ?>data-has-image="true"<?php endif; ?>>
                    <?php if ($has_image) : ?>
                        <div class="bw-step-layout__background">
                            <img src="<?php echo esc_url($card['backgroundImage']); ?>" alt="" />
                        </div>
                    <?php endif; ?>
                    
                    <div class="bw-step-layout__content">
                        <h3 class="bw-step-layout__title"><?php echo esc_html($card['title']); ?></h3>
                        <p class="bw-step-layout__description"><?php echo esc_html($card['description']); ?></p>
                        
                        <?php if (!empty($card['buttonText']) && !empty($card['buttonUrl'])) : ?>
                            <a href="<?php echo esc_url($card['buttonUrl']); ?>" class="bw-step-layout__button">
                                <?php echo esc_html($card['buttonText']); ?>
                            </a>
                        <?php endif; ?>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>
    </div>
    <?php
    return ob_get_clean();
}
add_shortcode('bw_step_layout', 'bw_step_layout_shortcode');

/**
 * Register Team Group Taxonomy
 */
function bw_register_team_group_taxonomy() {
    // Register the taxonomy even if post type doesn't exist yet
    // WordPress will attach it when the post type is registered
    
    $labels = array(
        'name'                       => _x( 'Team Groups', 'taxonomy general name', 'kadence-child' ),
        'singular_name'              => _x( 'Team Group', 'taxonomy singular name', 'kadence-child' ),
        'search_items'               => __( 'Search Team Groups', 'kadence-child' ),
        'popular_items'              => __( 'Popular Team Groups', 'kadence-child' ),
        'all_items'                  => __( 'All Team Groups', 'kadence-child' ),
        'parent_item'                => __( 'Parent Team Group', 'kadence-child' ),
        'parent_item_colon'          => __( 'Parent Team Group:', 'kadence-child' ),
        'edit_item'                  => __( 'Edit Team Group', 'kadence-child' ),
        'update_item'                => __( 'Update Team Group', 'kadence-child' ),
        'add_new_item'               => __( 'Add New Team Group', 'kadence-child' ),
        'new_item_name'              => __( 'New Team Group Name', 'kadence-child' ),
        'separate_items_with_commas' => __( 'Separate team groups with commas', 'kadence-child' ),
        'add_or_remove_items'        => __( 'Add or remove team groups', 'kadence-child' ),
        'choose_from_most_used'      => __( 'Choose from the most used team groups', 'kadence-child' ),
        'not_found'                  => __( 'No team groups found.', 'kadence-child' ),
        'menu_name'                  => __( 'Team Groups', 'kadence-child' ),
        'back_to_items'              => __( '← Back to Team Groups', 'kadence-child' ),
    );
    
    $args = array(
        'labels'                     => $labels,
        'hierarchical'               => true, // Set to true for category-like behavior, false for tag-like
        'public'                     => true,
        'publicly_queryable'         => true,
        'show_ui'                    => true,
        'show_in_menu'               => true,
        'show_in_nav_menus'          => true,
        'show_in_rest'               => true, // Enable for Gutenberg editor
        'show_tagcloud'              => true,
        'show_in_quick_edit'         => true,
        'show_admin_column'          => true,
        'description'                => __( 'Groups for organizing team members', 'kadence-child' ),
        'rewrite'                    => array(
            'slug'         => 'team-group',
            'with_front'   => false,
            'hierarchical' => true,
        ),
        'query_var'                  => true,
        'default_term'               => array(
            'name' => __( 'General', 'kadence-child' ),
            'slug' => 'general',
        ),
    );
    
    // Register the taxonomy with the proper slug 'tgroup'
    register_taxonomy( 'tgroup', array( 'team' ), $args );
}
// Use priority 20 to ensure this runs after most post types are registered
add_action( 'init', 'bw_register_team_group_taxonomy', 20 );

