<?php
/*
*  Template Name: 分类模板
*/
?>
<?php get_header() ?>

<!-- 新闻搜索功能模块 -->

<section class="mt-[80px] relative w-full h-[52vh] md:h-[45vh] min-h-[400px] max-h-[500px] flex flex-col justify-center overflow-hidden bg-slate-50 border-b border-slate-200/60">

    <!-- 背景网格特效 -->
    <div class="absolute inset-0 opacity-[0.03] pointer-events-none" style="background-image: linear-gradient(#10b981 1px, transparent 1px), linear-gradient(90deg, #10b981 1px, transparent 1px); background-size: 32px 32px;"></div>

    <!-- 左上角光晕 -->
    <div class="absolute top-0 left-0 w-[600px] h-[600px] bg-primary-light/40 rounded-full mix-blend-multiply filter blur-[100px] opacity-70 -translate-x-1/2 -translate-y-1/2 pointer-events-none"></div>

    <!-- 右下角光晕 -->
    <div class="absolute bottom-0 right-0 w-[500px] h-[500px] bg-accent-light/20 rounded-full mix-blend-multiply filter blur-[80px] opacity-60 translate-x-1/3 translate-y-1/3 pointer-events-none"></div>

    <!-- 核心内容区 -->
    <div class="relative z-10 max-w-7xl mx-auto px-6 lg:px-8 w-full text-center aos-init aos-animate" data-aos="fade-up" data-aos-duration="1000">

        <!-- 标签栏 -->
        <div class="inline-flex items-center justify-center gap-2 px-4 py-1.5 rounded-full bg-white shadow-sm border border-primary/10 text-primary-dark text-sm font-bold tracking-widest mb-6">
            <span class="material-symbols-outlined text-[16px] text-primary">newspaper</span>
            最新资讯
        </div>

        <!-- 主标题 -->
        <h1 class="font-display text-[2.66rem] md:text-5xl font-black text-slate-800 tracking-wide leading-tight mb-4">
            新闻中心
        </h1>

        <!-- 描述文本 -->
        <p class="text-slate-500 text-[1rem] max-w-2xl mx-auto leading-relaxed font-medium mb-10">
            关注企业最新动态、行业前沿资讯及重大活动报道，与您分享我们的成长与洞察。
        </p>

        <!-- 整合的 WordPress 搜索表单 -->
        <div class="search-form-wrapper max-w-3xl mx-auto">
            <?php
            $form_action = home_url('/');
            if (is_page()) {
                $form_action = get_permalink(get_queried_object_id());
            } elseif (is_category()) {
                $form_action = get_category_link(get_queried_object_id());
            }
            ?>
            <form class="news-search-form relative" method="get" action="<?php echo esc_url($form_action); ?>">
                <!-- 添加了 Tailwind 样式构建一体式圆角搜索栏 -->
                <div class="search-controls flex items-center bg-white rounded-full shadow-lg hover:shadow-xl transition-shadow duration-300 border border-slate-200/60 p-1.5">
                    
                    <!-- 分类选择下拉菜单 -->
                    <div class="category-selector relative flex-shrink-0  border-slate-200 ">
                        <?php
                        $current_cat = isset($_GET['category']) ? $_GET['category'] : '';
                        if (empty($current_cat) && is_category()) {
                            $current_cat = get_queried_object()->slug;
                        }
                        ?>
                        <select name="category" id="news-category" class="category-dropdown w-38 bg-transparent border-none text-slate-600 text-sm font-medium focus:ring-0 cursor-pointer pl-5 pr-8 py-3 appearance-none outline-none">
                            <option value="" data-url="<?php echo esc_url(home_url('/category/news-center/')); ?>" <?php selected(empty($current_cat) || $current_cat === 'news-center', true); ?>>显示全部</option>
                            <?php
                            $categories = get_categories(array(
                                'hide_empty' => false,
                                'orderby' => 'name',
                                'order' => 'ASC'
                            ));
                            foreach ($categories as $category) {
                                if ($category->slug === 'news-center') continue;
                                $cat_link = get_category_link($category->term_id);
                                echo '<option value="' . esc_attr($category->slug) . '" data-url="' . esc_url($cat_link) . '" ' . selected($current_cat, $category->slug, false) . '>' . esc_html($category->name) . '</option>';
                            }
                            ?>
                        </select>
                        <!-- 自定义下拉箭头图标 -->
                        <div class="absolute right-3 top-1/2 -translate-y-1/2 pointer-events-none text-slate-400">
                            <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7"></path></svg>
                        </div>
                    </div>
                    
                    <!-- 搜索输入框 -->
                    <div class="search-input-wrapper relative flex-grow">
                        <input type="text" name="search_keyword" id="news-search" 
                               class="search-input w-full bg-transparent border-none text-slate-700 text-[15px] placeholder-slate-400 focus:ring-0 px-5 py-3 outline-none" 
                               placeholder="输入关键词搜索新闻资讯..." 
                               value="<?php echo isset($_GET['search_keyword']) ? esc_attr($_GET['search_keyword']) : ''; ?>"
                               autocomplete="off">
                        <div class="search-suggestions absolute top-full left-0 w-full mt-2 bg-white rounded-xl shadow-xl z-50" id="search-suggestions"></div>
                    </div>
                    
                    <!-- 搜索按钮 -->
                    <button type="submit" class="search-button flex items-center justify-center w-12 h-12 bg-primary hover:bg-primary-dark active:scale-95 text-white rounded-full transition-all duration-200 flex-shrink-0 group">
                        <svg width="20" height="20" viewBox="0 0 20 20" fill="none" class="group-hover:scale-110 transition-transform duration-200">
                            <path d="M19 19L13 13M15 8C15 11.866 11.866 15 8 15C4.134 15 1 11.866 1 8C1 4.134 4.134 1 8 1C11.866 1 15 4.134 15 8Z" stroke="white" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"/>
                        </svg>
                    </button>
                </div>
                <input type="hidden" name="post_type" value="post">
            </form>
        </div>

    </div>

    <!-- 底部渐变线条 -->
    <div class="absolute bottom-0 left-1/2 -translate-x-1/2 w-1/3 h-[2px] bg-gradient-to-r from-transparent via-primary/40 to-transparent"></div>

