<?php
/**
 * 800BUS - 档案浏览
 */
require_once __DIR__ . '/includes/config.php';
require_once __DIR__ . '/includes/media_helpers.php';
session_start();

$is_logged_in = isset($_SESSION['user_id']);
$user_data = null;
if ($is_logged_in) {
    $uid = $_SESSION['user_id'];
    $u_res = $conn->query("SELECT username, is_admin FROM users WHERE id = " . (int)$uid);
    $user_data = $u_res ? $u_res->fetch_assoc() : null;
}

$co_id = (int)($_GET['co'] ?? 0);
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover">
    <title>档案浏览 - 800BUS</title>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }

        body {
            background: url('https://bg-img.800bus.cn/800bus/system/') center/cover fixed;
            color: #2d3748;
            font-family: -apple-system, BlinkMacSystemFont, "PingFang SC", "Microsoft YaHei", sans-serif;
            min-height: 100vh;
            display: flex;
            flex-direction: column;
        }

        .bg-overlay {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(232, 238, 244, 0.85);
            z-index: -1;
        }

        .nav {
            position: sticky;
            top: 0;
            width: 100%;
            height: 56px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 0 24px;
            background: rgba(255,255,255,0.85);
            backdrop-filter: blur(12px);
            border-bottom: 1px solid #cbd5e0;
            z-index: 1000;
        }
        .nav .logo {
            font-size: 18px;
            font-weight: 700;
            color: #2b6cb0;
            text-decoration: none;
            display: flex;
            align-items: center;
            gap: 1rem;
        }
        .nav .links {
            display: flex;
            align-items: center;
            gap: 4px;
        }
        .nav a {
            text-decoration: none;
            color: #4a5568;
            padding: 6px 12px;
            border-radius: 6px;
            font-size: 14px;
            transition: background 0.15s;
        }
        .nav a:hover {
            background: #e2e8f0;
        }
        .nav a.active {
            background: #2b6cb0;
            color: #fff;
        }
        .nav a.admin-tag {
            background: #fed7d7;
            color: #c53030;
        }
        .nav a.admin-tag:hover {
            background: #feb2b2;
        }

        .back-btn {
            display: flex;
            align-items: center;
            gap: 4px;
            background: #f1f5f9;
            border: none;
            padding: 8px 14px;
            border-radius: 6px;
            cursor: pointer;
            font-size: 14px;
            color: #4a5568;
            transition: all 0.2s;
        }
        .back-btn:hover {
            background: #e2e8f0;
            color: #2d3748;
        }
        .back-btn.hidden {
            display: none;
        }

        .main-wrapper {
            flex: 1;
        }

        .main-container {
            max-width: 1200px;
            margin: 2rem auto;
            padding: 0 20px;
        }

        .page-header {
            text-align: center;
            margin-bottom: 2rem;
            padding: 40px 0 20px;
        }
        .page-header h1 {
            font-size: 32px;
            font-weight: 700;
            color: #1a202c;
            margin-bottom: 8px;
        }
        .page-header p {
            color: #718096;
            font-size: 15px;
        }

        .stats-bar {
            background: #fff;
            border-radius: 8px;
            padding: 24px;
            margin-bottom: 24px;
            border: 1px solid #cbd5e0;
            display: flex;
            justify-content: center;
            gap: 32px;
            flex-wrap: wrap;
        }
        .stat-item {
            text-align: center;
            padding: 12px 8px;
            border-radius: 6px;
            background: #f7fafc;
        }
        .stat-value {
            font-size: 26px;
            font-weight: 700;
            margin-bottom: 2px;
        }
        .stat-label {
            font-size: 11px;
            color: #718096;
        }
        .stat-item.blue .stat-value { color: #2b6cb0; }
        .stat-item.green .stat-value { color: #38a169; }

        .breadcrumb {
            display: flex;
            align-items: center;
            gap: 8px;
            margin-bottom: 24px;
            font-size: 14px;
            color: #718096;
        }
        .breadcrumb a {
            color: #2b6cb0;
            text-decoration: none;
        }
        .breadcrumb a:hover {
            text-decoration: underline;
        }
        .breadcrumb span {
            color: #cbd5e0;
        }

        .post-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(260px, 1fr));
            gap: 16px;
        }

        .post-card {
            background: #fff;
            border-radius: 8px;
            overflow: hidden;
            text-decoration: none;
            color: inherit;
            display: flex;
            flex-direction: column;
            border: 1px solid #e2e8f0;
            transition: border-color 0.15s;
        }
        .post-card:hover {
            border-color: #4299e1;
        }

        .post-card .photo-img {
            width: 100%;
            aspect-ratio: 16/10;
            object-fit: cover;
            background: #edf2f7;
        }

        .post-content {
            padding: 12px;
        }

        .post-title {
            font-weight: 600;
            font-size: 14px;
            margin-bottom: 2px;
            color: #2d3748;
        }

        .post-meta {
            font-size: 12px;
            color: #718096;
            display: flex;
            flex-wrap: wrap;
            gap: 0.5rem;
            align-items: center;
        }

        .post-addr {
            font-size: 12px;
            color: #718096;
            margin-top: 4px;
        }

        .badge {
            background: #edf2f7;
            color: #718096;
            padding: 2px 8px;
            border-radius: 4px;
            font-size: 12px;
        }

        .lazy-img {
            opacity: 0;
            filter: blur(8px);
            transform: scale(1.03);
            transition: opacity 0.4s ease-out, filter 0.3s ease-out, transform 0.3s ease-out;
        }
        .lazy-img.loaded {
            opacity: 1;
            filter: blur(0);
            transform: scale(1);
        }

        .hidden {
            display: none !important;
        }

        .empty-state {
            text-align: center;
            padding: 60px 20px;
            color: #718096;
            grid-column: 1 / -1;
        }
        .empty-state .icon {
            font-size: 48px;
            margin-bottom: 16px;
        }
        .empty-state p {
            font-size: 15px;
        }

        footer {
            margin-top: 60px;
            padding: 40px 20px;
            text-align: center;
            background: #edf2f7;
            border-top: 1px solid #cbd5e0;
        }
        .footer-logo {
            font-size: 22px;
            font-weight: 700;
            color: #2b6cb0;
            margin-bottom: 16px;
        }
        footer p {
            color: #718096;
            font-size: 13px;
            line-height: 1.7;
        }
        footer a {
            color: #2b6cb0;
            text-decoration: none;
        }
        footer a:hover {
            text-decoration: underline;
        }
        .footer-links {
            display: flex;
            justify-content: center;
            gap: 20px;
            margin-bottom: 14px;
        }

        .search-bar-wrap {
            position: relative;
            max-width: 500px;
            margin: 0 auto 24px;
        }

        .search-bar {
            display: flex;
            border: 1px solid #e2e8f0;
            border-radius: 8px;
            overflow: hidden;
            transition: border-color 0.2s;
        }

        .search-bar input {
            flex: 1;
            border: none;
            padding: 10px 12px;
            font-size: 14px;
            outline: none;
            background: #fff;
            color: #2d3748;
        }

        .search-bar input::placeholder {
            color: #a0aec0;
        }

        #quickSearchResult {
            position: relative;
            max-width: 500px;
            margin: 0 auto;
        }

        .quickSearchResultWrap {
            background: #fff;
            border-radius: 8px;
            box-shadow: 0 4px 16px rgba(0,0,0,0.12);
            margin-top: 4px;
            max-height: 60vh;
            overflow-y: auto;
            display: none;
        }

        .quickSearchResultWrap.quickSearchShow {
            display: block;
        }

        .region-item {
            padding: 10px 16px;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: space-between;
            transition: background 0.15s;
        }

        .region-item:hover {
            background: #f0f4ff;
        }

        .region-item-city {
            padding-left: 40px;
            background: #fffdf5;
        }

        .region-item-city:hover {
            background: #fef9e7;
        }

        .region-item-company {
            padding-left: 60px;
            background: #fffdf5;
        }

        .region-item-company:hover {
            background: #fef9e7;
        }

        .region-item .icon {
            color: #667eea;
            font-size: 13px;
            margin-right: 6px;
        }

        .region-item .name {
            flex: 1;
        }

        .region-item .name h4 {
            margin: 0;
            font-size: 14px;
            color: #2d3748;
        }

        .region-item .name p {
            margin: 2px 0 0;
            font-size: 12px;
            color: #a0aec0;
        }

        .region-item .count {
            color: #cbd5e0;
            font-size: 13px;
            white-space: nowrap;
        }

        .region-item mark {
            background: #fef08a;
            color: #92400e;
            padding: 0 2px;
            border-radius: 2px;
        }

        .quick-search-loading {
            text-align: center;
            padding: 16px;
            color: #a0aec0;
        }

        .quick-search-empty {
            text-align: center;
            padding: 30px 16px;
            color: #a0aec0;
        }

        .quick-search-section {
            font-size: 12px;
            font-weight: 600;
            padding: 8px 16px 4px;
            color: #a0aec0;
        }

        @media (max-width: 768px) {
            .nav {
                padding: 0 16px;
            }
            .nav a {
                padding: 6px 10px;
                font-size: 13px;
            }
            .page-header {
                padding: 30px 0 16px;
            }
            .page-header h1 {
                font-size: 24px;
            }
            .post-grid {
                grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
                gap: 12px;
            }
            .main-container {
                padding: 0 1rem;
                margin: 1rem auto;
            }
            .stats-bar {
                gap: 16px;
                padding: 16px;
            }
            .stat-value {
                font-size: 22px;
            }
        }
    </style>
    <script src="includes/lazyload.js" defer></script>
