<?php
// 开启输出缓冲，确保AJAX请求可以输出干净的JSON
ob_start();

// 检测是否为AJAX请求（必须在任何输出之前）
$isAjax = isset($_GET['ajax']) && $_GET['ajax'] === '1';

$pageTitle = '机票与高铁票查询';
require_once 'config.php';
require_once 'header.php';

// 扩展热门城市数据（25+个主要城市，含拼音、首字母简拼、车站代码）
$hotCities = [
    ['name' => '北京', 'pinyin' => 'beijing', 'py' => 'bj', 'code' => 'BJP', 'icon' => '🏛️', 'region' => '华北'],
    ['name' => '上海', 'pinyin' => 'shanghai', 'py' => 'sh', 'code' => 'SHH', 'icon' => '🏙️', 'region' => '华东'],
    ['name' => '广州', 'pinyin' => 'guangzhou', 'py' => 'gz', 'code' => 'GZQ', 'icon' => '🌆', 'region' => '华南'],
    ['name' => '深圳', 'pinyin' => 'shenzhen', 'py' => 'sz', 'code' => 'SZQ', 'icon' => '🌃', 'region' => '华南'],
    ['name' => '杭州', 'pinyin' => 'hangzhou', 'py' => 'hz', 'code' => 'HZQ', 'icon' => '🏯', 'region' => '华东'],
    ['name' => '成都', 'pinyin' => 'chengdu', 'py' => 'cd', 'code' => 'CDW', 'icon' => '🕌', 'region' => '西南'],
    ['name' => '重庆', 'pinyin' => 'chongqing', 'py' => 'cq', 'code' => 'CQW', 'icon' => '🌉', 'region' => '西南'],
    ['name' => '武汉', 'pinyin' => 'wuhan', 'py' => 'wh', 'code' => 'WHN', 'icon' => '🏯', 'region' => '华中'],
    ['name' => '西安', 'pinyin' => 'xian', 'py' => 'xa', 'code' => 'XAQ', 'icon' => '🗼', 'region' => '西北'],
    ['name' => '南京', 'pinyin' => 'nanjing', 'py' => 'nj', 'code' => 'NJN', 'icon' => '🏯', 'region' => '华东'],
    ['name' => '天津', 'pinyin' => 'tianjin', 'py' => 'tj', 'code' => 'TJP', 'icon' => '🌆', 'region' => '华北'],
    ['name' => '苏州', 'pinyin' => 'suzhou', 'py' => 'sz2', 'code' => 'SZH', 'icon' => '🏮', 'region' => '华东'],
    ['name' => '郑州', 'pinyin' => 'zhengzhou', 'py' => 'zz', 'code' => 'ZZF', 'icon' => '🏯', 'region' => '华中'],
    ['name' => '长沙', 'pinyin' => 'changsha', 'py' => 'cs', 'code' => 'CSQ', 'icon' => '🏯', 'region' => '华中'],
    ['name' => '青岛', 'pinyin' => 'qingdao', 'py' => 'qd', 'code' => 'QDK', 'icon' => '🌊', 'region' => '华东'],
    ['name' => '大连', 'pinyin' => 'dalian', 'py' => 'dl', 'code' => 'DLD', 'icon' => '⛵', 'region' => '东北'],
    ['name' => '厦门', 'pinyin' => 'xiamen', 'py' => 'xm', 'code' => 'XMN', 'icon' => '🏝️', 'region' => '华东'],
    ['name' => '昆明', 'pinyin' => 'kunming', 'py' => 'km', 'code' => 'KMM', 'icon' => '🕌', 'region' => '西南'],
    ['name' => '贵阳', 'pinyin' => 'guiyang', 'py' => 'gy', 'code' => 'GYM', 'icon' => '🏯', 'region' => '西南'],
    ['name' => '南宁', 'pinyin' => 'nanning', 'py' => 'nn', 'code' => 'NNZ', 'icon' => '🌴', 'region' => '华南'],
    ['name' => '哈尔滨', 'pinyin' => 'haerbin', 'py' => 'heb', 'code' => 'HBB', 'icon' => '❄️', 'region' => '东北'],
    ['name' => '沈阳', 'pinyin' => 'shenyang', 'py' => 'sy', 'code' => 'SYT', 'icon' => '🏯', 'region' => '东北'],
    ['name' => '济南', 'pinyin' => 'jinan', 'py' => 'jn', 'code' => 'JNK', 'icon' => '⛲', 'region' => '华东'],
    ['name' => '合肥', 'pinyin' => 'hefei', 'py' => 'hf', 'code' => 'HFH', 'icon' => '🏙️', 'region' => '华东'],
    ['name' => '太原', 'pinyin' => 'taiyuan', 'py' => 'ty', 'code' => 'TYV', 'icon' => '🏯', 'region' => '华北'],
    ['name' => '阳泉', 'pinyin' => 'yangquan', 'py' => 'yq', 'code' => 'AQP', 'icon' => '⛰️', 'region' => '华北'],
    ['name' => '石家庄', 'pinyin' => 'shijiazhuang', 'py' => 'sjz', 'code' => 'SJP', 'icon' => '🏛️', 'region' => '华北'],
    ['name' => '丽江', 'pinyin' => 'lijiang', 'py' => 'lj', 'code' => 'LJI', 'icon' => '🏔️', 'region' => '西南'],
];

// 按区域分类
$regions = [
    ['name' => '华北', 'cities' => ['北京', '天津', '太原', '阳泉', '石家庄']],
    ['name' => '华东', 'cities' => ['上海', '杭州', '南京', '苏州', '青岛', '厦门', '济南', '合肥']],
    ['name' => '华南', 'cities' => ['广州', '深圳', '南宁']],
    ['name' => '西南', 'cities' => ['成都', '重庆', '昆明', '贵阳', '丽江']],
    ['name' => '华中', 'cities' => ['武汉', '长沙', '郑州']],
    ['name' => '西北', 'cities' => ['西安']],
    ['name' => '东北', 'cities' => ['大连', '哈尔滨', '沈阳']]
];

// 2026年节假日数据
$holidays2026 = [
    '2026-01-01' => '元旦',
    '2026-01-02' => '元旦',
    '2026-01-03' => '元旦',
    '2026-02-15' => '除夕',
    '2026-02-16' => '春节',
    '2026-02-17' => '春节',
    '2026-02-18' => '春节',
    '2026-02-19' => '春节',
    '2026-02-20' => '春节',
    '2026-02-21' => '春节',
    '2026-04-04' => '清明节',
    '2026-04-05' => '清明节',
    '2026-04-06' => '清明节',
    '2026-05-01' => '劳动节',
    '2026-05-02' => '劳动节',
    '2026-05-03' => '劳动节',
    '2026-05-04' => '劳动节',
    '2026-05-05' => '劳动节',
    '2026-06-19' => '端午节',
    '2026-06-20' => '端午节',
    '2026-06-21' => '端午节',
    '2026-09-25' => '中秋节',
    '2026-09-26' => '中秋节',
    '2026-09-27' => '中秋节',
    '2026-10-01' => '国庆节',
    '2026-10-02' => '国庆节',
    '2026-10-03' => '国庆节',
    '2026-10-04' => '国庆节',
    '2026-10-05' => '国庆节',
    '2026-10-06' => '国庆节',
    '2026-10-07' => '国庆节',
];

// 获取今天日期
$today = date('Y-m-d');
$maxDate = date('Y-m-d', strtotime('+30 days'));

// 获取历史记录
$searchHistory = isset($_COOKIE['ticket_search_history']) ? json_decode($_COOKIE['ticket_search_history'], true) : [];

