<?php
require_once __DIR__ . '/../includes/init.php';
require_once __DIR__ . '/../includes/notices_faqs_assets_lib.php';
require_once __DIR__ . '/../includes/auth.php';
if (isset($pdo) && $pdo instanceof PDO) {
    notices_faqs_ensure_assets_origin_column($pdo);
}
$pageTitle = __t('faq_page_title', '常见问题');
$currentLang = defined('CURRENT_LANG') ? CURRENT_LANG : 'zh_cn';
$langParam = ($currentLang !== 'zh_cn') ? '&lang=' . $currentLang : '';

// 从 notices_faqs 表获取常见问题（type='faq'）
$stmt = $pdo->prepare("SELECT id, title, title_en, content, content_en, created_at, assets_origin_base FROM notices_faqs WHERE type='faq' AND is_active=1 ORDER BY created_at DESC");
$stmt->execute();
$faqs = $stmt->fetchAll(PDO::FETCH_ASSOC);

// 获取所有公告列表（用于左侧）
$stmt = $pdo->prepare("SELECT id, title, title_en, content, content_en, created_at, assets_origin_base FROM notices_faqs WHERE type='notice' AND is_active=1 ORDER BY created_at DESC LIMIT 20");
$stmt->execute();
$notices = $stmt->fetchAll(PDO::FETCH_ASSOC);

require_once __DIR__ . '/../support/_support_lib.php';
if (isset($pdo) && $currentLang !== 'zh_cn' && $currentLang !== 'zh_tw') {
    if (function_exists('support_preload_ui_lang')) {
        support_preload_ui_lang($pdo, $currentLang);
    }
    if (function_exists('notices_faqs_batch_translate_titles')) {
        $notices = notices_faqs_batch_translate_titles($pdo, $notices, $currentLang);
        $faqs = notices_faqs_batch_translate_titles($pdo, $faqs, $currentLang);
    }
}

// 获取最新的一条公告（用于右侧默认显示）
$latestNotice = !empty($notices) ? $notices[0] : null;

// 判断当前显示的是公告还是常见问题
$currentId = isset($_GET['id']) ? intval($_GET['id']) : 0;
$currentType = null;
$currentItem = null;

if ($currentId > 0) {
    // 查找当前项
    foreach ($notices as $notice) {
        if ($notice['id'] == $currentId) {
            $currentType = 'notice';
            $currentItem = $notice;
            break;
        }
    }
    if (!$currentItem) {
        foreach ($faqs as $faq) {
            if ($faq['id'] == $currentId) {
                $currentType = 'faq';
                $currentItem = $faq;
                break;
            }
        }
    }
} else {
    // 默认显示最新公告
    if ($latestNotice) {
        $currentType = 'notice';
        $currentItem = $latestNotice;
    } elseif (!empty($faqs)) {
        $currentType = 'faq';
        $currentItem = $faqs[0];
    }
}

// 翻译列表项标题的辅助函数
function translateFaqTitle($row, $pdo) {
    if (!empty($row['_translated_title'])) {
        return (string)$row['_translated_title'];
    }
    $title = $row['title'];
    if (defined('CURRENT_LANG') && CURRENT_LANG !== 'zh_cn' && CURRENT_LANG !== 'zh_tw') {
        if (CURRENT_LANG === 'en' && !empty($row['title_en'])) {
            $title = $row['title_en'];
        } elseif (function_exists('translate_content')) {
            $title = translate_content($row['title'], CURRENT_LANG, $pdo, [
                'table' => 'notices_faqs',
                'id' => $row['id'],
                'field' => 'title_en'
            ]);
        }
    }
    return $title;
}

/**
 * 侧栏搜索用正文摘要：仅用库内原文/英文稿，不调翻译 API（避免泰语等语种逐条翻译导致页面一直加载）。
 */
