<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{{ app_name }} - Dashboard</title>

    <!-- Favicon -->
    <link rel="icon" href="/static/FenLiu.png" type="image/png">
    <link rel="apple-touch-icon" href="/static/FenLiu.png">

    <!-- Tailwind CSS -->
    <script src="https://cdn.tailwindcss.com"></script>

    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">

    <style>
        .stat-card {
            transition: transform 0.2s, box-shadow 0.2s;
        }

        .stat-card:hover {
            transform: translateY(-4px);
            box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
        }

        .water-wave {
            position: relative;
            overflow: hidden;
        }

        .water-wave::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: linear-gradient(90deg, transparent, rgba(59, 130, 246, 0.1), transparent);
            animation: wave 3s infinite linear;
        }

        @keyframes wave {
            0% { transform: translateX(-100%); }
            100% { transform: translateX(100%); }
        }

        .post-content {
            line-height: 1.6;
            word-wrap: break-word;
        }

        .post-content a {
            color: #3b82f6;
            text-decoration: underline;
        }

        .post-content a:hover {
            color: #1d4ed8;
        }

        .spam-score-low {
            background-color: #d1fae5;
            color: #065f46;
        }

        .spam-score-medium {
            background-color: #fef3c7;
            color: #92400e;
        }

        .spam-score-high {
            background-color: #fde68a;
            color: #92400e;
        }

        .spam-score-very-high {
            background-color: #fecaca;
            color: #991b1b;
        }
    </style>