</head>
<body>

<div class="bg-overlay"></div>

<nav class="nav">
    <div class="logo">
        <a href="/" style="text-decoration:none;color:#2b6cb0;">800BUS</a>
        <button id="backBtn" class="back-btn hidden" onclick="goBack()">← 返回</button>
    </div>
    <div class="links">
        <a href="about.php">关于我们</a>
        <a href="gallery.php">浏览画廊</a>
        <a href="explore.php" style="background:linear-gradient(135deg,#6366f1,#a855f7);color:#fff;box-shadow:0 2px 10px rgba(99,102,241,0.3);">🎬 探索</a>
        <a href="browse.php" class="active">档案浏览</a>
        <?php if($is_logged_in): ?>
            <?php if(isset($user_data['is_admin']) && $user_data['is_admin'] == 1): ?>
                <a href="admin/" class="admin-tag">后台管理</a>
            <?php endif; ?>
            <a href="user/">个人中心</a>
        <?php else: ?>
            <a href="login.php">登入系统</a>
        <?php endif; ?>
    </div>
</nav>

<div class="main-wrapper">
<main class="main-container">
    <div class="page-header">
        <h1>档案浏览</h1>
        <p>按地区分类浏览全部巴士档案</p>
    </div>
    <div id="quickSearchResult">
        <div class="search-bar-wrap">
            <div class="search-bar">
                <input type="text" id="quickSearchInput" placeholder="搜索省份、市县、公司..." autocomplete="off" oninput="handleQuickSearch(this.value)">
            </div>
        </div>
        <div class="quickSearchResultWrap" id="quickSearchResultWrap"></div>
    </div>
    <div id="selectionGrid" class="post-grid"></div>
    <div id="companyInfoBar" style="display:none;margin-bottom:20px;background:#fff;border-radius:12px;padding:16px 20px;border:1px solid #e2e8f0;">
        <div style="font-size:18px;font-weight:700;color:#1a202c;margin-bottom:4px;" id="companyInfoName"></div>
        <div style="font-size:13px;color:#718096;" id="companyInfoAddr"></div>
    </div>
    <div id="companyNews" style="display:none;margin-bottom:24px;background:#fff;border-radius:12px;padding:20px;border:1px solid #e2e8f0;">
        <div style="font-size:16px;font-weight:700;color:#1a202c;margin-bottom:16px;display:flex;align-items:center;gap:8px;">
            📰 本地区资讯
            <span id="companyNewsCount" style="font-size:12px;font-weight:500;color:#718096;background:#f1f5f9;padding:2px 8px;border-radius:10px;"></span>
        </div>
        <div id="companyNewsList" style="display:flex;flex-direction:column;gap:12px;"></div>
        <div id="companyNewsEmpty" style="display:none;text-align:center;padding:20px;color:#a0aec0;font-size:14px;">暂无相关资讯</div>
    </div>
    <div id="photoGrid" class="post-grid hidden"></div>
    <div id="paginationContainer" style="display:none;text-align:center;padding:24px 0;">
        <div id="paginationInfo" style="color:#718096;font-size:14px;margin-bottom:12px;"></div>
        <div id="paginationBtns" style="display:flex;justify-content:center;gap:8px;flex-wrap:wrap;"></div>
    </div>
    <div id="companyStats" style="display:none;text-align:center;margin-top:32px;padding:20px;color:#718096;font-size:14px;"></div>
    <div id="regionAdmins" style="display:none;max-width:960px;margin:24px auto 0;padding:0 16px;">
        <div style="background:#fff;border-radius:16px;padding:20px 24px;border:1px solid #e2e8f0;">
            <div style="font-size:15px;font-weight:700;color:#1a202c;margin-bottom:12px;">👤 本区域管理员</div>
            <div id="regionAdminsList" style="display:flex;flex-wrap:wrap;gap:10px;"></div>
        </div>
    </div>