</section>


<!-- ================= 1. 新闻中心头部 & 搜索区 ================= -->


<!-- ================= 2. 文章列表区 ================= -->
<div class="article-list-section py-16 md:py-24 bg-background">
    <div class="container max-w-6xl mx-auto px-6 lg:px-8">
        <div class="article-list-wrapper">
            <?php
            // 获取当前页码
            $paged = get_query_var('paged') ? get_query_var('paged') : (get_query_var('page') ? get_query_var('page') : 1);
            
            // 构建查询参数
            $args = array(
                'post_type' => 'post',
                'posts_per_page' => 5,
                'post_status' => 'publish',
                'orderby' => 'date',
                'order' => 'DESC',
                'paged' => $paged
            );

            if (is_category()) {
                $args['cat'] = get_query_var('cat');
            }

            // 处理分类筛选
            if (isset($_GET['category']) && !empty($_GET['category'])) {
                $args['category_name'] = sanitize_text_field($_GET['category']);
                if (isset($args['cat'])) {
                    unset($args['cat']);
                }
            }

            // 处理关键词搜索
            if (isset($_GET['search_keyword']) && !empty($_GET['search_keyword'])) {
                $args['s'] = sanitize_text_field($_GET['search_keyword']);
            }

            $articles_query = new WP_Query($args);

            if ($articles_query->have_posts()) :
                while ($articles_query->have_posts()) : $articles_query->the_post();
                    $featured_image = get_the_post_thumbnail_url(get_the_ID(), 'medium_large');
                    if (!$featured_image) {
                        $featured_image = get_template_directory_uri() . '/assets/images/default-post.jpg';
                    }
                    $excerpt = get_the_excerpt();
                    if (empty($excerpt)) {
                        $excerpt = wp_trim_words(get_the_content(), 20, '...');
                    }
                    $post_date = get_the_date('Y-m-d');
            ?>
            
            <!-- 单个文章卡片 -->
            <div class="article-list-item group flex flex-col md:flex-row gap-6 md:gap-8 mb-8 p-4 md:p-5 bg-white rounded-2xl border border-slate-100 shadow-[0_4px_20px_-4px_rgba(0,0,0,0.03)] hover:shadow-[0_8px_30px_-4px_rgba(0,0,0,0.08)] transition-all duration-300">
                
                <!-- 左侧：文章图片 -->
                <div class="article-image w-full md:w-[280px] lg:w-[320px] aspect-[4/3] md:aspect-[3/2] flex-shrink-0 rounded-xl overflow-hidden relative">
                    <a href="<?php echo esc_url(get_permalink()); ?>" class="block w-full h-full">
                        <img src="<?php echo esc_url($featured_image); ?>" alt="<?php echo esc_attr(get_the_title()); ?>" class="w-full h-full object-cover group-hover:scale-105 transition-transform duration-700 ease-out">
                    </a>
                </div>

                <!-- 右侧：文章内容 -->
                <div class="article-content flex flex-col justify-center flex-grow py-2 md:pr-4">
                    <div class="article-meta flex items-center gap-2 mb-3">
                        <span class="inline-block px-3 py-1 bg-slate-50 text-slate-500 rounded-md text-sm font-medium">
                            <?php echo esc_html($post_date); ?>
                        </span>
                    </div>
                    
                    <h3 class="article-title text-xl md:text-2xl font-bold text-slate-800 mb-3 line-clamp-2">
                        <a href="<?php echo esc_url(get_permalink()); ?>" class="hover:text-primary transition-colors duration-200">
                            <?php echo esc_html(get_the_title()); ?>
                        </a>
                    </h3>
                    
                    <p class="article-excerpt text-slate-500 leading-relaxed mb-6 line-clamp-2 flex-grow">
                        <?php echo esc_html($excerpt); ?>
                    </p>
                    
                    <div class="article-actions mt-auto">
                        <a href="<?php echo esc_url(get_permalink()); ?>" class=" inline-flex items-center gap-2 text-sm font-bold text-slate-800 hover:text-primary transition-colors">
                            阅读详情 
                            <span class="flex items-center justify-center w-8 h-8 rounded-full bg-slate-100 group-hover:bg-primary group-hover:text-white transition-colors duration-300">
                                &rarr;
                            </span>
                        </a>
                    </div>
                </div>
            </div>

            <?php
                endwhile;
                wp_reset_postdata();

                // 强大的分页器美化 (使用 Tailwind 的级联任意选择器)
                $total_pages = $articles_query->max_num_pages;
                if ($total_pages > 1) {
                    echo '<nav class="pagination mt-14 flex flex-wrap justify-center items-center gap-2 
                        [&>a]:flex [&>a]:items-center [&>a]:justify-center [&>a]:w-10 [&>a]:h-10 [&>a]:rounded-lg [&>a]:bg-white [&>a]:border [&>a]:border-slate-200 [&>a]:text-slate-600 [&>a]:font-medium [&>a]:transition-colors hover:[&>a]:bg-primary hover:[&>a]:text-white hover:[&>a]:border-primary
                        [&>span.current]:flex [&>span.current]:items-center [&>span.current]:justify-center [&>span.current]:w-10 [&>span.current]:h-10 [&>span.current]:rounded-lg [&>span.current]:bg-primary [&>span.current]:text-white [&>span.current]:font-bold [&>span.current]:shadow-md
                        [&>.prev]:w-auto [&>.prev]:px-4 [&>.next]:w-auto [&>.next]:px-4">';
                    
                    $big = 999999999;
                    global $wp;
                    $current_url = home_url($wp->request);
                    
                    if (empty($wp->request) || $wp->request === '/') {
                        $base_url = home_url('/news');
                        $format = '/page/%#%/';
                    } else {
                        $base_url = $current_url;
                        $format = '/page/%#%/';
                    }
                    
                    if (get_option('permalink_structure')) {
                        $base = str_replace($big, '%#%', esc_url(get_pagenum_link($big)));
                        if (strpos($base, home_url('/page/')) === 0) {
                            $base = home_url('/news/page/%#%/');
                        }
                    } else {
                        $base = add_query_arg('paged', '%#%', $base_url);
                        $format = '';
                    }
                    
                    $current_query = $_GET;
                    unset($current_query['paged']);
                    
                    echo paginate_links(array(
                        'base' => $base,
                        'format' => $format,
                        'current' => max(1, $paged),
                        'total' => $articles_query->max_num_pages,
                        'prev_text' => '&larr; 上一页',
                        'next_text' => '下一页 &rarr;',
                        'add_args' => $current_query,
                        'add_fragment' => false,
                    ));
                    echo '</nav>';
                }
            ?>
            <?php else : ?>
            
            <!-- 暂无文章空状态 -->
            <div class="no-articles py-20 text-center bg-slate-50/50 rounded-2xl border border-dashed border-slate-200">
                <div class="inline-flex items-center justify-center w-16 h-16 rounded-full bg-white shadow-sm mb-4">
                    <span class="material-symbols-outlined text-[32px] text-slate-300">article</span>
                </div>
                <h3 class="text-xl font-bold text-slate-700 mb-2">暂无相关资讯</h3>
                <p class="text-slate-500">抱歉，目前没有找到相关的文章或新闻，请稍后再来看看吧。</p>
            </div>
            
            <?php endif; ?>
        </div>
    </div>
</div>


<script>
document.addEventListener('DOMContentLoaded', function() {
    var categorySelect = document.getElementById('news-category');
    var searchForm = document.querySelector('.news-search-form');
    var searchInput = document.getElementById('news-search');

    if (categorySelect && searchForm) {
        categorySelect.addEventListener('change', function() {
            var keyword = searchInput ? searchInput.value.trim() : '';
            var selectedOption = this.options[this.selectedIndex];
            
            // 如果没有关键词，直接跳转到分类页
            if (!keyword && selectedOption && selectedOption.dataset.url) {
                window.location.href = selectedOption.dataset.url;
            } else {
                // 如果有关键词，或者没有分类url（比如"显示全部"且没配置url），则提交表单
                searchForm.submit();
            }
        });
    }
});
</script>

<?php get_footer() ?>