// 处理搜索请求（支持AJAX和传统POST）
$searchResults = [];
$fromCity = '';
$toCity = '';
$travelDate = $today;
$ticketType = 'train';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['search_tickets'])) {
    $fromCity = $_POST['from_city'] ?? '';
    $toCity = $_POST['to_city'] ?? '';
    $travelDate = $_POST['travel_date'] ?? $today;
    $ticketType = $_POST['ticket_type'] ?? 'train';

    // 保存搜索历史
    $newHistory = ['from' => $fromCity, 'to' => $toCity, 'date' => $travelDate, 'type' => $ticketType, 'time' => time()];
    $searchHistory = array_filter($searchHistory, function($h) use ($fromCity, $toCity) {
        return !($h['from'] == $fromCity && $h['to'] == $toCity);
    });
    array_unshift($searchHistory, $newHistory);
    $searchHistory = array_slice($searchHistory, 0, 10);
    setcookie('ticket_search_history', json_encode($searchHistory), time() + 30 * 24 * 3600, '/');

    if ($ticketType === 'train') {
        require_once __DIR__ . '/api/api_client.php';
        $ticketService = new TicketApiService();
        $apiResult = $ticketService->queryTrainTickets($fromCity, $toCity, $travelDate);
        if ($apiResult['success'] && !empty($apiResult['data'])) {
            $searchResults = [];
            foreach ($apiResult['data'] as $idx => $train) {
                $searchResults[] = [
                    'id' => $idx + 1,
                    'number' => $train['train_no'],
                    'from' => $train['from_station'],
                    'to' => $train['to_station'],
                    'depart_time' => $train['depart_time'],
                    'arrive_time' => $train['arrive_time'],
                    'duration' => $train['duration'],
                    'duration_min' => $train['duration_minutes'],
                    'price' => 0,
                    'discount' => 0,
                    'seats' => $train['seats'],
                    'type' => $train['type_name'],
                    'operator' => $train['type_name'],
                    'transit' => $train['transit'] ?? 0,
                    'transit_stations' => $train['transit_info'] ?? '',
                    'on_time_rate' => 0,
                    'source' => $apiResult['source'] ?? 'mock',
                ];
            }
        } else {
            $searchResults = generateMockResults($fromCity, $toCity, $travelDate, $ticketType);
        }
    } else {
        $searchResults = generateMockResults($fromCity, $toCity, $travelDate, $ticketType);
    }
}

// 如果是AJAX请求，直接返回JSON（清除所有之前的输出）
if ($isAjax) {
    ob_end_clean();
    header('Content-Type: application/json; charset=utf-8');
    if (!empty($searchResults)) {
        echo json_encode(['success' => true, 'data' => $searchResults, 'count' => count($searchResults)], JSON_UNESCAPED_UNICODE);
    } else {
        echo json_encode(['success' => false, 'message' => '未找到匹配班次'], JSON_UNESCAPED_UNICODE);
    }
    exit;
}

function generateMockResults($from, $to, $date, $type) {
    $results = [];
    $isFlight = $type === 'flight';

    $operators = $isFlight
        ? ['东方航空', '南方航空', '中国国航', '海南航空', '春秋航空', '吉祥航空', '四川航空', '厦门航空']
        : ['中国高铁', '和谐号', '复兴号', '高铁快线'];

    $prefixes = $isFlight ? ['MU', 'CZ', 'CA', 'HU', '9C', 'HO', '3U', 'MF'] : ['G', 'D', 'C'];

    $count = rand(8, 15);
    for ($i = 1; $i <= $count; $i++) {
        $departHour = 6 + rand(0, 16);
        $duration = $isFlight ? rand(90, 360) : rand(60, 600);
        $price = $isFlight ? rand(500, 2500) : rand(80, 800);
        $hasTransit = rand(0, 4) === 0 && !$isFlight;

        $seats = $isFlight
            ? ['经济舱' => rand(0, 60), '商务舱' => rand(0, 15), '头等舱' => rand(0, 5)]
            : ['二等座' => rand(0, 120), '一等座' => rand(0, 40), '商务座' => rand(0, 10)];

        $results[] = [
            'id' => $i,
            'number' => $prefixes[array_rand($prefixes)] . str_pad(rand(100, 9999), $isFlight ? 4 : 3, '0', STR_PAD_LEFT),
            'from' => $from,
            'to' => $to,
            'depart_time' => str_pad($departHour, 2, '0', STR_PAD_LEFT) . ':' . str_pad(rand(0, 59), 2, '0', STR_PAD_LEFT),
            'arrive_time' => date('H:i', strtotime(str_pad($departHour, 2, '0', STR_PAD_LEFT) . ':00') + $duration * 60),
            'duration' => formatDuration($duration),
            'duration_min' => $duration,
            'price' => $price,
            'discount' => rand(0, 35),
            'seats' => $seats,
            'type' => $isFlight ? '飞机' : ($hasTransit ? '中转高铁' : '高铁'),
            'operator' => $operators[array_rand($operators)],
            'transit' => $hasTransit ? rand(1, 2) : 0,
            'transit_stations' => $hasTransit ? ['郑州东', '武汉'][rand(0, 1)] : '',
            'on_time_rate' => 82 + rand(0, 17)
        ];
    }

    // 按出发时间排序
    usort($results, function($a, $b) {
        return strcmp($a['depart_time'], $b['depart_time']);
    });

    return $results;
}

function formatDuration($minutes) {
    $hours = floor($minutes / 60);
    $mins = $minutes % 60;
    return $hours . '小时' . ($mins > 0 ? $mins . '分钟' : '');
}

// 输出城市数据供JS使用
$citiesJson = json_encode($hotCities, JSON_UNESCAPED_UNICODE);
$holidaysJson = json_encode($holidays2026, JSON_UNESCAPED_UNICODE);
$regionsJson = json_encode($regions, JSON_UNESCAPED_UNICODE);
?>