function faqSearchExcerpt(array $row): string
{
    $content = '';
    if (defined('CURRENT_LANG') && CURRENT_LANG === 'en' && !empty($row['content_en'])) {
        $content = strip_tags((string) $row['content_en']);
    } else {
        $content = strip_tags((string) ($row['content'] ?? ''));
    }
    if (mb_strlen($content, 'UTF-8') > 600) {
        $content = mb_substr($content, 0, 600, 'UTF-8');
    }
    return $content;
}

/** @deprecated 侧栏请用 faqSearchExcerpt，勿在循环中调翻译 API */
function translateFaqContent($row, $pdo)
{
    return faqSearchExcerpt($row);
}

// 获取翻译后的标题和内容（用于当前显示项）
$itemTitle = $currentItem ? $currentItem['title'] : '';
$itemContent = $currentItem ? $currentItem['content'] : '';

if ($currentItem && defined('CURRENT_LANG') && CURRENT_LANG !== 'zh_cn' && CURRENT_LANG !== 'zh_tw') {
    // 标题翻译（侧栏已批量译时直接复用）
    if (!empty($currentItem['_translated_title'])) {
        $itemTitle = (string)$currentItem['_translated_title'];
        if (function_exists('ggai_text_is_mainly_chinese') && ggai_text_is_mainly_chinese(strip_tags($itemTitle))
            && function_exists('notices_faqs_translate_field')) {
            $itemTitle = notices_faqs_translate_field($pdo, $currentItem, CURRENT_LANG, 'title', 'title_en');
        }
    } elseif (CURRENT_LANG === 'en' && !empty($currentItem['title_en'])) {
        $itemTitle = $currentItem['title_en'];
    } elseif (function_exists('notices_faqs_translate_field')) {
        $itemTitle = notices_faqs_translate_field($pdo, $currentItem, CURRENT_LANG, 'title', 'title_en');
    } elseif (function_exists('translate_content')) {
        $itemTitle = translate_content($currentItem['title'], CURRENT_LANG, $pdo, [
            'table' => 'notices_faqs',
            'id' => $currentItem['id'],
            'field' => 'title_en'
        ]);
    }
    if (function_exists('ggai_text_is_mainly_chinese') && ggai_text_is_mainly_chinese(strip_tags((string)$itemTitle))) {
        if (function_exists('notices_faqs_translate_field')) {
            $retryTitle = notices_faqs_translate_field($pdo, $currentItem, CURRENT_LANG, 'title', 'title_en');
            if ($retryTitle !== '' && !ggai_text_is_mainly_chinese(strip_tags($retryTitle))) {
                $itemTitle = $retryTitle;
            }
        }
    }

    // 内容翻译（批量失败或仍为中文时逐条补译）
    if (CURRENT_LANG === 'en' && !empty($currentItem['content_en'])) {
        $itemContent = $currentItem['content_en'];
    } elseif (function_exists('notices_faqs_translate_field')) {
        $itemContent = notices_faqs_translate_field($pdo, $currentItem, CURRENT_LANG, 'content', 'content_en');
    } elseif (function_exists('translate_content')) {
        $itemContent = translate_content($currentItem['content'], CURRENT_LANG, $pdo, [
            'table' => 'notices_faqs',
            'id' => $currentItem['id'],
            'field' => 'content_en'
        ]);
    }
    if (function_exists('ggai_text_is_mainly_chinese') && ggai_text_is_mainly_chinese(strip_tags((string)$itemContent))) {
        if (function_exists('notices_faqs_translate_field')) {
            $retryBody = notices_faqs_translate_field($pdo, $currentItem, CURRENT_LANG, 'content', 'content_en');
            if ($retryBody !== '' && !ggai_text_is_mainly_chinese(strip_tags($retryBody))) {
                $itemContent = $retryBody;
            }
        }
    }
}

if ($currentItem && function_exists('fix_image_urls_in_html')) {
    $itemContent = fix_image_urls_in_html($itemContent);
}
if ($currentItem && function_exists('notices_faqs_rewrite_assets_for_display')) {
    $itemContent = notices_faqs_rewrite_assets_for_display($itemContent, $currentItem['assets_origin_base'] ?? null);
}

