<?php ?>
    <div class="card hero-section" style="padding: 2.5rem; margin-bottom: 2rem; position: relative; overflow: hidden; border: none; background: linear-gradient(135deg, var(--primary), #818cf8); border-radius: 2rem;">
        <div style="position: absolute; top: -100px; right: -100px; width: 300px; height: 300px; background: rgba(255,255,255,0.1); border-radius: 50%;"></div>
        <div style="position: relative; z-index: 2; display: flex; justify-content: space-between; align-items: center; gap: 1.5rem; flex-wrap: wrap;">
            <div style="flex: 1; min-width: 0;">
                <h1 style="font-size: clamp(2rem, 5vw, 3.5rem); margin-bottom: 0.75rem; color: white; line-height: 1.1; font-weight: 800; letter-spacing: -1.5px;">
                    <?= isset($currentCategory) ? htmlspecialchars($currentCategory['name']) : \App\Helpers\Lang::t('feed') ?>
                </h1>
                <p style="color: rgba(255,255,255,0.9); font-size: 1.15rem; font-weight: 500; max-width: 600px;">
                    <?= isset($currentCategory) ? htmlspecialchars($currentCategory['description']) : \App\Helpers\Lang::t('feed_desc') ?>
                </p>
            </div>
            <div style="display: flex; gap: 1rem; align-items: center;">
                <?php if (\App\Core\Session::get('role') == 3): ?>
                    <button id="admin-mode-btn" class="btn" style="background: rgba(0,0,0,0.2); color: white; border: 1px solid rgba(255,255,255,0.3); border-radius: 2rem; padding: 0.75rem 1.25rem;">
                        <i class="fas fa-magic"></i> <?= \App\Helpers\Lang::t('moderator_mode') ?>
                    </button>
                <?php endif; ?>
                <a href="/post/create" class="btn" style="background: white; color: var(--primary); padding: 1rem 2.5rem; border-radius: 4rem; font-size: 1.1rem; font-weight: 700; box-shadow: 0 10px 25px rgba(0,0,0,0.15);">
                    <i class="fas fa-plus-circle"></i> <?= \App\Helpers\Lang::t('new_topic') ?>
                </a>
            </div>
        </div>
    </div>

    <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 1.5rem;">
        <div id="reorder-save-box" style="display: none; align-items: center; gap: 1rem; background: rgba(16, 185, 129, 0.1); padding: 0.5rem 1rem; border-radius: 1rem; border: 1px solid var(--success); color: var(--success); font-weight: 700;">
            <i class="fas fa-info-circle"></i> <?= \App\Helpers\Lang::t('order_changed') ?>
            <button onclick="saveNewOrder()" class="btn btn-primary" style="padding: 0.4rem 1rem; font-size: 0.8rem;"><?= \App\Helpers\Lang::t('save_changes') ?></button>
        </div>
        <div style="margin-left: auto; display: flex; gap: 0.5rem; background: var(--card); padding: 0.4rem; border-radius: 1rem; border: 1px solid var(--border);">
            <?php $currentSort = $_GET['sort'] ?? 'latest'; ?>
            <a href="?sort=latest" class="btn" style="padding: 0.5rem 1.25rem; font-size: 0.85rem; font-weight: 600; border-radius: 0.75rem; background: <?= $currentSort == 'latest' ? 'var(--primary)' : 'transparent' ?>; color: <?= $currentSort == 'latest' ? 'white' : 'var(--text)' ?>;"><?= \App\Helpers\Lang::t('latest') ?></a>
            <a href="?sort=top" class="btn" style="padding: 0.5rem 1.25rem; font-size: 0.85rem; font-weight: 600; border-radius: 0.75rem; background: <?= $currentSort == 'top' ? 'var(--primary)' : 'transparent' ?>; color: <?= $currentSort == 'top' ? 'white' : 'var(--text)' ?>;"><?= \App\Helpers\Lang::t('top') ?></a>
            <a href="?sort=unsolved" class="btn" style="padding: 0.5rem 1.25rem; font-size: 0.85rem; font-weight: 600; border-radius: 0.75rem; background: <?= $currentSort == 'unsolved' ? 'var(--primary)' : 'transparent' ?>; color: <?= $currentSort == 'unsolved' ? 'white' : 'var(--text)' ?>;"><?= \App\Helpers\Lang::t('unsolved') ?></a>
        </div>
    </div>

    <div class="main-grid">
        <div id="topics-sortable" class="posts-list">
            <?php if (empty($posts)): ?>
                <div class="card" style="text-align: center; padding: 5rem 2rem;">
                    <i class="fas fa-ghost" style="font-size: 4rem; margin-bottom: 1.5rem; color: var(--primary); opacity: 0.2;"></i>
                    <h3><?= \App\Helpers\Lang::t('no_discussions') ?></h3>
                </div>
            <?php else: ?>
                <?php foreach ($posts as $post): ?>
                    <div class="card topic-row draggable-item" data-id="<?= $post['id'] ?>" style="padding: 1.5rem; display: flex; align-items: center; gap: 1.5rem; transition: var(--transition); position: relative;">
                        <!-- Drag Handle (Admin only) -->
                        <div class="drag-handle" style="display: none; cursor: grab; color: var(--text-muted); font-size: 1.25rem;">
                            <i class="fas fa-grip-vertical"></i>
                        </div>

                        <!-- Vote Widget -->
                        <div class="vote-container" style="min-width: 50px; background: rgba(0,0,0,0.03); border-radius: 0.75rem; padding: 0.5rem 0;">
                            <button class="vote-btn" data-post="<?= $post['id'] ?>" data-type="1"><i class="fas fa-caret-up"></i></button>
                            <span class="score-count" style="font-weight: 800; font-size: 1.1rem;"><?= $post['score'] ?? 0 ?></span>
                            <button class="vote-btn" data-post="<?= $post['id'] ?>" data-type="-1"><i class="fas fa-caret-down"></i></button>
                        </div>

                        <!-- Content -->
                        <div style="flex: 1; min-width: 0;">
                            <div style="display: flex; align-items: center; gap: 0.75rem; margin-bottom: 0.5rem; font-size: 0.8rem;">
                                <a href="/c/<?= htmlspecialchars($post['category_slug'] ?? '') ?>" class="badge" style="background: var(--primary-light); color: var(--primary); text-decoration: none;">
                                    <i class="fas fa-folder" style="margin-right: 0.3rem;"></i><?= htmlspecialchars($post['category_name']) ?>
                                </a>
                                <span style="color: var(--text-muted);">•</span>
                                <?php if (($post['sort_order'] ?? 0) >= 9000): ?>
                                    <span class="badge" style="background: #fbbf24; color: #78350f;"><i class="fas fa-thumbtack"></i> <?= \App\Helpers\Lang::t('pinned') ?></span>
                                    <span style="color: var(--text-muted);">•</span>
                                <?php endif; ?>
                                <a href="/u/<?= $post['username'] ?>" style="color: var(--text); font-weight: 700; text-decoration: none;"><?= $post['username'] ?></a>
                                <span style="color: var(--text-muted); opacity: 0.7;"><?= date('H:i', strtotime($post['created_at'])) ?></span>
                            </div>
                            
                            <h2 style="font-size: 1.2rem; margin-bottom: 0.75rem; font-weight: 700; line-height: 1.4;">
                                <a href="/post/<?= $post['slug'] ?>" style="text-decoration: none; color: inherit; display: block;" class="topic-link">
                                    <?= htmlspecialchars($post['title']) ?>
                                </a>
                            </h2>

                            <div style="display: flex; gap: 1.5rem; font-size: 0.85rem; color: var(--text-muted); font-weight: 500;">
                                <span><i class="far fa-comment-alt" style="margin-right: 0.4rem; color: var(--primary);"></i> <?= $post['comment_count'] ?> <?= \App\Helpers\Lang::t('replies') ?></span>
                                <span><i class="far fa-eye" style="margin-right: 0.4rem;"></i> <?= $post['view_count'] ?> <?= \App\Helpers\Lang::t('views') ?></span>
                                <?php if ($post['type'] === 'question'): ?>
                                    <span style="color: <?= $post['is_best_answer_selected'] ? 'var(--success)' : '#eab308' ?>;">
                                        <i class="fas <?= $post['is_best_answer_selected'] ? 'fa-check-circle' : 'fa-question-circle' ?>" style="margin-right: 0.3rem;"></i>
                                        <?= $post['is_best_answer_selected'] ? \App\Helpers\Lang::t('solved') : \App\Helpers\Lang::t('question') ?>
                                    </span>
                                <?php endif; ?>
                            </div>
                        </div>

                        <!-- Moderator Dropdown -->
                        <?php if (\App\Core\Session::get('role') == 3): ?>
                        <div class="mod-dropdown" style="margin-left: auto;">
                            <button class="btn btn-icon" onclick="toggleMod(event, <?= $post['id'] ?>)" style="color: var(--text-muted);"><i class="fas fa-ellipsis-v"></i></button>
                            <div id="mod-menu-<?= $post['id'] ?>" class="card mod-menu-dropdown hidden">
                                <form action="/admin/posts/block/<?= $post['id'] ?>" method="POST"><?= \App\Core\CSRF::field() ?><button type="submit"><i class="fas fa-ban"></i> <?= \App\Helpers\Lang::t('block') ?></button></form>
                                <form action="/admin/posts/delete/<?= $post['id'] ?>" method="POST" onsubmit="return confirm('<?= \App\Helpers\Lang::t('confirm_delete') ?>')"><?= \App\Core\CSRF::field() ?><button type="submit" style="color: #ef4444;"><i class="fas fa-trash"></i> <?= \App\Helpers\Lang::t('delete') ?></button></form>
                            </div>
                        </div>
                        <?php endif; ?>
                    </div>
                <?php endforeach; ?>
            <?php endif; ?>
        </div>

        <aside class="sidebar">
            <div class="card" style="padding: 1.75rem; border-radius: 1.25rem;">
                <h3 style="margin-bottom: 1.5rem; font-size: 1.15rem; display: flex; align-items: center; gap: 0.75rem;">
                    <i class="fas fa-chart-line text-primary"></i> <?= \App\Helpers\Lang::t('stats') ?>
                </h3>
                <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 1.25rem;">
                    <a href="/users" class="forum-stat clickable" style="text-decoration: none; color: inherit;">
                        <span class="count"><?= $stats['members'] ?></span>
                        <span class="label"><?= \App\Helpers\Lang::t('members') ?></span>
                    </a>
                    <div class="forum-stat">
                        <span class="count"><?= $stats['topics'] ?></span>
                        <span class="label"><?= \App\Helpers\Lang::t('topics') ?></span>
                    </div>
                    <div class="forum-stat">
                        <span class="count"><?= $stats['posts'] ?></span>
                        <span class="label"><?= \App\Helpers\Lang::t('posts') ?></span>
                    </div>
                    <div class="forum-stat">
                        <span class="count"><?= $stats['online'] ?></span>
                        <span class="label"><?= \App\Helpers\Lang::t('online') ?></span>
                    </div>
                </div>
            </div>

            <div class="card" style="padding: 1.75rem; border-radius: 1.25rem;">
                <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 1.5rem;">
                    <h3 style="margin: 0; font-size: 1.15rem;"><?= \App\Helpers\Lang::t('categories') ?></h3>
                    <?php if (\App\Core\Session::get('role') == 3): ?>
                        <a href="/admin/categories" title="<?= \App\Helpers\Lang::t('manage_categories') ?>" style="color: var(--primary);"><i class="fas fa-cog"></i></a>
                    <?php endif; ?>
                </div>
                <div style="display: flex; flex-direction: column; gap: 0.75rem;">
                    <?php foreach ($categories as $cat): ?>
                    <a href="/c/<?= $cat['slug'] ?>" class="category-card <?= (isset($currentCategory) && $currentCategory['id'] == $cat['id']) ? 'active' : '' ?>">
                        <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 0.5rem;">
                            <span class="cat-name"><i class="fas fa-<?= $cat['icon'] ?>" style="margin-right: 0.6rem; width: 20px; text-align: center;"></i> <?= $cat['name'] ?></span>
                            <span class="badge" style="background: var(--primary); color: white;"><?= $cat['topic_count'] ?></span>
                        </div>
                        <p class="cat-desc"><?= htmlspecialchars($cat['description']) ?></p>
                    </a>
                    <?php endforeach; ?>
                </div>
            </div>
        </aside>
    </div>

    <!-- Drag and Drop Assets -->
    <script src="https://cdn.jsdelivr.net/npm/sortablejs@1.15.0/Sortable.min.js"></script>
    <style>
        .category-card {
            display: block;
            text-decoration: none;
            padding: 1rem;
            background: var(--bg);
            border: 1px solid var(--border);
            border-radius: 1rem;
            transition: var(--transition);
        }
        .category-card:hover, .category-card.active {
            border-color: var(--primary);
            background: var(--card);
            transform: translateX(5px);
        }
        .category-card .cat-name { font-weight: 700; color: var(--text); }
        .category-card .cat-desc { font-size: 0.8rem; color: var(--text-muted); margin: 0; line-height: 1.4; display: -webkit-box; -webkit-line-clamp: 2; line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; }
        
        .mod-menu-dropdown {
            position: absolute; right: 1.5rem; top: 3.5rem; z-index: 100;
            min-width: 150px; padding: 0.5rem; box-shadow: var(--shadow-lg); border: 1px solid var(--primary-light);
        }
        .mod-menu-dropdown button {
            width: 100%; text-align: left; padding: 0.6rem 1rem; background: transparent; border: none;
            color: var(--text); cursor: pointer; border-radius: 0.5rem; font-weight: 600; display: flex; align-items: center; gap: 0.75rem;
        }
        .mod-menu-dropdown button:hover { background: var(--primary-light); color: var(--primary); }
        
        .draggable-item.ghost { opacity: 0.4; background: var(--primary-light); border: 2px dashed var(--primary); }
        .draggable-item.chosen { box-shadow: 0 20px 40px rgba(0,0,0,0.2); transform: scale(1.02); z-index: 10; }
        
        .forum-stat.clickable { transition: var(--transition); border-radius: 0.75rem; padding: 0.25rem; }
        .forum-stat.clickable:hover { background: var(--primary-light); color: var(--primary) !important; transform: translateY(-2px); }
        .forum-stat.clickable:hover .label { color: var(--primary); }
    </style>

    <script>
    let sortable = null;
    const adminBtn = document.getElementById('admin-mode-btn');
    
    if (adminBtn) {
        adminBtn.addEventListener('click', () => {
            const isEnabled = adminBtn.classList.toggle('active');
            adminBtn.style.background = isEnabled ? 'var(--primary)' : 'rgba(0,0,0,0.2)';
            
            document.querySelectorAll('.drag-handle').forEach(el => el.style.display = isEnabled ? 'block' : 'none');
            
            if (isEnabled) {
                sortable = new Sortable(document.getElementById('topics-sortable'), {
                    animation: 150,
                    handle: '.drag-handle',
                    ghostClass: 'ghost',
                    chosenClass: 'chosen',
                    onEnd: function() {
                        document.getElementById('reorder-save-box').style.display = 'flex';
                    }
                });
            } else if (sortable) {
                sortable.destroy();
                sortable = null;
            }
        });
    }

    function toggleMod(e, id) {
        e.stopPropagation();
        document.querySelectorAll('.mod-menu-dropdown').forEach(el => {
            if (el.id !== 'mod-menu-' + id) el.classList.add('hidden');
        });
        document.getElementById('mod-menu-' + id).classList.toggle('hidden');
    }

    async function saveNewOrder() {
        const items = document.querySelectorAll('.draggable-item');
        const orders = [];
        items.forEach((item, index) => {
            orders.push({
                id: item.dataset.id,
                order: items.length - index // Newer/Hotter at top
            });
        });

        try {
            const response = await fetch('/api/admin/posts/reorder', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                    'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content
                },
                body: 'orders=' + encodeURIComponent(JSON.stringify(orders)) + '&csrf_token=' + document.querySelector('meta[name="csrf-token"]').content
            });
            const res = await response.json();
            if (res.success) {
                window.location.reload();
            }
        } catch (e) {
            alert('Failed to save order');
        }
    }

    document.addEventListener('click', () => {
        document.querySelectorAll('.mod-menu-dropdown').forEach(el => el.classList.add('hidden'));
    });
    </script>