<main class="site-main">
    <!-- 搜索区域 -->
    <section class="ticket-search-section">
        <div class="container">
            <div class="search-card">
                <!-- 选项卡：单程/往返 -->
                <div class="trip-type-tabs">
                    <button class="tab-btn active" data-trip="oneway" id="tabOneway">
                        <i class="fas fa-arrow-right"></i> 单程
                    </button>
                    <button class="tab-btn" data-trip="roundtrip" id="tabRoundtrip">
                        <i class="fas fa-exchange-alt"></i> 往返
                    </button>
                </div>

                <!-- 搜索表单 -->
                <form method="POST" class="search-form" id="searchForm">
                    <input type="hidden" name="search_tickets" value="1">

                    <div class="form-row">
                        <!-- 出发地 -->
                        <div class="form-group location-group">
                            <label class="label-icon"><i class="fas fa-map-marker-alt"></i></label>
                            <div class="location-input-wrapper">
                                <input type="text" name="from_city" id="from_city"
                                       placeholder="出发城市/拼音/代码"
                                       value="<?= htmlspecialchars($fromCity) ?>"
                                       class="location-input"
                                       autocomplete="off">
                                <button type="button" class="swap-btn" id="swapCities" title="交换出发地与目的地">
                                    <i class="fas fa-exchange-alt"></i>
                                </button>
                            </div>
                            <div class="location-dropdown" id="fromDropdown"></div>
                        </div>

                        <!-- 目的地 -->
                        <div class="form-group location-group">
                            <label class="label-icon"><i class="fas fa-map-pin"></i></label>
                            <input type="text" name="to_city" id="to_city"
                                   placeholder="目的城市/拼音/代码"
                                   value="<?= htmlspecialchars($toCity) ?>"
                                   class="location-input"
                                   autocomplete="off">
                            <div class="location-dropdown" id="toDropdown"></div>
                        </div>

                        <!-- 往返日期（往返模式显示） -->
                        <div class="form-group date-group" id="returnDateGroup" style="display:none;">
                            <label class="label-icon"><i class="fas fa-calendar-check"></i></label>
                            <input type="date" name="return_date" id="return_date"
                                   class="date-input"
                                   min="<?= $today ?>" max="<?= $maxDate ?>">
                            <span class="date-hint">返程日期</span>
                        </div>

                        <!-- 出发日期选择 -->
                        <div class="form-group date-group">
                            <label class="label-icon"><i class="fas fa-calendar-alt"></i></label>
                            <input type="date" name="travel_date" id="travel_date"
                                   min="<?= $today ?>" max="<?= $maxDate ?>"
                                   value="<?= htmlspecialchars($travelDate) ?>"
                                   class="date-input">
                            <div class="preset-dates">
                                <button type="button" class="preset-btn" data-date="today">今天</button>
                                <button type="button" class="preset-btn" data-date="tomorrow">明天</button>
                                <button type="button" class="preset-btn" data-date="dayafter">后天</button>
                                <button type="button" class="preset-btn" data-date="weekend">周末</button>
                            </div>
                            <div class="holiday-hint" id="holidayHint"></div>
                        </div>

                        <!-- 票务类型 -->
                        <div class="form-group type-group">
                            <label class="label-icon"><i class="fas fa-ticket-alt"></i></label>
                            <div class="type-tabs">
                                <button type="button" class="type-tab <?= $ticketType !== 'flight' ? 'active' : '' ?>"
                                        data-type="train">
                                    <i class="fas fa-train"></i> 高铁
                                </button>
                                <button type="button" class="type-tab <?= $ticketType === 'flight' ? 'active' : '' ?>"
                                        data-type="flight">
                                    <i class="fas fa-plane"></i> 机票
                                </button>
                            </div>
                            <input type="hidden" name="ticket_type" id="ticket_type"
                                   value="<?= htmlspecialchars($ticketType) ?>">
                        </div>

                        <!-- 搜索按钮 -->
                        <button type="submit" class="search-btn" id="searchBtn">
                            <i class="fas fa-search"></i> 搜索班次
                        </button>
                    </div>
                </form>

                <!-- 历史记录 -->
                <?php if (!empty($searchHistory)): ?>
                <div class="search-history" id="searchHistory">
                    <div class="history-header">
                        <span class="history-label"><i class="fas fa-history"></i> 历史搜索</span>
                        <button type="button" class="history-clear" id="clearHistory" title="清除历史记录">
                            <i class="fas fa-trash-alt"></i>
                        </button>
                    </div>
                    <div class="history-list">
                        <?php foreach (array_slice($searchHistory, 0, 5) as $index => $history): ?>
                        <span class="history-item"
                              data-from="<?= htmlspecialchars($history['from']) ?>"
                              data-to="<?= htmlspecialchars($history['to']) ?>"
                              data-date="<?= htmlspecialchars($history['date']) ?>"
                              data-type="<?= htmlspecialchars($history['type'] ?? 'train') ?>">
                            <?= htmlspecialchars($history['from']) ?> → <?= htmlspecialchars($history['to']) ?>
                            <small><?= htmlspecialchars($history['date']) ?></small>
                        </span>
                        <?php endforeach; ?>
                    </div>
                </div>
                <?php endif; ?>
            </div>
        </div>
    </section>

    <!-- 加载状态：骨架屏 -->
    <section class="ticket-results-section" id="resultsSection" style="display:none;">
        <div class="container">
            <!-- 筛选栏 -->
            <div class="filter-bar" id="filterBar" style="display:none;">
                <div class="filter-left">
                    <span class="result-count" id="resultCount"></span>
                    <span class="query-info" id="queryInfo"></span>
                </div>
                <div class="filter-right">
                    <div class="filter-group">
                        <label class="filter-label">出发时段</label>
                        <select id="timeFilter" class="filter-select">
                            <option value="all">全部时段</option>
                            <option value="morning">早上 (06-12点)</option>
                            <option value="afternoon">下午 (12-18点)</option>
                            <option value="evening">晚上 (18-24点)</option>
                        </select>
                    </div>
                    <div class="filter-group">
                        <label class="filter-label">排序</label>
                        <select id="sortSelect" class="filter-select">
                            <option value="depart_asc">出发时间 ↑</option>
                            <option value="depart_desc">出发时间 ↓</option>
                            <option value="arrive_asc">到达时间 ↑</option>
                            <option value="arrive_desc">到达时间 ↓</option>
                            <option value="duration_asc">历时最短</option>
                            <option value="duration_desc">历时最长</option>
                            <option value="price_asc">价格最低</option>
                            <option value="price_desc">价格最高</option>
                        </select>
                    </div>
                    <label class="checkbox-label filter-check">
                        <input type="checkbox" id="onlyDirect"> 仅看直达
                    </label>
                </div>
            </div>

            <!-- 骨架屏加载 -->
            <div class="skeleton-container" id="skeletonLoading">
                <?php for ($i = 0; $i < 5; $i++): ?>
                <div class="skeleton-card">
                    <div class="skeleton-row skeleton-header">
                        <div class="skeleton-block w-30"></div>
                        <div class="skeleton-block w-20"></div>
                        <div class="skeleton-block w-15"></div>
                    </div>
                    <div class="skeleton-row skeleton-body">
                        <div class="skeleton-block w-25"></div>
                        <div class="skeleton-block w-10"></div>
                        <div class="skeleton-block w-25"></div>
                    </div>
                    <div class="skeleton-row skeleton-footer">
                        <div class="skeleton-block w-30"></div>
                        <div class="skeleton-block w-20"></div>
                    </div>
                </div>
                <?php endfor; ?>
            </div>

            <!-- 班次列表 -->
            <div class="results-list" id="resultsList"></div>

            <!-- 空状态 -->
            <div class="empty-state" id="emptyState" style="display:none;">
                <div class="empty-icon">🔍</div>
                <h3>未找到相关班次</h3>
                <p id="emptyHint">请尝试调整出发地、目的地或日期</p>
                <div class="empty-suggestions" id="emptySuggestions"></div>
                <button class="btn-primary" onclick="document.getElementById('searchForm').reset();document.getElementById('resultsSection').style.display='none';">重新搜索</button>
            </div>

            <!-- 错误状态 -->
            <div class="error-state" id="errorState" style="display:none;">
                <div class="error-icon">⚠️</div>
                <h3>查询出错了</h3>
                <p id="errorMsg">网络连接异常，请检查网络后重试</p>
                <button class="btn-primary" onclick="location.reload();">刷新重试</button>
            </div>
        </div>
    </section>

    <!-- 预渲染的搜索结果（PHP直出，无JS时也能用） -->
    <?php if (!empty($searchResults)): ?>
    <script>
    // 将PHP搜索结果传递给前端JS渲染，避免重复请求
    window.__preloadedResults = <?= json_encode($searchResults, JSON_UNESCAPED_UNICODE) ?>;
    window.__preloadedFrom = <?= json_encode($fromCity, JSON_UNESCAPED_UNICODE) ?>;
    window.__preloadedTo = <?= json_encode($toCity, JSON_UNESCAPED_UNICODE) ?>;
    window.__preloadedDate = <?= json_encode($travelDate, JSON_UNESCAPED_UNICODE) ?>;
    window.__preloadedType = <?= json_encode($ticketType, JSON_UNESCAPED_UNICODE) ?>;
    </script>
    <?php endif; ?>

    <!-- 功能介绍（无搜索结果时显示） -->
    <?php if (empty($searchResults)): ?>
    <section class="ticket-features" id="featuresSection">
        <div class="container">
            <div class="section-title">
                <h2>✨ 票务查询功能</h2>
                <p>一站式查询机票与高铁票，轻松规划您的旅程</p>
            </div>
            <div class="features-grid">
                <div class="feature-card">
                    <div class="feature-icon">🚄</div>
                    <h3>高铁查询</h3>
                    <p>覆盖全国主要城市高铁网络，实时查询车次信息与票价，支持高铁/动车/普速列车</p>
                </div>
                <div class="feature-card">
                    <div class="feature-icon">✈️</div>
                    <h3>机票预订</h3>
                    <p>对接多家航空公司，提供最优价格与航班选择，覆盖国内主要航线</p>
                </div>
                <div class="feature-card">
                    <div class="feature-icon">📅</div>
                    <h3>智能选期</h3>
                    <p>支持30天内日期选择，标记国家法定节假日与周末高峰期提示</p>
                </div>
                <div class="feature-card">
                    <div class="feature-icon">🔍</div>
                    <h3>精准筛选</h3>
                    <p>按出发时段、价格区间、运营商多维度筛选，支持直达/中转过滤</p>
                </div>
                <div class="feature-card">
                    <div class="feature-icon">📱</div>
                    <h3>移动优先</h3>
                    <p>完美适配手机、平板与桌面设备，触控优化，随时随地查询</p>
                </div>
                <div class="feature-card">
                    <div class="feature-icon">💾</div>
                    <h3>历史记录</h3>
                    <p>自动保存搜索历史与筛选偏好，方便快速重复查询</p>
                </div>
            </div>
        </div>
    </section>
    <?php endif; ?>