// 浏览器标题：文章题目优先，便于 SEO（格式：标题 - 网站名 / 栏目）
$faqSiteName = (function_exists('partner_field') ? (partner_field('site_name') ?: '') : '')
    ?: ($GLOBALS['partnerInfo']['site_name'] ?? 'AI智能量化');
if ($currentItem && trim((string) $itemTitle) !== '') {
    $faqSectionLabel = ($currentType === 'notice')
        ? __t('home_latest_notice_title', '最新公告')
        : __t('faq_page_title', '常见问题');
    $pageTitle = trim((string) $itemTitle) . ' - ' . $faqSiteName . ' / ' . $faqSectionLabel;
} else {
    $pageTitle = __t('faq_page_title', '常见问题') . ' - ' . $faqSiteName;
}
$pageTitleFull = true;

// 数据已就绪，释放 Session 锁，避免同页其它 AJAX（refresh_session 等）在正文翻译期间被阻塞
if (session_status() === PHP_SESSION_ACTIVE) {
    session_write_close();
}

ob_start();
?>
<div class="container-fluid py-4 faq-member-page">
    <div class="row">
        <!-- 左侧边栏：公告和常见问题列表 -->
        <div class="col-lg-3 col-md-4 mb-4">
            <div class="sticky-top faq-sidebar-sticky" style="top: 20px;">
                <!-- 搜索框 -->
                <div class="card shadow-sm mb-3 faq-search-card">
                    <div class="card-body p-3">
                        <div class="input-group">
                            <span class="input-group-text">
                                <i class="fas fa-search"></i>
                            </span>
                            <input type="text" id="faqSearchInput" class="form-control" 
                                   placeholder="<?php echo __t('faq_search_placeholder', '搜索标题或内容...'); ?>"
                                   autocomplete="off">
                        </div>
                    </div>
                </div>
                
                <!-- 公告列表 -->
                <div class="card shadow-sm mb-3 faq-panel faq-panel-notice">
                    <div class="card-header">
                        <h5 class="mb-0">
                            <i class="fas fa-bullhorn me-2"></i>
                            <?php echo __t('home_latest_notice_title', '最新公告'); ?>
                        </h5>
                    </div>
                    <div class="list-group list-group-flush" id="noticeList" style="max-height: 750px; overflow-y: auto;">
                        <?php if (empty($notices)): ?>
                            <div class="list-group-item text-muted text-center py-3 notice-item">
                                <?php echo __t('home_notice_empty', '暂无公告'); ?>
                            </div>
                        <?php else: ?>
                            <?php foreach($notices as $notice): 
                                $noticeTitle = translateFaqTitle($notice, $pdo);
                                $isActive = ($currentItem && $currentItem['id'] == $notice['id'] && $currentType === 'notice');
                                // 获取翻译后的内容用于搜索
                                $noticeContent = faqSearchExcerpt($notice);
                                // 同时保留原始内容用于搜索（确保中文搜索也能找到）
                                $noticeContentOriginal = strip_tags($notice['content']);
                            ?>
                                <a href="<?php echo htmlspecialchars(function_exists('ggai_mu') ? ggai_mu('/user/faq.php?id=' . (int) $notice['id']) : ('faq.php?id=' . (int) $notice['id'] . $langParam), ENT_QUOTES, 'UTF-8'); ?>" 
                                   class="list-group-item list-group-item-action notice-item <?php echo $isActive ? 'active' : ''; ?>"
                                   data-title="<?php echo htmlspecialchars($noticeTitle, ENT_QUOTES); ?>"
                                   data-content="<?php echo htmlspecialchars($noticeContent, ENT_QUOTES); ?>"
                                   data-content-original="<?php echo htmlspecialchars($noticeContentOriginal, ENT_QUOTES); ?>">
                                    <div class="d-flex justify-content-between align-items-start">
                                        <div class="flex-grow-1">
                                            <div class="fw-bold mb-1" style="font-size: 0.95rem;">
                                                <span class="sidebar-item-marker" style="margin-right: 0.35rem; <?php echo $isActive ? 'color: rgba(255,255,255,0.95);' : 'color: #fbbf24;'; ?>" aria-hidden="true">★</span><?php echo htmlspecialchars($noticeTitle); ?>
                                            </div>
                                            <small class="text-muted" style="<?php echo $isActive ? 'color: rgba(255,255,255,0.8) !important;' : ''; ?>">
                                                <?php echo date('Y-m-d', strtotime($notice['created_at'])); ?>
                                            </small>
                                        </div>
                                    </div>
                                </a>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </div>
                </div>
                
                <!-- 常见问题列表 -->
                <div class="card shadow-sm faq-panel faq-panel-faq">
                    <div class="card-header">
                        <h5 class="mb-0">
                            <i class="fas fa-question-circle me-2"></i>
                            <?php echo __t('faq_page_title', '常见问题'); ?>
                        </h5>
                    </div>
                    <div class="list-group list-group-flush" id="faqList" style="max-height: 750px; overflow-y: auto;">
                        <?php if (empty($faqs)): ?>
                            <div class="list-group-item text-muted text-center py-3 faq-item">
                                <?php echo __t('home_faq_empty', '暂无常见问题'); ?>
                            </div>
                        <?php else: ?>
                            <?php foreach($faqs as $faq): 
                                $faqTitle = translateFaqTitle($faq, $pdo);
                                $isActive = ($currentItem && $currentItem['id'] == $faq['id'] && $currentType === 'faq');
                                // 获取翻译后的内容用于搜索
                                $faqContent = faqSearchExcerpt($faq);
                                // 同时保留原始内容用于搜索（确保中文搜索也能找到）
                                $faqContentOriginal = strip_tags($faq['content']);
                            ?>
                                <a href="<?php echo htmlspecialchars(function_exists('ggai_mu') ? ggai_mu('/user/faq.php?id=' . (int) $faq['id']) : ('faq.php?id=' . (int) $faq['id'] . $langParam), ENT_QUOTES, 'UTF-8'); ?>" 
                                   class="list-group-item list-group-item-action faq-item <?php echo $isActive ? 'active' : ''; ?>"
                                   data-title="<?php echo htmlspecialchars($faqTitle, ENT_QUOTES); ?>"
                                   data-content="<?php echo htmlspecialchars($faqContent, ENT_QUOTES); ?>"
                                   data-content-original="<?php echo htmlspecialchars($faqContentOriginal, ENT_QUOTES); ?>">
                                    <div class="d-flex justify-content-between align-items-start">
                                        <div class="flex-grow-1">
                                            <div class="fw-bold mb-1" style="font-size: 0.95rem;">
                                                <span class="sidebar-item-marker" style="margin-right: 0.35rem; <?php echo $isActive ? 'color: rgba(255,255,255,0.95);' : 'color: #34d399;'; ?>" aria-hidden="true">◆</span><?php echo htmlspecialchars($faqTitle); ?>
                                            </div>
                                            <small class="text-muted" style="<?php echo $isActive ? 'color: rgba(255,255,255,0.8) !important;' : ''; ?>">
                                                <?php echo date('Y-m-d', strtotime($faq['created_at'])); ?>
                                            </small>
                                        </div>
                                    </div>
                                </a>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- 右侧主内容区 -->
        <div class="col-lg-9 col-md-8">
            <!-- 顶部操作栏 -->
            <div class="card shadow-sm mb-4 faq-page-header">
                <div class="card-body">
                    <div class="d-flex justify-content-between align-items-center flex-wrap gap-2">
                        <div>
                            <h4 class="mb-0">
                                <i class="fas fa-question-circle text-success me-2"></i>
                                <?php echo __t('faq_page_title', '常见问题'); ?>
                            </h4>
                        </div>
                        <div class="d-flex flex-wrap gap-2">
                            <?php $manual_pdf = $GLOBALS['partnerInfo']['manual_pdf'] ?? ''; ?>
                            <?php if ($manual_pdf): ?>
                                <a href="<?= htmlspecialchars(get_image_url($manual_pdf)) ?>" target="_blank" class="btn btn-danger btn-sm">
                                    <i class="fas fa-file-pdf me-1"></i> <?php echo __t('nav_help', '使用说明'); ?>
                                </a>
                            <?php endif; ?>
                            <a href="<?= htmlspecialchars(ggai_mu('/user/index.php'), ENT_QUOTES, 'UTF-8') ?>" class="btn btn-outline-primary btn-sm">
                                <i class="fas fa-home me-1"></i> <?php echo __t('faq_back_to_home', '返回会员首页'); ?>
                            </a>
                        </div>
                    </div>
                    
                    <!-- 教程视频链接 -->
                    <div class="mt-3 pt-3 border-top faq-tutorial-row">
                        <div class="d-flex flex-wrap gap-2">
                            <a href="<?= htmlspecialchars(($GLOBALS['partnerInfo']['download_url'] ?? 'http://down.ggai365.com') . '/video_download.php?file=BACZ.mp4') ?>" target="_blank" class="btn btn-success btn-sm" style="font-weight:bold;">
                                <i class="fas fa-video-camera me-1"></i><?php echo __t('faq_tutorial_binance_deposit', '币AN充值教程'); ?>
                            </a>
                            <a href="<?= htmlspecialchars(($GLOBALS['partnerInfo']['download_url'] ?? 'http://down.ggai365.com') . '/video_download.php?file=OECZ.mp4') ?>" target="_blank" class="btn btn-warning btn-sm" style="font-weight:bold;">
                                <i class="fas fa-video-camera me-1"></i><?php echo __t('faq_tutorial_okx_deposit', '欧E充值教程'); ?>
                            </a>
                            <a href="<?= htmlspecialchars(($GLOBALS['partnerInfo']['download_url'] ?? 'http://down.ggai365.com') . '/video_download.php?file=BAHELP.mp4') ?>" target="_blank" class="btn btn-danger btn-sm" style="font-weight:bold;">
                                <i class="fas fa-video-camera me-1"></i><?php echo __t('faq_tutorial_binance_api', '币AN-API教程'); ?>
                            </a>
                            <a href="<?= htmlspecialchars(($GLOBALS['partnerInfo']['download_url'] ?? 'http://down.ggai365.com') . '/video_download.php?file=OEHELP.mp4') ?>" target="_blank" class="btn btn-info btn-sm" style="font-weight:bold;">
                                <i class="fas fa-video-camera me-1"></i><?php echo __t('faq_tutorial_okx_api', '欧E-API教程'); ?>
                            </a>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- 显示当前选中内容 -->
            <?php if ($currentItem): ?>
                <!-- 面包屑导航 -->
                <nav aria-label="breadcrumb" class="mb-3 faq-breadcrumb-wrap">
                    <ol class="breadcrumb">
                        <li class="breadcrumb-item">
                            <a href="<?= htmlspecialchars(ggai_mu('/user/index.php'), ENT_QUOTES, 'UTF-8') ?>" style="text-decoration: none;">
                                <i class="fas fa-home me-1"></i>
                                <?php echo __t('faq_back_to_home', '返回会员首页'); ?>
                            </a>
                        </li>
                        <li class="breadcrumb-item active" aria-current="page">
                            <?php 
                            if ($currentType === 'notice') {
                                echo __t('home_latest_notice_title', '最新公告');
                            } else {
                                echo __t('faq_page_title', '常见问题');
                            }
                            ?>
                        </li>
                    </ol>
                </nav>
                
                <!-- 标题 -->
                <div class="card shadow-sm mb-4 faq-meta-card">
                    <div class="card-body">
                        <h2 class="mb-3 faq-article-title" style="font-weight: bold; line-height: 1.4;">
                            <?php echo htmlspecialchars($itemTitle); ?>
                        </h2>
                        
                        <!-- 元信息 -->
                        <div class="d-flex align-items-center flex-wrap gap-2 pb-3 border-bottom">
                            <span class="badge <?php echo $currentType === 'notice' ? 'bg-primary' : 'bg-success'; ?> fs-6">
                                <i class="fas <?php echo $currentType === 'notice' ? 'fa-bullhorn' : 'fa-question-circle'; ?> me-1"></i>
                                <?php 
                                if ($currentType === 'notice') {
                                    echo __t('notice_type_label', '公告');
                                } else {
                                    echo __t('faq_type_label', '常见问题');
                                }
                                ?>
                            </span>
                            <span class="text-muted">
                                <i class="fas fa-calendar-alt me-1"></i>
                                <?php echo date('Y-m-d H:i', strtotime($currentItem['created_at'])); ?>
                            </span>
                        </div>
                    </div>
                </div>
                
                <!-- 内容区域（优化排版，适配会员区暗色主题） -->
                <div class="card shadow-sm mb-4 faq-article-card">
                    <div class="card-body faq-article-body">
                        <div class="content-text">
                            <?php 
                            // 处理HTML内容，确保正确显示
                            // itemContent 已在上方经过 fix_image_urls_in_html + notices_faqs_rewrite_assets_for_display
                            $content = $itemContent;
                            
                            // 如果内容包含HTML标签，处理空行后直接输出
                            if (strip_tags($content) !== $content) {
                                // HTML内容：处理连续的空行（包括<br>标签和换行符的组合）
                                // 将连续的<br>标签（3个或更多）替换为最多2个
                                $content = preg_replace('/(<br\s*\/?>[\s\n]*){3,}/i', '<br><br>', $content);
                                // 处理纯换行符（在HTML标签之间）
                                $content = preg_replace('/\n{3,}/', "\n\n", $content);
                                echo $content;
                            } else {
                                // 纯文本内容：处理空行，然后转换为HTML
                                // 将连续3个或更多换行符替换为最多2个
                                $content = preg_replace('/\n{3,}/', "\n\n", $content);
                                // 转换为HTML，保留换行
                                $content = nl2br(htmlspecialchars($content));
                                // 再次处理转换后的<br>标签，确保连续的空行不超过2个
                                $content = preg_replace('/(<br\s*\/?>[\s\n]*){3,}/i', '<br><br>', $content);
                                echo $content;
                            }
                            ?>
                        </div>
                    </div>
                </div>
                
                <!-- 操作按钮 -->

            <?php else: ?>
                <!-- 内容提示 -->
                <div class="alert alert-info">
                    <i class="fas fa-info-circle me-2"></i>
                    <?php echo __t('faq_select_hint', '请从左侧列表中选择一个问题查看详情'); ?>
                </div>
            <?php endif; ?>
        </div>
    </div>