</head>
<body class="bg-gray-50 min-h-screen">
    <!-- Navigation -->
    <nav class="bg-gradient-to-r from-blue-600 to-blue-800 text-white shadow-lg">
        <div class="container mx-auto px-4 py-4">
            <div class="flex justify-between items-center">
                <div class="flex items-center space-x-3">
                    <div class="text-3xl">🌊</div>
                    <div>
                        <h1 class="text-2xl font-bold">{{ app_name }}</h1>
                        <p class="text-sm opacity-80">Fediverse Content Filtering</p>
                    </div>
                </div></div>

                <div class="hidden md:flex space-x-6">
                    <a href="/" class="hover:text-blue-200 transition-colors font-bold border-b-2 border-white">
                        <i class="fas fa-home mr-2"></i>Dashboard
                    </a>
                    <a href="/streams" class="hover:text-blue-200 transition-colors">
                        <i class="fas fa-hashtag mr-2"></i>Streams
                    </a>
                    <a href="/posts" class="hover:text-blue-200 transition-colors">
                        <i class="fas fa-stream mr-2"></i>Posts
                    </a>
                    <a href="/stats" class="hover:text-blue-200 transition-colors">
                        <i class="fas fa-chart-bar mr-2"></i>Stats
                    </a>
                </div>

                <!-- Mobile menu button -->
                <button class="md:hidden text-2xl" onclick="toggleMobileMenu()">
                    <i class="fas fa-bars"></i>
                </button>
            </div>

            <!-- Mobile menu -->
            <div id="mobileMenu" class="hidden md:hidden mt-4 space-y-3">
                <a href="/" class="block py-2 hover:text-blue-200 transition-colors font-bold">
                    <i class="fas fa-home mr-2"></i>Dashboard
                </a>
                <a href="/streams" class="block py-2 hover:text-blue-200 transition-colors">
                    <i class="fas fa-hashtag mr-2"></i>Streams
                </a>
                <a href="/posts" class="block py-2 hover:text-blue-200 transition-colors">
                    <i class="fas fa-stream mr-2"></i>Posts
                </a>
                <a href="/stats" class="block py-2 hover:text-blue-200 transition-colors">
                    <i class="fas fa-chart-bar mr-2"></i>Stats
                </a>
            </div>
        </div>
    </nav>

    <!-- Main content -->
    <main class="container mx-auto px-4 py-8">
        <!-- Welcome header -->
        <div class="mb-8 text-center">
            <h2 class="text-3xl font-bold text-gray-800 mb-2">Welcome to {{ app_name }}</h2>
            <p class="text-gray-600 max-w-2xl mx-auto">
                Monitor Fediverse hashtags, filter content, and export quality posts for boosting.
                Inspired by ancient Chinese water management principles.
            </p>
        </div>

        <!-- Statistics cards -->
        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
            <div class="stat-card bg-white rounded-xl shadow-md p-6 water-wave">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-sm text-gray-500 uppercase tracking-wider">Total Streams</p>
                        <p class="text-3xl font-bold text-blue-600 mt-2">{{ total_streams }}</p>
                    </div>
                    <div class="text-blue-500 text-3xl">
                        <i class="fas fa-hashtag"></i>
                    </div>
                </div>
                <div class="mt-4">
                    <p class="text-sm text-gray-600">
                        <span class="font-semibold text-green-600">{{ active_streams }}</span> active streams
                    </p>
                </div>
            </div>

            <div class="stat-card bg-white rounded-xl shadow-md p-6">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-sm text-gray-500 uppercase tracking-wider">Total Posts</p>
                        <p class="text-3xl font-bold text-green-600 mt-2">{{ total_posts }}</p>
                    </div>
                    <div class="text-green-500 text-3xl">
                        <i class="fas fa-stream"></i>
                    </div>
                </div>
                <div class="mt-4">
                    <p class="text-sm text-gray-600">
                        <span class="font-semibold text-blue-600">{{ processed_posts }}</span> processed
                    </p>
                </div>
            </div>

            <div class="stat-card bg-white rounded-xl shadow-md p-6">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-sm text-gray-500 uppercase tracking-wider">Active Streams</p>
                        <p class="text-3xl font-bold text-purple-600 mt-2">{{ active_streams }}</p>
                    </div>
                    <div class="text-purple-500 text-3xl">
                        <i class="fas fa-satellite-dish"></i>
                    </div>
                </div>
                <div class="mt-4">
                    <p class="text-sm text-gray-600">
                        Monitoring hashtags in real-time
                    </p>
                </div>
            </div>

            <div class="stat-card bg-white rounded-xl shadow-md p-6">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-sm text-gray-500 uppercase tracking-wider">Version</p>
                        <p class="text-3xl font-bold text-gray-600 mt-2">{{ app_version }}</p>
                    </div>
                    <div class="text-gray-500 text-3xl">
                        <i class="fas fa-code-branch"></i>
                    </div>
                </div>
                <div class="mt-4">
                    <p class="text-sm text-gray-600">
                        Phase 1: Monitoring
                    </p>
                </div>
            </div>
        </div>

        <!-- Two column layout -->
        <div class="grid grid-cols-1 lg:grid-cols-2 gap-8">
            <!-- Recent Posts -->
            <div class="bg-white rounded-xl shadow-md overflow-hidden">
                <div class="px-6 py-4 border-b border-gray-200">
                    <h3 class="text-lg font-semibold text-gray-800 flex items-center">
                        <i class="fas fa-clock mr-2 text-blue-500"></i>
                        Recent Posts
                    </h3>
                </div>

                <div class="divide-y divide-gray-100">
                    {% if recent_posts %}
                        {% for post in recent_posts %}
                        <div class="p-6 hover:bg-gray-50 transition-colors">
                            <div class="flex justify-between items-start mb-3">
                                <div>
                                    <h4 class="font-medium text-gray-800">
                                        {% if post.author_display_name %}
                                            {{ post.author_display_name }}
                                        {% else %}
                                            {{ post.author_username }}
                                        {% endif %}
                                    </h4>
                                    <p class="text-sm text-gray-500">
                                        @{{ post.author_username }} •
                                        <span data-time="{{ post.created_at.isoformat() if post.created_at else post.fetched_at.isoformat() }}">
                                            {{ post.created_at.strftime('%Y-%m-%d %H:%M') if post.created_at else post.fetched_at.strftime('%Y-%m-%d %H:%M') }}
                                        </span>
                                    </p>
                                </div>
                                <div class="flex space-x-2">
                                    {% if post.processed %}
                                    <span class="px-2 py-1 text-xs rounded-full {{ 'spam-score-low' if post.spam_score < 30 else 'spam-score-medium' if post.spam_score < 70 else 'spam-score-high' if post.spam_score < 90 else 'spam-score-very-high' }}">
                                        Score: {{ post.spam_score }}
                                    </span>
                                    {% else %}
                                    <span class="px-2 py-1 text-xs rounded-full bg-gray-100 text-gray-800">
                                        Unprocessed
                                    </span>
                                    {% endif %}
                                </div>
                            </div>

                            <div class="post-content text-gray-700 mb-4">
                                {{ post.content[:200] }}{% if post.content|length > 200 %}...{% endif %}
                            </div>

                            <div class="flex justify-between items-center text-sm text-gray-500">
                                <div class="flex space-x-4">
                                    <span class="flex items-center">
                                        <i class="fas fa-retweet mr-1"></i>
                                        {{ post.boosts }}
                                    </span>
                                    <span class="flex items-center">
                                        <i class="fas fa-heart mr-1"></i>
                                        {{ post.likes }}
                                    </span>
                                    <span class="flex items-center">
                                        <i class="fas fa-reply mr-1"></i>
                                        {{ post.replies }}
                                    </span>
                                </div>
                                <a href="/posts/{{ post.id }}" class="text-blue-600 hover:text-blue-800 font-medium">
                                    View Details →
                                </a>
                            </div>
                        </div>
                        {% endfor %}
                    {% else %}
                        <div class="p-8 text-center text-gray-500">
                            <i class="fas fa-inbox text-4xl mb-4 opacity-50"></i>
                            <p class="text-lg">No posts yet</p>
                            <p class="text-sm mt-2">Start monitoring hashtags to see posts here</p>
                        </div>
                    {% endif %}
                </div>

                <div class="px-6 py-4 border-t border-gray-200 bg-gray-50">
                    <a href="/posts" class="text-blue-600 hover:text-blue-800 font-medium flex items-center justify-center">
                        <i class="fas fa-stream mr-2"></i>
                        View All Posts
                    </a>
                </div>
            </div>

            <!-- Active Streams -->
            <div class="bg-white rounded-xl shadow-md overflow-hidden">
                <div class="px-6 py-4 border-b border-gray-200">
                    <h3 class="text-lg font-semibold text-gray-800 flex items-center">
                        <i class="fas fa-satellite-dish mr-2 text-green-500"></i>
                        Active Streams
                    </h3>
                </div>

                <div class="divide-y divide-gray-100">
                    {% if active_streams_list %}
                        {% for stream in active_streams_list %}
                        <div class="p-6 hover:bg-gray-50 transition-colors">
                            <div class="flex justify-between items-center mb-3">
                                <div>
                                    <h4 class="font-medium text-gray-800 flex items-center">
                                        <i class="fas fa-hashtag text-blue-500 mr-2"></i>
                                        #{{ stream.hashtag }}
                                    </h4>
                                    <p class="text-sm text-gray-500">
                                        {{ stream.instance }}
                                        {% if stream.last_check %}
                                            • Last checked: <span data-time="{{ stream.last_check.isoformat() }}">{{ stream.last_check.strftime('%Y-%m-%d %H:%M') }}</span>
                                        {% endif %}
                                    </p>
                                </div>
                                <span class="px-3 py-1 text-xs rounded-full bg-green-100 text-green-800 font-medium">
                                    Active
                                </span>
                            </div>

                            <div class="flex justify-between items-center mt-4">
                                <div class="text-sm text-gray-600">
                                    <i class="fas fa-database mr-1"></i>
                                    {{ stream.posts|length if stream.posts else 0 }} posts
                                </div>
                                <div class="flex space-x-2">
                                    <button
                                        class="px-3 py-1 text-sm bg-blue-100 text-blue-700 rounded hover:bg-blue-200 transition-colors"
                                        onclick="fetchStream({{ stream.id }})"
                                    >
                                        <i class="fas fa-sync-alt mr-1"></i>
                                        Fetch
                                    </button>
                                    <a
                                        href="/streams#stream-{{ stream.id }}"
                                        class="px-3 py-1 text-sm bg-gray-100 text-gray-700 rounded hover:bg-gray-200 transition-colors"
                                    >
                                        <i class="fas fa-cog mr-1"></i>
                                        Manage
                                    </a>
                                </div>
                            </div>
                        </div>
                        {% endfor %}
                    {% else %}
                        <div class="p-8 text-center text-gray-500">
                            <i class="fas fa-hashtag text-4xl mb-4 opacity-50"></i>
                            <p class="text-lg">No active streams</p>
                            <p class="text-sm mt-2">Add hashtags to start monitoring</p>
                        </div>
                    {% endif %}
                </div>

                <div class="px-6 py-4 border-t border-gray-200 bg-gray-50">
                    <div class="flex justify-between items-center">
                        <a href="/streams" class="text-blue-600 hover:text-blue-800 font-medium flex items-center">
                            <i class="fas fa-hashtag mr-2"></i>
                            Manage Streams
                        </a>
                        <button
                            onclick="addNewStream()"
                            class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors flex items-center"
                        >
                            <i class="fas fa-plus mr-2"></i>
                            Add Stream
                        </button>
                    </div>
                </div>
            </div>
        </div>

        <!-- Quick Actions -->
        <div class="mt-8 bg-gradient-to-r from-blue-50 to-indigo-50 rounded-xl shadow-md p-6">
            <h3 class="text-lg font-semibold text-gray-800 mb-4 flex items-center">
                <i class="fas fa-bolt mr-2 text-yellow-500"></i>
                Quick Actions
            </h3>

            <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                <button
                    onclick="addNewStream()"
                    class="bg-white rounded-lg p-4 shadow-sm hover:shadow-md transition-shadow text-left group"
                >
                    <div class="flex items-center mb-2">
                        <div class="w-10 h-10 rounded-full bg-blue-100 flex items-center justify-center mr-3 group-hover:bg-blue-200 transition-colors">
                            <i class="fas fa-hashtag text-blue-600"></i>
                        </div>
                        <h4 class="font-medium text-gray-800">Add Hashtag</h4>
                    </div>
                    <p class="text-sm text-gray-600">Start monitoring a new hashtag</p>
                </button>

                <a
                    href="/posts"
                    class="bg-white rounded-lg p-4 shadow-sm hover:shadow-md transition-shadow text-left group block"
                >
                    <div class="flex items-center mb-2">
                        <div class="w-10 h-10 rounded-full bg-green-100 flex items-center justify-center mr-3 group-hover:bg-green-200 transition-colors">
                            <i class="fas fa-stream text-green-600"></i>
                        </div>
                        <h4 class="font-medium text-gray-800">Review Posts</h4>
                    </div>
                    <p class="text-sm text-gray-600">Process and score recent posts</p>
                </a>

                <a
                    href="/stats"
                    class="bg-white rounded-lg p-4 shadow-sm hover:shadow-md transition-shadow text-left group block"
                >
                    <div class="flex items-center mb-2">
                        <div class="w-10 h-10 rounded-full bg-purple-100 flex items-center justify-center mr-3 group-hover:bg-purple-200 transition-colors">
                            <i class="fas fa-chart-bar text-purple-600"></i>
                        </div>
                        <h4 class="font-medium text-gray-800">View Stats</h4>
                    </div>
                    <p class="text-sm text-gray-600">See analytics and metrics</p>
                </a>
            </div>
        </div>
    </main>

    <!-- Footer -->
    <footer class="bg-gray-800 text-white py-8 mt-12">
        <div class="container mx-auto px-4">
            <div class="flex flex-col md:flex-row justify-between items-center">
                <div class="mb-4 md:mb-0">
                    <div class="flex items-center space-x-2">
                        <div class="text-2xl">🌊</div>
                        <div>
                            <h2 class="text-xl font-bold">{{ app_name }}</h2>
                            <p class="text-sm opacity-80">分流 - Divide the Flow</p>
                        </div>
                    </div>
                    <p class="mt-2 text-sm opacity-80 max-w-md">
                        Applying ancient Chinese water management principles to modern Fediverse content streams.
                        Inspired by the Dujiangyan irrigation system (256 BC).
                    </p>
                </div>

                <div class="text-center md:text-right">
                    <p class="text-sm opacity-80">
                        Version {{ app_version }}
                    </p>
                    <p class="text-sm opacity-80 mt-1">
                        &copy; 2024 {{ app_name }} Project. AGPL-3.0 License.
                    </p>
                </div>
            </div>
        </div>
    </footer>

    <!-- JavaScript -->
    <script>
        function toggleMobileMenu() {
            const menu = document.getElementById('mobileMenu');
            menu.classList.toggle('hidden');
        }

        function fetchStream(streamId) {
            fetch(`/api/v1/hashtags/${streamId}/fetch`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert(`Fetched ${data.posts_fetched} posts for #${data.hashtag}`);
                    location.reload();
                } else {
                    alert(`Error: ${data.error_message || 'Failed to fetch posts'}`);
                }
            })
            .catch(error => {
                alert(`Error: ${error.message}`);
            });
        }

        function addNewStream() {
            const hashtag = prompt('Enter hashtag (without #):');
            if (hashtag) {
                const instance = prompt('Enter instance (e.g., mastodon.social):', 'mastodon.social');
                if (instance) {
                    fetch('/api/v1/hashtags', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                        },
                        body: JSON.stringify({
                            hashtag: hashtag,
                            instance: instance,
                            active: true
                        }),
                    })
                    .then(response => response.json())
                    .then(data => {
                        if (data.id) {
                            alert(`Added #${hashtag} on ${instance}`);
                            window.location.href = '/streams';
                        } else {
                            alert(`Error: ${data.detail || 'Failed to add stream'}`);
                        }
                    })
                    .catch(error => {
                        alert(`Error: ${error.message}`);
                    });
                }
            }
        }

        // Format relative time
        function formatRelativeTime(dateString) {
            const date = new Date(dateString);
            const now = new Date();
            const diffMs = now - date;
            const diffSec = Math.floor(diffMs / 1000);
            const diffMin = Math.floor(diffSec / 60);
            const diffHour = Math.floor(diffMin / 60);
            const diffDay = Math.floor(diffHour / 24);

            if (diffSec < 60) {
                return 'just now';
            } else if (diffMin < 60) {
                return `${diffMin} minute${diffMin !== 1 ? 's' : ''} ago`;
            } else if (diffHour < 24) {
                return `${diffHour} hour${diffHour !== 1 ? 's' : ''} ago`;
            } else if (diffDay < 7) {
                return `${diffDay} day${diffDay !== 1 ? 's' : ''} ago`;
            } else {
                return date.toLocaleDateString();
            }
        }

        // Apply relative time formatting
        document.addEventListener('DOMContentLoaded', function() {
            const timeElements = document.querySelectorAll('[data-time]');
            timeElements.forEach(function(element) {
                const timeString = element.getAttribute('data-time');
                if (timeString) {
                    element.textContent = formatRelativeTime(timeString);
                    element.title = new Date(timeString).toLocaleString();
                }
            });
        });
    </script>
</body>
</html>