</main>

<!-- 内联CSS用于票务模块 -->
<style>
/* ========== 票务搜索卡片 ========== */
.ticket-search-section {
    padding: 40px 0 20px;
}
.search-card {
    background: #fff;
    border-radius: 20px;
    padding: 30px;
    box-shadow: 0 8px 30px rgba(0,0,0,0.08);
}
.trip-type-tabs {
    display: flex;
    gap: 10px;
    margin-bottom: 25px;
}
.trip-type-tabs .tab-btn {
    padding: 10px 24px;
    border: 2px solid #eee;
    background: #fff;
    border-radius: 25px;
    cursor: pointer;
    font-size: 15px;
    transition: all 0.3s;
    display: flex;
    align-items: center;
    gap: 6px;
}
.trip-type-tabs .tab-btn.active {
    background: #b64a2a;
    color: #fff;
    border-color: #b64a2a;
}
.trip-type-tabs .tab-btn:hover:not(.active) {
    border-color: #b64a2a;
    color: #b64a2a;
}

/* 搜索表单 */
.search-form .form-row {
    display: flex;
    gap: 12px;
    align-items: flex-start;
    flex-wrap: wrap;
}
.form-group {
    position: relative;
    flex: 1;
    min-width: 120px;
}
.form-group.location-group { flex: 1.5; min-width: 180px; }
.form-group.date-group { flex: 1.2; min-width: 150px; }
.form-group.type-group { flex: 0.8; min-width: 140px; }

.label-icon {
    position: absolute;
    left: 12px;
    top: 50%;
    transform: translateY(-50%);
    color: #b64a2a;
    font-size: 16px;
    z-index: 2;
    pointer-events: none;
}

.location-input-wrapper {
    position: relative;
}
.location-input {
    width: 100%;
    padding: 14px 40px 14px 36px;
    border: 2px solid #e0e0e0;
    border-radius: 12px;
    font-size: 15px;
    transition: all 0.3s;
    background: #fafafa;
    outline: none;
}
.location-input:focus {
    border-color: #b64a2a;
    background: #fff;
    box-shadow: 0 0 0 3px rgba(182,74,42,0.1);
}
.swap-btn {
    position: absolute;
    right: 8px;
    top: 50%;
    transform: translateY(-50%);
    background: #f8edeb;
    border: none;
    width: 32px;
    height: 32px;
    border-radius: 50%;
    cursor: pointer;
    color: #b64a2a;
    font-size: 14px;
    transition: all 0.3s;
    display: flex;
    align-items: center;
    justify-content: center;
}
.swap-btn:hover {
    background: #b64a2a;
    color: #fff;
    transform: translateY(-50%) rotate(180deg);
}

/* 日期输入 */
.date-input {
    width: 100%;
    padding: 14px 14px 14px 36px;
    border: 2px solid #e0e0e0;
    border-radius: 12px;
    font-size: 15px;
    background: #fafafa;
    outline: none;
    cursor: pointer;
    transition: all 0.3s;
}
.date-input:focus {
    border-color: #b64a2a;
    background: #fff;
}
.date-hint {
    display: block;
    font-size: 12px;
    color: #999;
    margin-top: 4px;
    text-align: center;
}

/* 快捷日期按钮 */
.preset-dates {
    display: flex;
    gap: 6px;
    margin-top: 8px;
    flex-wrap: wrap;
}
.preset-btn {
    padding: 4px 12px;
    background: #f8edeb;
    border: 1px solid #f5d5cc;
    border-radius: 15px;
    cursor: pointer;
    font-size: 12px;
    color: #b64a2a;
    transition: all 0.2s;
    white-space: nowrap;
}
.preset-btn:hover {
    background: #b64a2a;
    color: #fff;
    border-color: #b64a2a;
}

/* 节假日提示 */
.holiday-hint {
    margin-top: 6px;
    font-size: 12px;
    color: #e67e22;
    min-height: 18px;
}

/* 票务类型切换 */
.type-tabs {
    display: flex;
    border: 2px solid #e0e0e0;
    border-radius: 12px;
    overflow: hidden;
}
.type-tab {
    flex: 1;
    padding: 13px 10px;
    border: none;
    background: #fafafa;
    cursor: pointer;
    font-size: 14px;
    transition: all 0.3s;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 5px;
}
.type-tab.active {
    background: #b64a2a;
    color: #fff;
}
.type-tab:hover:not(.active) {
    background: #f8edeb;
}