</main>
</div>

<?php require_once __DIR__ . '/system/footer.php'; ?>

<script>
    const state = { step: 'province', p: null, c: null, co: null, page: 1, totalPages: 1 };

    function deriveBlurPath(path) {
        // 如果是完整URL，直接在URL中添加_blur后缀
        if (path.startsWith('http://') || path.startsWith('https://')) {
            var lastDot = path.lastIndexOf('.');
            if (lastDot === -1) return path + '_blur';
            return path.substring(0, lastDot) + '_blur' + path.substring(lastDot);
        }
        // 否则作为相对路径处理
        var normalized = path.startsWith('/') ? path : '/' + path;
        var lastDot = normalized.lastIndexOf('.');
        if (lastDot === -1) return normalized + '_blur';
        return normalized.substring(0, lastDot) + '_blur' + normalized.substring(lastDot);
    }

    function deriveThumbPath(path) {
        // 如果是完整URL，直接在URL中添加_thumb后缀
        if (path.startsWith('http://') || path.startsWith('https://')) {
            var lastDot = path.lastIndexOf('.');
            if (lastDot === -1) return path + '_thumb';
            return path.substring(0, lastDot) + '_thumb' + path.substring(lastDot);
        }
        // 否则作为相对路径处理
        var normalized = path.startsWith('/') ? path : '/' + path;
        var lastDot = normalized.lastIndexOf('.');
        if (lastDot === -1) return normalized + '_thumb';
        return normalized.substring(0, lastDot) + '_thumb' + normalized.substring(lastDot);
    }

    function renderPhotoCard(photo) {
        // 如果photo_path已经是完整URL（以http://或https://开头），则直接使用
        // 否则作为相对路径处理，添加/前缀
        const fullPath = photo.photo_path.startsWith('http://') || photo.photo_path.startsWith('https://') 
            ? photo.photo_path 
            : (photo.photo_path.startsWith('/') ? photo.photo_path : '/' + photo.photo_path);
        const blurPath = deriveBlurPath(fullPath);
        const thumbPath = deriveThumbPath(fullPath);

        return `
            <a href="/photo/${photo.id}" class="post-card">
                <img src="${blurPath}"
                     data-src="${thumbPath}"
                     data-fallback="${fullPath}"
                     class="photo-img lazy-img"
                     loading="lazy"
                     decoding="async"
                     alt="${photo.license_plate}"
                     onerror="this.onerror=null;var f=this.getAttribute('data-fallback');if(f&&this.src.indexOf(f)===-1)this.src=f;">
                <div class="post-content">
                    <div class="post-title">${photo.license_plate || photo.brand || 'BUS ARCHIVE'}</div>
                    <div class="post-meta">
                        <span>${photo.brand || '未标记型号'}</span>
                        <span class="badge">ID: ${photo.id}</span>
                    </div>
                </div>
            </a>
        `;
    }

    const imgObserver = new IntersectionObserver(function(entries, obs) {
        entries.forEach(function(entry) {
            if (!entry.isIntersecting) return;

            var img = entry.target;
            var src = img.getAttribute('data-src');
            var fallback = img.getAttribute('data-fallback');

            if (!src || img.dataset.loadedHigh === '1') {
                obs.unobserve(img);
                return;
            }

            var highImg = new Image();
            highImg.onload = function() {
                img.src = src;
                img.classList.add('loaded');
                img.dataset.loadedHigh = '1';

                if (fallback && fallback !== src) {
                    var fullImg = new Image();
                    fullImg.onload = function() {
                        img.src = fallback;
                    };
                    fullImg.src = fallback;
                }
            };
            highImg.onerror = function() {
                if (fallback && fallback !== src) {
                    var fbImg = new Image();
                    fbImg.onload = fbImg.onerror = function() {
                        img.src = fallback;
                        img.classList.add('loaded');
                    };
                    fbImg.src = fallback;
                } else {
                    img.classList.add('loaded');
                }
            };
            highImg.src = src;

            obs.unobserve(img);
        });
    }, {
        rootMargin: '200px 0px'
    });

    async function apiRequest(action, params = '') {
        const res = await fetch(`api/regions.php?action=${action}${params}`);
        const text = await res.text();
        return JSON.parse(text.match(/\{[\s\S]*\}/)[0]);
    }

    async function loadRegionAdmins(provinceId, cityId) {
        const wrap = document.getElementById('regionAdmins');
        const list = document.getElementById('regionAdminsList');
        wrap.style.display = 'none';
        list.innerHTML = '';
        var params = '';
        if (cityId) params = '&city_id=' + cityId;
        else if (provinceId) params = '&province_id=' + provinceId;
        else return;
        try {
            var json = await apiRequest('get_region_admins', params);
            if (json.success && json.data && json.data.length > 0) {
                list.innerHTML = json.data.map(function(a) {
                    var avatarContent = '';
                    if (a.email && a.email.indexOf('@qq.com') !== -1) {
                        var qq = a.email.split('@')[0];
                        avatarContent = '<img src="http://q1.qlogo.cn/g?b=qq&nk=' + qq + '&s=40" style="width:28px;height:28px;border-radius:50%;object-fit:cover;">';
                    } else {
                        avatarContent = '<span style="width:28px;height:28px;border-radius:50%;background:#e2e8f0;display:flex;align-items:center;justify-content:center;font-size:12px;font-weight:700;color:#4a5568;">' + (a.username.charAt(0) || '?') + '</span>';
                    }
                    return '<a href="/user/' + a.id + '" style="display:inline-flex;align-items:center;gap:8px;padding:8px 16px;background:#f7fafc;border:1px solid #e2e8f0;border-radius:24px;text-decoration:none;color:#2d3748;font-size:13px;font-weight:500;transition:all 0.2s;" onmouseover="this.style.background=\'#edf2f7\'" onmouseout="this.style.background=\'#f7fafc\'">'
                        + avatarContent
                        + '<span>' + a.username + '</span></a>';
                }).join('');
                wrap.style.display = 'block';
            }
        } catch(e) {}
    }

    function showCompanyNews(newsJson) {
        const newsContainer = document.getElementById('companyNews');
        const newsList = document.getElementById('companyNewsList');
        const newsEmpty = document.getElementById('companyNewsEmpty');
        const newsCount = document.getElementById('companyNewsCount');
        
        if (!newsJson.success || !newsJson.data || newsJson.data.length === 0) {
            newsContainer.style.display = 'none';
            return;
        }
        
        const news = newsJson.data;
        newsCount.textContent = news.length + '条';
        
        newsList.innerHTML = news.map(function(item) {
            // 处理图片
            let imageHtml = '';
            if (item.images && Array.isArray(item.images) && item.images.length > 0) {
                const imgUrl = item.images[0].thumbnail || item.images[0].original;
                if (imgUrl) {
                    imageHtml = `<div style="width:60px;height:60px;border-radius:8px;overflow:hidden;flex-shrink:0;background:#f1f5f9;">
                        <img src="${imgUrl}" style="width:100%;height:100%;object-fit:cover;" onerror="this.parentElement.style.display='none'">
                    </div>`;
                }
            }
            
            // 分类标签颜色
            const categoryColor = item.category === '公交运营' ? 
                'background:#eff6ff;color:#1e40af;' : 
                'background:#f0fdf4;color:#166534;';
            
            // 内容摘要（移除HTML标签）
            let summary = item.content || '';
            summary = summary.replace(/<[^>]*>/g, '').substring(0, 100);
            if (summary.length > 100) summary += '...';
            
            // 时间格式化
            const time = new Date(item.created_at).toLocaleDateString('zh-CN');
            
            return `
                <a href="/news/${item.id}" style="display:flex;gap:12px;padding:12px;background:#f8fafc;border-radius:10px;text-decoration:none;color:inherit;transition:all 0.2s;border:1px solid transparent;" 
                   onmouseover="this.style.background='#f1f5f9';this.style.borderColor='#e2e8f0'" 
                   onmouseout="this.style.background='#f8fafc';this.style.borderColor='transparent'">
                    ${imageHtml}
                    <div style="flex:1;min-width:0;">
                        <div style="display:flex;align-items:center;gap:6px;margin-bottom:4px;">
                            <span style="font-size:11px;padding:2px 8px;border-radius:6px;font-weight:600;${categoryColor}">${item.category}</span>
                            <span style="font-size:12px;color:#94a3b8;">${time}</span>
                        </div>
                        <div style="font-size:14px;font-weight:600;color:#1e293b;margin-bottom:4px;line-height:1.4;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;">${item.title}</div>
                        <div style="font-size:12px;color:#64748b;line-height:1.5;display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden;">${summary}</div>
                    </div>
                </a>
            `;
        }).join('');
        
        newsContainer.style.display = 'block';
    }

    async function navigate() {
        const params = new URLSearchParams(location.search);
        state.p = params.get('p');
        state.c = params.get('c');
        state.co = params.get('co');
        state.page = parseInt(params.get('page')) || 1;

        const infoBar = document.getElementById('companyInfoBar');
        const infoName = document.getElementById('companyInfoName');
        const infoAddr = document.getElementById('companyInfoAddr');
        const statsEl = document.getElementById('companyStats');
        const regionAdminsEl = document.getElementById('regionAdmins');
        const paginationContainer = document.getElementById('paginationContainer');
        regionAdminsEl.style.display = 'none';
        paginationContainer.style.display = 'none';

        if (state.co) {
            state.step = 'archive';
            infoBar.style.display = 'block';
            infoName.textContent = '加载中...';
            infoAddr.textContent = '';
            statsEl.style.display = 'none';
            const [photosJson, companyJson, photographersJson, newsJson] = await Promise.all([
                apiRequest('get_company_photos', `&company_id=${state.co}&page=${state.page}`),
                apiRequest('get_company', `&company_id=${state.co}`),
                apiRequest('get_company_photographers', `&company_id=${state.co}`),
                apiRequest('get_company_news', `&company_id=${state.co}`)
            ]);
            showPhotos(photosJson.data);
            if (photosJson.pagination) {
                state.totalPages = photosJson.pagination.total_pages || 1;
                if (state.totalPages > 1) {
                    renderPagination(photosJson.pagination);
                    paginationContainer.style.display = 'block';
                }
            }
            if (companyJson.success && companyJson.data) {
                const c = companyJson.data;
                infoName.textContent = c.name || '';
                infoAddr.textContent = c.address ? ('📍 ' + c.address) : '';
            }
            if (photographersJson.success && photographersJson.data) {
                var photographers = photographersJson.data.photographers || [];
                var stats = photographersJson.data.stats || {};
                var pc = parseInt(stats.photographer_count) || 0;
                var hc = parseInt(stats.photo_count) || 0;
                var statsText = '本公司页面由 ' + pc + ' 位摄影师共同维护，现存影像档案 ' + hc + ' 件。';
                if (photographers.length > 0) {
                    var links = photographers.map(function(p) {
                        var avatar = '';
                        if (p.email && p.email.indexOf('@qq.com') !== -1) {
                            var qq = p.email.split('@')[0];
                            avatar = '<img src="http://q1.qlogo.cn/g?b=qq&nk=' + qq + '&s=40" style="width:20px;height:20px;border-radius:50%;vertical-align:middle;margin-right:2px;">';
                        }
                        return avatar + '<a href="/user/' + p.id + '" style="color:#2b6cb0;text-decoration:none;font-weight:600;">' + p.username + '</a>';
                    }).join('、');
                    statsText += '<br>感谢摄影师: ' + links;
                }
                statsEl.innerHTML = statsText;
                statsEl.style.display = 'block';
            }
            showCompanyNews(newsJson);
        } else if (state.c) {
            state.step = 'company';
            infoBar.style.display = 'none';
            statsEl.style.display = 'none';
            
            const cityStatsJson = await apiRequest('get_city_stats', `&city_id=${state.c}`);
            if (cityStatsJson.success && cityStatsJson.data) {
                var pc = parseInt(cityStatsJson.data.photographer_count) || 0;
                var hc = parseInt(cityStatsJson.data.photo_count) || 0;
                var cityStatsText = '本页由 ' + pc + ' 位摄影师共同维护，共上传档案 ' + hc + ' 份。';
                statsEl.innerHTML = cityStatsText;
                statsEl.style.display = 'block';
            }
            
            const json = await apiRequest('get_companies', `&city_id=${state.c}`);
            showSelection(json.data, 'company');
            loadRegionAdmins(null, state.c);
        } else if (state.p) {
            state.step = 'city';
            infoBar.style.display = 'none';
            statsEl.style.display = 'none';
            
            const provinceStatsJson = await apiRequest('get_province_stats', `&province_id=${state.p}`);
            if (provinceStatsJson.success && provinceStatsJson.data) {
                var pc = parseInt(provinceStatsJson.data.photographer_count) || 0;
                var hc = parseInt(provinceStatsJson.data.photo_count) || 0;
                var provinceStatsText = '本页由 ' + pc + ' 位摄影师共同维护，共上传档案 ' + hc + ' 份。';
                statsEl.innerHTML = provinceStatsText;
                statsEl.style.display = 'block';
            }
            
            const json = await apiRequest('get_cities', `&province_id=${state.p}`);
            showSelection(json.data, 'city');
            loadRegionAdmins(state.p, null);
        } else {
            state.step = 'province';
            infoBar.style.display = 'none';
            statsEl.style.display = 'none';
            const json = await apiRequest('get_provinces');
            showSelection(json.data, 'province');
        }
        updateNav();
    }

    function showSelection(data, type) {
        document.getElementById('photoGrid').classList.add('hidden');
        const grid = document.getElementById('selectionGrid');
        grid.classList.remove('hidden');
        grid.innerHTML = data.map(item => {
            let meta = '';
            if (type === 'province') {
                meta = `${item.city_count || 0} 个市县 · ${item.photo_count || 0} 份档案`;
            } else if (type === 'city') {
                meta = `${item.company_count || 0} 家公司 · ${item.photo_count || 0} 份档案`;
            } else if (type === 'company') {
                meta = `${item.photo_count || 0} 份档案`;
            }
            let addr = '';
            if (type === 'company' && item.address) {
                addr = `<div class="post-addr">📍 ${item.address}</div>`;
            }
            return `
            <div class="post-card" onclick="handleSelect('${item.id}', '${type}')" style="cursor:pointer">
                <div class="post-content">
                    <div class="post-title">${item.name}</div>
                    <div class="post-meta">${meta}</div>
                    ${addr}
                </div>
            </div>`;
        }).join('');
    }

    function showPhotos(photos) {
        document.getElementById('selectionGrid').classList.add('hidden');
        const grid = document.getElementById('photoGrid');
        grid.classList.remove('hidden');

        if (photos.length) {
            grid.innerHTML = photos.map(renderPhotoCard).join('');
            document.querySelectorAll('.lazy-img').forEach(function(img) {
                imgObserver.observe(img);
            });
        } else {
            grid.innerHTML = '<div class="empty-state"><div class="icon">📭</div><p>暂无档案内容</p></div>';
        }
    }

    function renderPagination(pagination) {
        const infoEl = document.getElementById('paginationInfo');
        const btnsEl = document.getElementById('paginationBtns');
        infoEl.textContent = '第 ' + pagination.current_page + ' / ' + pagination.total_pages + ' 页，共 ' + pagination.total + ' 条档案';
        
        var html = '';
        var cp = pagination.current_page;
        var tp = pagination.total_pages;
        
        if (cp > 1) {
            html += '<a href="javascript:void(0)" onclick="goToPage(1)" style="padding:8px 14px;background:#fff;border:1px solid #cbd5e0;border-radius:6px;text-decoration:none;color:#4a5568;font-size:14px;">首页</a>';
            html += '<a href="javascript:void(0)" onclick="goToPage(' + (cp - 1) + ')" style="padding:8px 14px;background:#fff;border:1px solid #cbd5e0;border-radius:6px;text-decoration:none;color:#4a5568;font-size:14px;">上一页</a>';
        }
        
        var startPage = Math.max(1, cp - 2);
        var endPage = Math.min(tp, cp + 2);
        if (startPage > 1) {
            html += '<span style="padding:8px;color:#a0aec0;">...</span>';
        }
        for (var i = startPage; i <= endPage; i++) {
            if (i === cp) {
                html += '<span style="padding:8px 14px;background:#2b6cb0;color:#fff;border-radius:6px;font-size:14px;font-weight:600;">' + i + '</span>';
            } else {
                html += '<a href="javascript:void(0)" onclick="goToPage(' + i + ')" style="padding:8px 14px;background:#fff;border:1px solid #cbd5e0;border-radius:6px;text-decoration:none;color:#4a5568;font-size:14px;">' + i + '</a>';
            }
        }
        if (endPage < tp) {
            html += '<span style="padding:8px;color:#a0aec0;">...</span>';
        }
        
        if (cp < tp) {
            html += '<a href="javascript:void(0)" onclick="goToPage(' + (cp + 1) + ')" style="padding:8px 14px;background:#fff;border:1px solid #cbd5e0;border-radius:6px;text-decoration:none;color:#4a5568;font-size:14px;">下一页</a>';
            html += '<a href="javascript:void(0)" onclick="goToPage(' + tp + ')" style="padding:8px 14px;background:#fff;border:1px solid #cbd5e0;border-radius:6px;text-decoration:none;color:#4a5568;font-size:14px;">末页</a>';
        }
        
        btnsEl.innerHTML = html;
    }

    function goToPage(page) {
        state.page = page;
        const p = new URLSearchParams(location.search);
        p.set('page', page);
        history.pushState({}, '', '?' + p.toString());
        navigate();
    }

    function handleSelect(id, type) {
        const p = new URLSearchParams(location.search);
        p.delete('page');
        if (type === 'province') p.set('p', id);
        else if (type === 'city') p.set('c', id);
        else if (type === 'company') p.set('co', id);

        history.pushState({}, '', '?' + p.toString());
        navigate();
    }

    function goBack() {
        const p = new URLSearchParams(location.search);
        p.delete('page');
        if (state.step === 'archive') p.delete('co');
        else if (state.step === 'company') p.delete('c');
        else if (state.step === 'city') p.delete('p');

        history.pushState({}, '', '?' + (p.toString() || ''));
        navigate();
    }

    function updateNav() {
        document.getElementById('backBtn').classList.toggle('hidden', state.step === 'province');
    }

    window.onpopstate = navigate;

    let quickSearchTimeout = null;

    function hlText(text, kw) {
        if (!kw) return text;
        return text.replace(new RegExp('(' + kw.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + ')', 'gi'), '<mark>$1</mark>');
    }

    function handleQuickSearch(keyword) {
        clearTimeout(quickSearchTimeout);
        var wrap = document.getElementById('quickSearchResultWrap');
        if (keyword.trim().length === 0) {
            wrap.classList.remove('quickSearchShow');
            return;
        }
        quickSearchTimeout = setTimeout(function() { performQuickSearch(keyword); }, 300);
    }

    async function performQuickSearch(keyword) {
        var wrap = document.getElementById('quickSearchResultWrap');
        wrap.innerHTML = '<div class="quick-search-loading">搜索中...</div>';
        wrap.classList.add('quickSearchShow');
        try {
            var res = await fetch('/api/regions.php?action=search_all_regions&keyword=' + encodeURIComponent(keyword));
            var json = await res.json();
            if (json.success) displayQuickSearchResults(json.data, keyword);
        } catch(e) {
            wrap.innerHTML = '<div class="quick-search-empty">搜索失败</div>';
        }
    }

    function displayQuickSearchResults(results, keyword) {
        var wrap = document.getElementById('quickSearchResultWrap');
        var html = '';

        var hasResults = (results.provinces && results.provinces.length > 0) ||
                         (results.cities && results.cities.length > 0) ||
                         (results.companies && results.companies.length > 0);

        if (!hasResults) {
            html = '<div class="quick-search-empty">暂无匹配结果</div>';
        } else {
            if (results.provinces && results.provinces.length > 0) {
                html += '<div class="quick-search-section">🗺️ 省份 (' + results.provinces.length + ')</div>';
                results.provinces.forEach(function(item) {
                    html += '<div class="region-item" onclick="searchGoProvince(' + item.id + ')"><span class="icon">🗺️</span><div class="name"><h4>' + hlText(item.name, keyword) + '</h4><p>' + (item.city_count || 0) + ' 个市县 · ' + (item.photo_count || 0) + ' 份档案</p></div><span class="count">›</span></div>';
                });
            }
            if (results.cities && results.cities.length > 0) {
                html += '<div class="quick-search-section">🏙️ 市县 (' + results.cities.length + ')</div>';
                results.cities.forEach(function(item) {
                    html += '<div class="region-item region-item-city" onclick="searchGoCity(' + item.id + ',' + item.province_id + ')"><span class="icon">🏙️</span><div class="name"><h4>' + hlText(item.name, keyword) + '</h4><p>' + (item.path || '') + '</p></div><span class="count">›</span></div>';
                    if (item.companies && item.companies.length > 0) {
                        item.companies.forEach(function(co) {
                            html += '<div class="region-item region-item-company" onclick="searchGoCompany(' + co.id + ')"><span class="icon">🏢</span><div class="name"><h4>' + hlText(co.name, keyword) + '</h4><p>' + (co.address ? '📍 ' + co.address : '') + '</p></div><span class="count">›</span></div>';
                        });
                    }
                });
            }
            if (results.companies && results.companies.length > 0 && (!results.cities || results.cities.length === 0)) {
                html += '<div class="quick-search-section">🏢 公司 (' + results.companies.length + ')</div>';
                results.companies.forEach(function(item) {
                    html += '<div class="region-item" onclick="searchGoCompany(' + item.id + ')"><span class="icon">🏢</span><div class="name"><h4>' + hlText(item.name, keyword) + '</h4><p>' + (item.path || '') + '</p></div><span class="count">›</span></div>';
                });
            }
        }

        wrap.innerHTML = html;
        wrap.classList.add('quickSearchShow');
    }

    function searchGoProvince(id) {
        document.getElementById('quickSearchResultWrap').classList.remove('quickSearchShow');
        document.getElementById('quickSearchInput').value = '';
        history.pushState({}, '', '?p=' + id);
        navigate();
    }

    function searchGoCity(id, pid) {
        document.getElementById('quickSearchResultWrap').classList.remove('quickSearchShow');
        document.getElementById('quickSearchInput').value = '';
        history.pushState({}, '', '?p=' + pid + '&c=' + id);
        navigate();
    }

    function searchGoCompany(id) {
        document.getElementById('quickSearchResultWrap').classList.remove('quickSearchShow');
        document.getElementById('quickSearchInput').value = '';
        history.pushState({}, '', '?co=' + id);
        navigate();
    }

    document.addEventListener('click', function(e) {
        var wrap = document.getElementById('quickSearchResult');
        if (!wrap.contains(e.target)) {
            document.getElementById('quickSearchResultWrap').classList.remove('quickSearchShow');
        }
    });

    navigate();
</script>

</body>
</html>