</div>
<link rel="stylesheet" href="/user/assets/css/faq-member.css?v=1">
<script src="/assets/js/jquery-3.7.1.min.js"></script>
<script src="/assets/js/bootstrap.bundle.min.js"></script>
<script src="/assets/js/image_fallback.js"></script>
<script>
// === 搜索功能 ===
(function() {
    const searchInput = document.getElementById('faqSearchInput');
    if (!searchInput) return;
    
    function filterItems() {
        const searchTerm = searchInput.value.toLowerCase().trim();
        
        // 过滤公告列表
        const noticeItems = document.querySelectorAll('#noticeList .notice-item');
        let noticeVisibleCount = 0;
        noticeItems.forEach(function(item) {
            if (item.classList.contains('text-muted')) {
                // 这是"暂无公告"提示，根据是否有可见项决定显示
                return;
            }
            const title = item.getAttribute('data-title') || '';
            const content = item.getAttribute('data-content') || '';
            const contentOriginal = item.getAttribute('data-content-original') || '';
            // 同时搜索翻译后的内容和原始内容
            const searchText = (title + ' ' + content + ' ' + contentOriginal).toLowerCase();
            
            if (searchTerm === '' || searchText.includes(searchTerm)) {
                item.style.display = '';
                noticeVisibleCount++;
            } else {
                item.style.display = 'none';
            }
        });
        
        // 显示/隐藏"暂无公告"提示
        const noticeEmpty = document.querySelector('#noticeList .notice-item.text-muted');
        if (noticeEmpty) {
            noticeEmpty.style.display = (noticeVisibleCount === 0 && searchTerm !== '') ? 'none' : '';
        }
        
        // 过滤常见问题列表
        const faqItems = document.querySelectorAll('#faqList .faq-item');
        let faqVisibleCount = 0;
        faqItems.forEach(function(item) {
            if (item.classList.contains('text-muted')) {
                // 这是"暂无常见问题"提示，根据是否有可见项决定显示
                return;
            }
            const title = item.getAttribute('data-title') || '';
            const content = item.getAttribute('data-content') || '';
            const contentOriginal = item.getAttribute('data-content-original') || '';
            // 同时搜索翻译后的内容和原始内容
            const searchText = (title + ' ' + content + ' ' + contentOriginal).toLowerCase();
            
            if (searchTerm === '' || searchText.includes(searchTerm)) {
                item.style.display = '';
                faqVisibleCount++;
            } else {
                item.style.display = 'none';
            }
        });
        
        // 显示/隐藏"暂无常见问题"提示
        const faqEmpty = document.querySelector('#faqList .faq-item.text-muted');
        if (faqEmpty) {
            faqEmpty.style.display = (faqVisibleCount === 0 && searchTerm !== '') ? 'none' : '';
        }
        
        // 如果没有搜索结果，显示提示
        if (searchTerm !== '' && noticeVisibleCount === 0 && faqVisibleCount === 0) {
            // 可以在这里添加"无搜索结果"提示
        }
    }
    
    // 监听输入
    searchInput.addEventListener('input', filterItems);
    searchInput.addEventListener('keyup', filterItems);
})();