/* 搜索按钮 */
.search-btn {
    padding: 14px 30px;
    background: linear-gradient(135deg, #b64a2a, #d4543a);
    color: #fff;
    border: none;
    border-radius: 12px;
    font-size: 16px;
    font-weight: bold;
    cursor: pointer;
    transition: all 0.3s;
    display: flex;
    align-items: center;
    gap: 8px;
    white-space: nowrap;
    min-width: 140px;
    justify-content: center;
}
.search-btn:hover {
    transform: translateY(-2px);
    box-shadow: 0 6px 20px rgba(182,74,42,0.3);
}
.search-btn:active {
    transform: translateY(0);
}

/* 下拉面板 */
.location-dropdown {
    position: absolute;
    top: 100%;
    left: 0;
    width: 100%;
    min-width: 320px;
    max-height: 400px;
    overflow-y: auto;
    background: #fff;
    border: 2px solid #e0e0e0;
    border-top: none;
    border-radius: 0 0 15px 15px;
    box-shadow: 0 10px 30px rgba(0,0,0,0.12);
    z-index: 200;
    display: none;
    padding: 10px 0;
}
.location-dropdown.show {
    display: block;
}
.dropdown-header {
    padding: 8px 16px;
    font-size: 13px;
    color: #999;
    font-weight: bold;
    text-transform: uppercase;
}
.dropdown-cities {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 4px;
    padding: 4px 12px;
}
.dropdown-city {
    padding: 8px 10px;
    border-radius: 8px;
    cursor: pointer;
    transition: all 0.2s;
    display: flex;
    align-items: center;
    gap: 6px;
    font-size: 13px;
}
.dropdown-city:hover {
    background: #f8edeb;
}
.dropdown-city .city-icon { font-size: 16px; }
.dropdown-city .city-code {
    font-size: 10px;
    color: #999;
    margin-left: auto;
}
.dropdown-city.selected {
    background: #b64a2a;
    color: #fff;
}
.dropdown-city.selected .city-code { color: rgba(255,255,255,0.7); }
.dropdown-divider {
    height: 1px;
    background: #eee;
    margin: 8px 12px;
}
.region-group {
    padding: 6px 16px;
    border-bottom: 1px solid #f5f5f5;
}
.region-group:last-child { border-bottom: none; }
.region-name {
    font-size: 12px;
    color: #b64a2a;
    font-weight: bold;
    margin-bottom: 4px;
}
.region-cities {
    display: flex;
    gap: 6px;
    flex-wrap: wrap;
}
.region-city {
    padding: 4px 10px;
    background: #f5f5f5;
    border-radius: 12px;
    font-size: 12px;
    cursor: pointer;
    transition: all 0.2s;
}
.region-city:hover {
    background: #b64a2a;
    color: #fff;
}
.dropdown-no-result {
    padding: 20px;
    text-align: center;
    color: #999;
    font-size: 13px;
}
.dropdown-match-info {
    padding: 4px 16px;
    font-size: 11px;
    color: #27ae60;
}

/* 历史记录 */
.search-history {
    margin-top: 20px;
    padding-top: 15px;
    border-top: 1px solid #f0f0f0;
}
.history-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 10px;
}
.history-label {
    font-size: 13px;
    color: #999;
    display: flex;
    align-items: center;
    gap: 5px;
}
.history-clear {
    background: none;
    border: none;
    color: #ccc;
    cursor: pointer;
    font-size: 13px;
    transition: color 0.2s;
}
.history-clear:hover { color: #e74c3c; }
.history-list {
    display: flex;
    gap: 8px;
    flex-wrap: wrap;
}
.history-item {
    padding: 6px 14px;
    background: #f8f9fa;
    border-radius: 20px;
    font-size: 13px;
    cursor: pointer;
    transition: all 0.2s;
    display: flex;
    align-items: center;
    gap: 4px;
}
.history-item:hover {
    background: #f8edeb;
    color: #b64a2a;
}
.history-item small {
    color: #999;
    font-size: 11px;
}

/* 筛选栏 */
.filter-bar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex-wrap: wrap;
    gap: 12px;
    padding: 15px 20px;
    background: #fff;
    border-radius: 12px;
    margin-bottom: 20px;
    box-shadow: 0 2px 10px rgba(0,0,0,0.05);
}
.filter-left {
    display: flex;
    align-items: center;
    gap: 12px;
}
.result-count {
    font-weight: bold;
    color: #b64a2a;
    font-size: 15px;
}
.query-info {
    color: #999;
    font-size: 13px;
}
.filter-right {
    display: flex;
    align-items: center;
    gap: 12px;
    flex-wrap: wrap;
}
.filter-group {
    display: flex;
    align-items: center;
    gap: 6px;
}
.filter-label {
    font-size: 12px;
    color: #999;
    white-space: nowrap;
}
.filter-select {
    padding: 8px 12px;
    border: 1px solid #ddd;
    border-radius: 8px;
    font-size: 13px;
    background: #fafafa;
    cursor: pointer;
    outline: none;
}
.filter-select:focus { border-color: #b64a2a; }
.filter-check {
    display: flex;
    align-items: center;
    gap: 6px;
    font-size: 13px;
    color: #555;
    cursor: pointer;
    white-space: nowrap;
}

/* 骨架屏 */
.skeleton-container {
    display: flex;
    flex-direction: column;
    gap: 15px;
}
.skeleton-card {
    background: #fff;
    border-radius: 15px;
    padding: 20px;
    box-shadow: 0 2px 8px rgba(0,0,0,0.04);
}
.skeleton-row {
    display: flex;
    gap: 10px;
    margin-bottom: 12px;
}
.skeleton-block {
    height: 16px;
    background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%);
    background-size: 200% 100%;
    animation: skeleton-shimmer 1.5s infinite;
    border-radius: 4px;
}
.skeleton-block.w-10 { width: 10%; }
.skeleton-block.w-15 { width: 15%; }
.skeleton-block.w-20 { width: 20%; }
.skeleton-block.w-25 { width: 25%; }
.skeleton-block.w-30 { width: 30%; }
.skeleton-block.w-40 { width: 40%; }
.skeleton-header .skeleton-block { height: 18px; }
.skeleton-body .skeleton-block { height: 44px; }
.skeleton-footer .skeleton-block { height: 36px; }
@keyframes skeleton-shimmer {
    0% { background-position: -200% 0; }
    100% { background-position: 200% 0; }
}

