<?php get_header(); ?>

<main class="main-content">
    <div class="container">
        
        <!-- Home Slider Section -->
        <?php 
        $slider_enabled = get_option('pulsegrid_slider_enabled', '1');
        
        if ($slider_enabled === '1') :
            $slider_type = get_option('pulsegrid_slider_type', 'carousel');
            $slider_post_ids = get_option('pulsegrid_slider_posts_ids', array());
            
            if (!empty($slider_post_ids)) :
                $featured_query = new WP_Query(array(
                    'post__in' => $slider_post_ids,
                    'orderby' => 'post__in',
                    'posts_per_page' => -1
                ));
            else :
                $slider_posts_count = get_option('pulsegrid_slider_posts_count', 10);
                $featured_query = new WP_Query(array('posts_per_page' => intval($slider_posts_count)));
            endif;
        
        if ($slider_type === 'fullwidth') : ?>
            <!-- Full Width Backdrop Slider -->
            <section class="fullwidth-slider">
                <div class="fullwidth-slides-container" id="fullwidthSlides"
                     data-autoplay="<?php echo esc_attr(get_option('pulsegrid_slider_autoplay', '0')); ?>"
                     data-interval="<?php echo esc_attr(get_option('pulsegrid_slider_interval', 5)); ?>">
                    <?php
                    if ($featured_query->have_posts()) :
                        while ($featured_query->have_posts()) : $featured_query->the_post();
                            $backdrop = get_post_meta(get_the_ID(), '_tmdb_backdrop', true);
                    ?>
                        <div class="fullwidth-slide">
                            <a href="<?php the_permalink(); ?>">
                                <?php if ($backdrop) : ?>
                                    <img src="<?php echo esc_url($backdrop); ?>" alt="<?php the_title(); ?>">
                                <?php elseif (has_post_thumbnail()) : ?>
                                    <?php the_post_thumbnail('large'); ?>
                                <?php endif; ?>
                                <div class="fullwidth-slide-overlay">
                                    <div class="fullwidth-slide-content">
                                        <h2 class="fullwidth-slide-title"><?php the_title(); ?></h2>
                                    </div>
                                </div>
                            </a>
                        </div>
                    <?php
                        endwhile;
                        wp_reset_postdata();
                    endif;
                    ?>
                </div>
                <button class="fullwidth-slider-btn fullwidth-prev-btn" id="fullwidthPrevBtn">
                    <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                        <path d="m15 18-6-6 6-6"/>
                    </svg>
                </button>
                <button class="fullwidth-slider-btn fullwidth-next-btn" id="fullwidthNextBtn">
                    <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                        <path d="m9 18 6-6-6-6"/>
                    </svg>
                </button>
            </section>
        <?php else : ?>
            <!-- Carousel Slider -->
            <section class="home-slider">
                <div class="slider-wrapper" 
                     data-autoplay="<?php echo esc_attr(get_option('pulsegrid_slider_autoplay', '0')); ?>"
                     data-interval="<?php echo esc_attr(get_option('pulsegrid_slider_interval', 5)); ?>">
                    <button class="slider-btn prev-btn" id="prevBtn">‹</button>
                    <div class="slider-container">
                        <div class="slider-track" id="sliderTrack">
                            <?php
                            if ($featured_query->have_posts()) :
                                while ($featured_query->have_posts()) : $featured_query->the_post();
                            ?>
                                <div class="slider-item">
                                    <a href="<?php the_permalink(); ?>">
                                        <div class="slider-image">
                                            <?php if (has_post_thumbnail()) : ?>
                                                <div class="post-thumbnail-wrapper">
                                                    <img src="<?php the_post_thumbnail_url('medium'); ?>" alt="<?php the_title(); ?>">
                                                    <?php echo pulsegrid_get_tmdb_badges(get_the_ID()); ?>
                                                </div>
                                            <?php else : ?>
                                                <div class="no-image-placeholder">
                                                    Sin imagen
                                                </div>
                                            <?php endif; ?>
                                        </div>
                                        <div class="slider-title">
                                            <h4><?php the_title(); ?></h4>
                                        </div>
                                    </a>
                                </div>
                            <?php
                                endwhile;
                                wp_reset_postdata();
                            endif;
                            ?>
                        </div>
                    </div>
                    <button class="slider-btn next-btn" id="nextBtn">›</button>
                </div>
            </section>
        <?php 
        endif; // End slider type check
        endif; // End slider enabled check
        ?>

        <!-- Search Section -->
        <?php 
        $search_enabled = get_option('pulsegrid_search_enabled', '1');
        if ($search_enabled === '1') :
        ?>
        <section class="search-section">
            <form role="search" method="get" class="search-form" action="<?php echo home_url('/'); ?>">
                <input type="search" class="search-input" placeholder="Buscar..." value="<?php echo get_search_query(); ?>" name="s" />
                <button type="submit" class="search-submit">Buscar</button>
            </form>
        </section>
        <?php endif; ?>

        <!-- Home Ad -->
        <?php 
        $home_ad = get_option('pulsegrid_home_ad', '');
        if (!empty($home_ad)) : 
        ?>
        <div class="home-ad-container">
            <?php echo $home_ad; ?>
        </div>
        <?php endif; ?>

        <!-- Dynamic Category Sections -->
        <?php
        $home_sections = get_option('pulsegrid_home_sections', array());
        
        if (!empty($home_sections)) :
            foreach ($home_sections as $section) :
                // Skip disabled sections
                if (!isset($section['enabled']) || !$section['enabled']) {
                    continue;
                }
                
                $section_title = isset($section['title']) ? $section['title'] : '';
                $section_type = isset($section['type']) ? $section['type'] : 'category';
                $section_category = isset($section['category']) ? intval($section['category']) : 0;
                $section_tag = isset($section['tag']) ? intval($section['tag']) : 0;
                $section_posts_count = isset($section['posts_count']) ? intval($section['posts_count']) : 14;
                
                // Prepare query arguments based on type
                $query_args = array(
                    'posts_per_page' => $section_posts_count,
                    'post_status' => 'publish'
                );
                
                switch ($section_type) {
                    case 'category':
                        // Skip if no category selected
                        if (empty($section_category)) {
                            continue 2;
                        }
                        $query_args['cat'] = $section_category;
                        $section_link = get_category_link($section_category);
                        break;
                        
                    case 'tag':
                        // Skip if no tag selected
                        if (empty($section_tag)) {
                            continue 2;
                        }
                        $query_args['tag_id'] = $section_tag;
                        $section_link = get_tag_link($section_tag);
                        break;
                        
                    case 'latest':
                        // Exclude posts marked to be hidden from latest posts
                        $query_args['meta_query'] = array(
                            'relation' => 'OR',
                            array(
                                'key' => '_pulsegrid_exclude_from_latest',
                                'compare' => 'NOT EXISTS'
                            ),
                            array(
                                'key' => '_pulsegrid_exclude_from_latest',
                                'value' => '1',
                                'compare' => '!='
                            )
                        );
                        
                        // Link to the Últimos Posts page - use Customizer setting first
                        $ultimos_page_id = get_theme_mod('pulsegrid_ultimos_posts_page', '');
                        $ultimos_page = null;
                        
                        // Method 1: Use selected page from Customizer
                        if (!empty($ultimos_page_id)) {
                            $ultimos_page = get_post($ultimos_page_id);
                        }
                        
                        // Method 2: By title if Customizer not set
                        if (!$ultimos_page) {
                            $ultimos_page = get_page_by_title('Últimos Posts');
                        }
                        
                        // Method 3: By page template if title fails
                        if (!$ultimos_page) {
                            $pages_with_template = get_pages(array(
                                'meta_key' => '_wp_page_template',
                                'meta_value' => 'template-ultimos-posts.php'
                            ));
                            if (!empty($pages_with_template)) {
                                $ultimos_page = $pages_with_template[0];
                            }
                        }
                        
                        // Method 4: By custom query if all else fails
                        if (!$ultimos_page) {
                            $args = array(
                                'post_type' => 'page',
                                'post_status' => 'publish',
                                'meta_query' => array(
                                    array(
                                        'key' => '_wp_page_template',
                                        'value' => 'template-ultimos-posts.php'
                                    )
                                )
                            );
                            $pages = get_posts($args);
                            if (!empty($pages)) {
                                $ultimos_page = $pages[0];
                            }
                        }
                        
                        if ($ultimos_page) {
                            $section_link = get_permalink($ultimos_page->ID);
                        } else {
                            // Fallback to blog/posts page
                            $section_link = get_post_type_archive_link('post');
                            if (empty($section_link)) {
                                $section_link = get_home_url('/') . '?post_type=post';
                            }
                        }
                        break;
                        
                    default:
                        continue 2; // Skip invalid types
                }
                
                $section_posts = new WP_Query($query_args);
                
                if ($section_posts->have_posts()) :
        ?>
        <section class="category-section">
            <div class="section-header">
                <h2 class="section-title"><?php echo esc_html($section_title); ?></h2>
                <a href="<?php echo esc_url($section_link); ?>" class="view-more-link">
                    + Ver Más
                </a>
            </div>
            
            <div class="posts-grid posts-grid-vertical">
                <?php
                while ($section_posts->have_posts()) : $section_posts->the_post();
                ?>
                    <article class="post-item">
                        <a href="<?php the_permalink(); ?>">
                            <?php pulsegrid_post_thumbnail_with_badges('medium'); ?>
                        </a>
                        <div class="post-content">
                            <h3 class="post-title">
                                <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
                            </h3>
                            <?php 
                            $episode_number = get_post_meta(get_the_ID(), '_tmdb_episode_number', true);
                            if (!empty($episode_number)) : 
                            ?>
                                <div class="post-episode-number">Episodio <?php echo esc_html($episode_number); ?></div>
                            <?php endif; ?>
                        </div>
                    </article>
                <?php
                endwhile;
                wp_reset_postdata();
                ?>
            </div>
        </section>
        <?php
                endif;
            endforeach;
        endif;
        ?>

    </div>
</main>

<?php get_footer(); ?>