// === 会话刷新机制：定期刷新会话，防止超时退出 ===
(function(){
    function refreshSession() {
        fetch('/user/ajax/refresh_session.php', {
            method: 'GET',
            credentials: 'same-origin', // 确保发送 Cookie
            cache: 'no-cache'
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                console.log('会话已刷新，时间戳:', new Date(data.timestamp * 1000).toLocaleTimeString());
            } else {
                console.warn('会话刷新失败，可能需要重新登录');
            }
        })
        .catch(error => {
            console.error('会话刷新请求失败:', error);
        });
    }

    // 每5分钟刷新一次会话（300000毫秒）
    // 这样即使会话超时时间设置为24小时，也能确保会话保持活跃
    setInterval(refreshSession, 300000); // 5分钟
    // 页面加载后立即刷新一次
    setTimeout(refreshSession, 1000);
    
    // 页面可见性变化时也刷新会话（用户切换回标签页时）
    document.addEventListener('visibilitychange', function() {
        if (!document.hidden) {
            refreshSession();
        }
    });
    
    // 用户活动时刷新会话（鼠标移动、点击、键盘输入等）
    let activityTimer;
    const activityEvents = ['mousedown', 'mousemove', 'keypress', 'scroll', 'touchstart'];
    activityEvents.forEach(function(eventName) {
        document.addEventListener(eventName, function() {
            clearTimeout(activityTimer);
            activityTimer = setTimeout(function() {
                refreshSession();
            }, 60000); // 1分钟无活动后刷新
        }, true);
    });
})();
</script>
<?php
$pageContent = ob_get_clean();
$ggaiSkipSupportNotify = true;
require_once __DIR__ . '/includes/layout.php'; 