/* 班次卡片 */
.results-list {
    display: flex;
    flex-direction: column;
    gap: 15px;
}
.ticket-card {
    background: #fff;
    border-radius: 15px;
    padding: 20px 25px;
    box-shadow: 0 3px 12px rgba(0,0,0,0.06);
    transition: all 0.3s;
    border: 1px solid transparent;
}
.ticket-card:hover {
    transform: translateY(-2px);
    box-shadow: 0 6px 20px rgba(0,0,0,0.1);
    border-color: #f5d5cc;
}
.ticket-card.transit-card {
    border-left: 4px solid #e67e22;
}
.ticket-header {
    display: flex;
    align-items: center;
    gap: 12px;
    margin-bottom: 15px;
}
.ticket-operator {
    font-weight: bold;
    color: #333;
    font-size: 15px;
}
.ticket-number {
    background: #f0f0f0;
    padding: 2px 10px;
    border-radius: 10px;
    font-size: 13px;
    color: #666;
    font-family: monospace;
}
.ticket-type {
    margin-left: auto;
    background: #f8edeb;
    color: #b64a2a;
    padding: 3px 12px;
    border-radius: 12px;
    font-size: 12px;
    font-weight: bold;
}
.ticket-body {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 20px;
    flex-wrap: wrap;
}
.route-info {
    display: flex;
    align-items: center;
    gap: 20px;
    flex: 1;
}
.city-block {
    text-align: center;
}
.city-block .city-name {
    font-size: 20px;
    font-weight: bold;
    color: #333;
    display: block;
}
.city-block .city-time {
    font-size: 28px;
    font-weight: bold;
    color: #b64a2a;
}
.route-arrow {
    text-align: center;
    position: relative;
    min-width: 60px;
}
.route-arrow i {
    font-size: 20px;
    color: #ccc;
}
.transit-tag {
    display: block;
    background: #fff3cd;
    color: #856404;
    font-size: 11px;
    padding: 2px 8px;
    border-radius: 8px;
    margin-top: 4px;
}
.transit-info {
    font-size: 11px;
    color: #e67e22;
    margin-top: 2px;
}
.ticket-info {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 4px;
    font-size: 13px;
    color: #666;
}
.ticket-footer {
    display: flex;
    align-items: center;
    gap: 15px;
    margin-top: 15px;
    padding-top: 15px;
    border-top: 1px solid #f0f0f0;
    flex-wrap: wrap;
}
.price-section {
    display: flex;
    align-items: baseline;
    gap: 8px;
}
.original-price {
    text-decoration: line-through;
    color: #999;
    font-size: 13px;
}
.current-price {
    font-size: 28px;
    font-weight: bold;
    color: #e74c3c;
}
.current-price::before { content: '¥'; font-size: 16px; }
.discount-tag {
    background: #ffe0e0;
    color: #e74c3c;
    padding: 2px 8px;
    border-radius: 8px;
    font-size: 11px;
    font-weight: bold;
}
.seat-section {
    display: flex;
    gap: 12px;
    font-size: 13px;
    color: #666;
    flex: 1;
    flex-wrap: wrap;
}
.seat-type .available { color: #27ae60; font-weight: bold; }
.seat-type .soldout { color: #e74c3c; }
.book-btn {
    padding: 10px 24px;
    background: linear-gradient(135deg, #b64a2a, #d4543a);
    color: #fff;
    border: none;
    border-radius: 25px;
    font-size: 14px;
    cursor: pointer;
    transition: all 0.3s;
    white-space: nowrap;
    font-weight: bold;
}
.book-btn:hover {
    transform: scale(1.05);
    box-shadow: 0 4px 15px rgba(182,74,42,0.3);
}

/* 空状态 */
.empty-state, .error-state {
    text-align: center;
    padding: 60px 20px;
}
.empty-icon, .error-icon { font-size: 4rem; margin-bottom: 15px; }
.empty-state h3, .error-state h3 {
    color: #333;
    margin-bottom: 10px;
    font-size: 1.5rem;
}
.empty-state p, .error-state p {
    color: #999;
    margin-bottom: 20px;
}
.empty-suggestions {
    display: flex;
    gap: 10px;
    justify-content: center;
    flex-wrap: wrap;
    margin-bottom: 20px;
}
.empty-suggestions .suggestion-item {
    padding: 8px 16px;
    background: #f8edeb;
    border-radius: 20px;
    cursor: pointer;
    font-size: 14px;
    color: #b64a2a;
    transition: all 0.2s;
}
.empty-suggestions .suggestion-item:hover {
    background: #b64a2a;
    color: #fff;
}

/* 错误状态 */
.error-state { color: #e74c3c; }

/* 功能介绍区 */
.ticket-features {
    padding: 50px 0;
    background: #fafafa;
}
.features-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
    gap: 25px;
    margin-top: 30px;
}
.feature-card {
    background: #fff;
    padding: 30px;
    border-radius: 15px;
    text-align: center;
    box-shadow: 0 5px 20px rgba(0,0,0,0.05);
    transition: transform 0.3s;
}
.feature-card:hover {
    transform: translateY(-5px);
}
.feature-card .feature-icon {
    font-size: 3rem;
    margin-bottom: 15px;
}
.feature-card h3 {
    color: #333;
    margin-bottom: 10px;
}
.feature-card p {
    color: #666;
    font-size: 14px;
    line-height: 1.6;
}

/* ========== 响应式 ========== */
@media (max-width: 1023px) {
    .search-form .form-row {
        gap: 10px;
    }
    .form-group.location-group,
    .form-group.date-group,
    .form-group.type-group {
        flex: 1 1 45%;
        min-width: 140px;
    }
    .search-btn {
        flex: 1 1 100%;
        min-width: auto;
    }
    .dropdown-cities {
        grid-template-columns: repeat(3, 1fr);
    }
    .ticket-body {
        flex-direction: column;
        align-items: flex-start;
    }
    .filter-bar {
        flex-direction: column;
        align-items: flex-start;
    }
    .filter-right {
        width: 100%;
    }
    .filter-select {
        flex: 1;
        min-width: 100px;
    }
}

@media (max-width: 767px) {
    .ticket-search-section {
        padding: 20px 0 10px;
    }
    .search-card {
        padding: 20px 15px;
        border-radius: 15px;
    }
    .search-form .form-row {
        flex-direction: column;
        gap: 10px;
    }
    .form-group {
        flex: 1 1 100% !important;
        min-width: auto !important;
    }
    .dropdown-cities {
        grid-template-columns: repeat(2, 1fr);
    }
    .location-dropdown {
        min-width: auto;
        width: 100%;
        max-height: 300px;
    }
    .trip-type-tabs .tab-btn {
        padding: 8px 16px;
        font-size: 13px;
    }
    .city-block .city-name {
        font-size: 16px;
    }
    .city-block .city-time {
        font-size: 22px;
    }
    .route-arrow {
        min-width: 40px;
    }
    .ticket-card {
        padding: 15px;
    }
    .ticket-footer {
        flex-direction: column;
        align-items: stretch;
        gap: 10px;
    }
    .book-btn {
        width: 100%;
        text-align: center;
    }
    .current-price {
        font-size: 24px;
    }
    .features-grid {
        grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
    }
    .skeleton-card {
        padding: 15px;
    }
}
</style>

<script>
// 城市数据和节假日数据
window.__citiesData = <?= $citiesJson ?>;
window.__holidaysData = <?= $holidaysJson ?>;
window.__regionsData = <?= $regionsJson ?>;
window.__today = '<?= $today ?>';
window.__maxDate = '<?= $maxDate ?>';
</script>

<script>
(function() {
    'use strict';
    var citiesData = window.__citiesData || [];
    var holidaysData = window.__holidaysData || {};
    var regionsData = window.__regionsData || [];
    var today = window.__today || '';
    var maxDate = window.__maxDate || '';

    // DOM元素
    var fromInput = document.getElementById('from_city');
    var toInput = document.getElementById('to_city');
    var fromDropdown = document.getElementById('fromDropdown');
    var toDropdown = document.getElementById('toDropdown');
    var swapBtn = document.getElementById('swapCities');
    var dateInput = document.getElementById('travel_date');
    var holidayHint = document.getElementById('holidayHint');
    var typeTabs = document.querySelectorAll('.type-tab');
    var ticketTypeInput = document.getElementById('ticket_type');
    var tabOneway = document.getElementById('tabOneway');
    var tabRoundtrip = document.getElementById('tabRoundtrip');
    var returnDateGroup = document.getElementById('returnDateGroup');
    var searchForm = document.getElementById('searchForm');
    var resultsSection = document.getElementById('resultsSection');
    var featuresSection = document.getElementById('featuresSection');
    var resultsList = document.getElementById('resultsList');
    var skeletonLoading = document.getElementById('skeletonLoading');
    var filterBar = document.getElementById('filterBar');
    var emptyState = document.getElementById('emptyState');
    var errorState = document.getElementById('errorState');
    var resultCount = document.getElementById('resultCount');
    var queryInfo = document.getElementById('queryInfo');
    var timeFilter = document.getElementById('timeFilter');
    var sortSelect = document.getElementById('sortSelect');
    var onlyDirect = document.getElementById('onlyDirect');
    var clearHistoryBtn = document.getElementById('clearHistory');
    var searchHistory = document.getElementById('searchHistory');

    var allResults = [];
    var currentFrom = '';
    var currentTo = '';

    // ========== 城市搜索匹配 ==========
    function matchCities(query) {
        if (!query || query.length < 1) return citiesData.slice(0, 20);
        var q = query.toLowerCase().trim();
        var results = [];
        citiesData.forEach(function(city) {
            var score = 0;
            var name = city.name;
            var py = city.pinyin || '';
            var pyAbbr = city.py || '';
            var code = city.code || '';

            if (name === q || name.indexOf(q) === 0) score = 100;
            else if (name.indexOf(q) !== -1) score = 80;
            else if (py === q) score = 90;
            else if (py.indexOf(q) === 0) score = 75;
            else if (py.indexOf(q) !== -1) score = 60;
            else if (pyAbbr === q) score = 85;
            else if (pyAbbr.indexOf(q) === 0) score = 50;
            else if (code.toLowerCase() === q) score = 95;

            if (score > 0) {
                results.push({ city: city, score: score, matchType: score >= 90 ? 'exact' : 'partial' });
            }
        });
        results.sort(function(a, b) { return b.score - a.score; });
        return results;
    }

    // ========== 渲染下拉面板 ==========
    function renderDropdown(dropdown, query, targetInput, otherInput) {
        if (!dropdown) return;
        var matches = matchCities(query);

        if (!query || query.length < 1) {
            // 显示全部热门城市
            var html = '<div class="dropdown-header"><i class="fas fa-fire"></i> 热门城市（点击选择）</div>';
            html += '<div class="dropdown-cities">';
            citiesData.forEach(function(city) {
                var sel = targetInput && targetInput.value === city.name ? ' selected' : '';
                html += '<div class="dropdown-city' + sel + '" data-city="' + city.name + '">';
                html += '<span class="city-icon">' + (city.icon || '') + '</span>';
                html += '<span class="city-name">' + city.name + '</span>';
                html += '<span class="city-code">' + (city.code || '') + '</span>';
                html += '</div>';
            });
            html += '</div>';
            html += '<div class="dropdown-divider"></div>';
            html += '<div class="dropdown-header"><i class="fas fa-globe-asia"></i> 按区域选择</div>';
            regionsData.forEach(function(region) {
                html += '<div class="region-group">';
                html += '<div class="region-name">' + region.name + '</div>';
                html += '<div class="region-cities">';
                region.cities.forEach(function(c) {
                    html += '<span class="region-city" data-city="' + c + '">' + c + '</span>';
                });
                html += '</div></div>';
            });
            dropdown.innerHTML = html;
        } else if (matches.length === 0) {
            dropdown.innerHTML = '<div class="dropdown-no-result"><i class="fas fa-search"></i> 未找到匹配城市，请尝试其他关键词</div>';
        } else {
            var exactCount = matches.filter(function(m) { return m.score >= 80; }).length;
            var html = '<div class="dropdown-match-info">找到 ' + matches.length + ' 个匹配城市</div>';
            html += '<div class="dropdown-cities">';
            matches.forEach(function(m) {
                var city = m.city;
                var sel = targetInput && targetInput.value === city.name ? ' selected' : '';
                html += '<div class="dropdown-city' + sel + '" data-city="' + city.name + '">';
                html += '<span class="city-icon">' + (city.icon || '') + '</span>';
                html += '<span class="city-name">' + city.name + '</span>';
                html += '<span class="city-code">' + (city.code || '') + '</span>';
                html += '</div>';
            });
            html += '</div>';
            dropdown.innerHTML = html;
        }

        dropdown.classList.add('show');

        // 绑定点击事件
        dropdown.querySelectorAll('.dropdown-city, .region-city').forEach(function(el) {
            el.addEventListener('click', function() {
                var city = this.getAttribute('data-city');
                if (targetInput) {
                    targetInput.value = city;
                    targetInput.dispatchEvent(new Event('change'));
                }
                dropdown.classList.remove('show');
            });
        });
    }

    // ========== 出发地输入处理 ==========
    if (fromInput) {
        fromInput.addEventListener('focus', function() {
            renderDropdown(fromDropdown, fromInput.value, fromInput, toInput);
        });
        fromInput.addEventListener('input', function() {
            renderDropdown(fromDropdown, fromInput.value, fromInput, toInput);
        });
    }

    // ========== 目的地输入处理 ==========
    if (toInput) {
        toInput.addEventListener('focus', function() {
            renderDropdown(toDropdown, toInput.value, toInput, fromInput);
        });
        toInput.addEventListener('input', function() {
            renderDropdown(toDropdown, toInput.value, toInput, fromInput);
        });
    }

    // ========== 点击外部关闭下拉 ==========
    document.addEventListener('click', function(e) {
        if (fromDropdown && !e.target.closest('#from_city') && !e.target.closest('#fromDropdown')) {
            fromDropdown.classList.remove('show');
        }
        if (toDropdown && !e.target.closest('#to_city') && !e.target.closest('#toDropdown')) {
            toDropdown.classList.remove('show');
        }
    });

    // ========== 交换城市 ==========
    if (swapBtn) {
        swapBtn.addEventListener('click', function() {
            var tmp = fromInput.value;
            fromInput.value = toInput.value;
            toInput.value = tmp;
        });
    }

    // ========== 单程/往返切换 ==========
    if (tabOneway && tabRoundtrip && returnDateGroup) {
        tabOneway.addEventListener('click', function() {
            tabOneway.classList.add('active');
            tabRoundtrip.classList.remove('active');
            returnDateGroup.style.display = 'none';
        });
        tabRoundtrip.addEventListener('click', function() {
            tabRoundtrip.classList.add('active');
            tabOneway.classList.remove('active');
            returnDateGroup.style.display = '';
        });
    }

    // ========== 票务类型切换 ==========
    typeTabs.forEach(function(tab) {
        tab.addEventListener('click', function() {
            typeTabs.forEach(function(t) { t.classList.remove('active'); });
            tab.classList.add('active');
            if (ticketTypeInput) {
                ticketTypeInput.value = tab.getAttribute('data-type');
            }
        });
    });

    // ========== 快捷日期按钮 ==========
    document.querySelectorAll('.preset-btn').forEach(function(btn) {
        btn.addEventListener('click', function() {
            var type = this.getAttribute('data-date');
            var d = new Date();
            if (type === 'today') {
                // already today
            } else if (type === 'tomorrow') {
                d.setDate(d.getDate() + 1);
            } else if (type === 'dayafter') {
                d.setDate(d.getDate() + 2);
            } else if (type === 'weekend') {
                var day = d.getDay();
                var add = day === 6 ? 1 : (day === 0 ? 6 : (6 - day));
                d.setDate(d.getDate() + add);
            }
            var yyyy = d.getFullYear();
            var mm = String(d.getMonth() + 1).padStart(2, '0');
            var dd = String(d.getDate()).padStart(2, '0');
            dateInput.value = yyyy + '-' + mm + '-' + dd;
            updateHolidayHint();
        });
    });

    // ========== 节假日提示 ==========
    function updateHolidayHint() {
        if (!holidayHint || !dateInput) return;
        var val = dateInput.value;
        if (holidaysData[val]) {
            holidayHint.innerHTML = '<i class="fas fa-calendar-check"></i> ' + holidaysData[val] + '（购票高峰期）';
            holidayHint.style.color = '#e74c3c';
        } else {
            var d = new Date(val);
            var day = d.getDay();
            if (day === 0 || day === 6) {
                holidayHint.innerHTML = '<i class="fas fa-calendar"></i> 周末（出行高峰）';
                holidayHint.style.color = '#e67e22';
            } else {
                holidayHint.innerHTML = '';
            }
        }
    }

    if (dateInput) {
        dateInput.addEventListener('change', updateHolidayHint);
        updateHolidayHint();
    }

    // ========== 历史记录点击 ==========
    document.querySelectorAll('.history-item').forEach(function(item) {
        item.addEventListener('click', function() {
            var from = this.getAttribute('data-from');
            var to = this.getAttribute('data-to');
            var date = this.getAttribute('data-date');
            var type = this.getAttribute('data-type');
            if (fromInput) fromInput.value = from;
            if (toInput) toInput.value = to;
            if (dateInput) dateInput.value = date;
            if (ticketTypeInput) ticketTypeInput.value = type;
            typeTabs.forEach(function(t) {
                t.classList.toggle('active', t.getAttribute('data-type') === type);
            });
            updateHolidayHint();
            searchForm.submit();
        });
    });

    // ========== 清除历史 ==========
    if (clearHistoryBtn) {
        clearHistoryBtn.addEventListener('click', function() {
            document.cookie = 'ticket_search_history=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;';
            if (searchHistory) searchHistory.style.display = 'none';
        });
    }

    // ========== 筛选偏好记忆 ==========
    function saveFilterPrefs() {
        var prefs = {
            timeFilter: timeFilter ? timeFilter.value : 'all',
            sortSelect: sortSelect ? sortSelect.value : 'depart_asc',
            onlyDirect: onlyDirect ? onlyDirect.checked : false
        };
        try {
            localStorage.setItem('ticket_filter_prefs', JSON.stringify(prefs));
        } catch(e) {}
    }

    function loadFilterPrefs() {
        try {
            var prefs = JSON.parse(localStorage.getItem('ticket_filter_prefs'));
            if (prefs) {
                if (timeFilter && prefs.timeFilter) timeFilter.value = prefs.timeFilter;
                if (sortSelect && prefs.sortSelect) sortSelect.value = prefs.sortSelect;
                if (onlyDirect && prefs.onlyDirect !== undefined) onlyDirect.checked = prefs.onlyDirect;
            }
        } catch(e) {}
    }

    loadFilterPrefs();

    if (timeFilter) timeFilter.addEventListener('change', function() { applyFilters(); saveFilterPrefs(); });
    if (sortSelect) sortSelect.addEventListener('change', function() { applyFilters(); saveFilterPrefs(); });
    if (onlyDirect) onlyDirect.addEventListener('change', function() { applyFilters(); saveFilterPrefs(); });

    // ========== 筛选与排序 ==========
    function applyFilters() {
        var filtered = allResults.slice();

        // 出发时段筛选
        if (timeFilter && timeFilter.value !== 'all') {
            filtered = filtered.filter(function(r) {
                var hour = parseInt(r.depart_time.split(':')[0]);
                if (timeFilter.value === 'morning') return hour >= 6 && hour < 12;
                if (timeFilter.value === 'afternoon') return hour >= 12 && hour < 18;
                if (timeFilter.value === 'evening') return hour >= 18 || hour < 6;
                return true;
            });
        }

        // 直达筛选
        if (onlyDirect && onlyDirect.checked) {
            filtered = filtered.filter(function(r) { return !r.transit || r.transit === 0; });
        }

        // 排序
        if (sortSelect) {
            var sortVal = sortSelect.value;
            filtered.sort(function(a, b) {
                switch(sortVal) {
                    case 'depart_asc': return a.depart_time.localeCompare(b.depart_time);
                    case 'depart_desc': return b.depart_time.localeCompare(a.depart_time);
                    case 'arrive_asc': return a.arrive_time.localeCompare(b.arrive_time);
                    case 'arrive_desc': return b.arrive_time.localeCompare(a.arrive_time);
                    case 'duration_asc': return a.duration_min - b.duration_min;
                    case 'duration_desc': return b.duration_min - a.duration_min;
                    case 'price_asc': return a.price - b.price;
                    case 'price_desc': return b.price - a.price;
                    default: return 0;
                }
            });
        }

        renderResults(filtered);
    }

    // ========== 渲染搜索结果 ==========
    function renderResults(results) {
        if (!resultsList) return;

        if (results.length === 0) {
            resultsList.innerHTML = '';
            if (emptyState) {
                emptyState.style.display = '';
                var hint = document.getElementById('emptyHint');
                if (hint) hint.textContent = '当前筛选条件下没有匹配班次，请调整筛选条件';
                var sugg = document.getElementById('emptySuggestions');
                if (sugg) {
                    sugg.innerHTML = '<span class="suggestion-item" onclick="document.getElementById(\'timeFilter\').value=\'all\';applyFilters();">清除时段筛选</span>' +
                        '<span class="suggestion-item" onclick="document.getElementById(\'onlyDirect\').checked=false;applyFilters();">显示中转</span>' +
                        '<span class="suggestion-item" onclick="document.getElementById(\'sortSelect\').value=\'depart_asc\';applyFilters();">重置排序</span>';
                }
            }
        } else {
            if (emptyState) emptyState.style.display = 'none';
        }

        if (errorState) errorState.style.display = 'none';
        if (resultCount) resultCount.textContent = '共找到 ' + results.length + ' 个班次';
        if (queryInfo) queryInfo.textContent = currentFrom + ' → ' + currentTo;

        var html = '';
        results.forEach(function(r) {
            var transitClass = r.transit ? ' transit-card' : '';
            html += '<div class="ticket-card' + transitClass + '">';

            // Header
            html += '<div class="ticket-header">';
            html += '<div class="ticket-operator">' + r.operator + '</div>';
            html += '<div class="ticket-number">' + r.number + '</div>';
            html += '<div class="ticket-type">' + r.type + '</div>';
            html += '</div>';

            // Body
            html += '<div class="ticket-body">';
            html += '<div class="route-info">';
            html += '<div class="city-block"><span class="city-name">' + r.from + '</span><span class="city-time">' + r.depart_time + '</span></div>';
            html += '<div class="route-arrow">';
            html += '<i class="fas fa-arrow-right"></i>';
            if (r.transit) {
                html += '<span class="transit-tag">中转' + r.transit + '站</span>';
                if (r.transit_stations) html += '<div class="transit-info">经停：' + r.transit_stations + '</div>';
            }
            html += '</div>';
            html += '<div class="city-block"><span class="city-name">' + r.to + '</span><span class="city-time">' + r.arrive_time + '</span></div>';
            html += '</div>';
            html += '<div class="ticket-info"><span>⏱️ ' + r.duration + '</span>' + (r.on_time_rate > 0 ? '<span>📊 准点率 ' + r.on_time_rate + '%</span>' : '') + '</div>';
            html += '</div>';

            // Footer
            html += '<div class="ticket-footer">';
            html += '<div class="price-section">';
            if (r.price > 0) {
                if (r.discount > 0) {
                    html += '<span class="original-price">¥' + Math.round(r.price / (1 - r.discount / 100)) + '</span>';
                }
                html += '<span class="current-price">¥' + r.price + '</span>';
                if (r.discount > 0) {
                    html += '<span class="discount-tag">' + r.discount + '% OFF</span>';
                }
            }
            if (r.source === '12306') {
                html += '<span class="data-source" style="font-size:11px;color:#52c41a;background:#f6ffed;padding:2px 8px;border-radius:10px;border:1px solid #b7eb8f;">12306实时</span>';
            }
            html += '</div>';
            html += '<div class="seat-section">';
            for (var seatType in r.seats) {
                var count = r.seats[seatType];
                var isAvailable = false;
                var displayText = '';
                if (typeof count === 'string') {
                    displayText = count;
                    isAvailable = count !== '售罄' && count !== '无' && count !== '--' && count !== '';
                } else if (typeof count === 'number') {
                    isAvailable = count > 0;
                    displayText = count > 0 ? count + '张' : '售罄';
                } else {
                    displayText = String(count);
                    isAvailable = true;
                }
                html += '<span class="seat-type">' + seatType + ': <span class="' + (isAvailable ? 'available' : 'soldout') + '">' + displayText + '</span></span>';
            }
            html += '</div>';
            html += '<button class="book-btn" onclick="window.open(\'https://kyfw.12306.cn/otn/leftTicket/init\',\'_blank\')">去12306预订</button>';
            html += '</div>';

            html += '</div>';
        });

        resultsList.innerHTML = html;
    }

    // ========== 显示加载状态 ==========
    function showLoading() {
        if (resultsSection) resultsSection.style.display = '';
        if (featuresSection) featuresSection.style.display = 'none';
        if (skeletonLoading) skeletonLoading.style.display = '';
        if (filterBar) filterBar.style.display = 'none';
        if (resultsList) resultsList.innerHTML = '';
        if (emptyState) emptyState.style.display = 'none';
        if (errorState) errorState.style.display = 'none';
    }

    function showResults() {
        if (skeletonLoading) skeletonLoading.style.display = 'none';
        if (filterBar) filterBar.style.display = '';
    }

    function showError(msg) {
        if (skeletonLoading) skeletonLoading.style.display = 'none';
        if (filterBar) filterBar.style.display = 'none';
        if (emptyState) emptyState.style.display = 'none';
        if (errorState) errorState.style.display = '';
        var errMsg = document.getElementById('errorMsg');
        if (errMsg) errMsg.textContent = msg || '网络连接异常，请检查网络后重试';
    }

    // ========== AJAX搜索 ==========
    searchForm.addEventListener('submit', function(e) {
        var from = fromInput ? fromInput.value.trim() : '';
        var to = toInput ? toInput.value.trim() : '';
        var date = dateInput ? dateInput.value : '';
        var type = ticketTypeInput ? ticketTypeInput.value : 'train';

        if (!from || !to) {
            e.preventDefault();
            alert('请输入出发城市和目的城市');
            return false;
        }

        currentFrom = from;
        currentTo = to;

        e.preventDefault();
        showLoading();

        // 使用FormData提交
        var formData = new FormData(searchForm);

        fetch('tickets.php?ajax=1', {
            method: 'POST',
            body: formData
        })
        .then(function(response) {
            if (!response.ok) throw new Error('服务器响应异常');
            return response.json();
        })
        .then(function(json) {
            if (json.success && json.data) {
                allResults = json.data;
                showResults();
                applyFilters();
            } else {
                allResults = [];
                showResults();
                renderResults([]);
            }
        })
        .catch(function(err) {
            showError(err.message || '网络连接异常，请检查网络后重试');
        });

        return false;
    });

    // ========== 预加载结果渲染 ==========
    if (window.__preloadedResults && window.__preloadedResults.length > 0) {
        allResults = window.__preloadedResults;
        currentFrom = window.__preloadedFrom || '';
        currentTo = window.__preloadedTo || '';
        if (resultsSection) resultsSection.style.display = '';
        if (featuresSection) featuresSection.style.display = 'none';
        if (skeletonLoading) skeletonLoading.style.display = 'none';
        if (filterBar) filterBar.style.display = '';
        if (queryInfo) queryInfo.textContent = currentFrom + ' → ' + currentTo;
        renderResults(allResults);
    }

})();
</script>

<?php require_once 'footer.php'; ?>