<!DOCTYPE html>
<html lang="en" data-theme="light">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Workflow Dashboard - Task Board</title>
    <!-- Google Fonts: Inter -->
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
    <!-- Tailwind CSS CDN -->
    <script src="https://cdn.tailwindcss.com"></script>
    <script>
        tailwind.config = {
            darkMode: ['class', '[data-theme="dark"]'],
            safelist: [
                'bg-card', 'bg-background', 'bg-hover', 'bg-accent', 'bg-muted', 'bg-primary', 'bg-success', 'bg-warning',
                'bg-success-light', 'bg-warning-light', 'text-foreground', 'text-muted-foreground', 'text-primary',
                'text-success', 'text-warning', 'text-primary-foreground', 'border', 'border-border', 'border-primary',
                'border-l-success', 'border-l-warning', 'border-l-muted-foreground', 'rounded', 'rounded-lg', 'rounded-full',
                'shadow', 'shadow-sm', 'shadow-md', 'p-2', 'p-3', 'p-4', 'p-5', 'px-3', 'px-4', 'py-2', 'py-3',
                'mb-2', 'mb-3', 'mb-4', 'mt-2', 'mt-4', 'mx-auto', 'gap-2', 'gap-3', 'gap-4', 'space-y-2',
                'flex', 'flex-1', 'flex-col', 'flex-wrap', 'items-center', 'items-start', 'justify-between', 'justify-center',
                'grid', 'w-full', 'w-5', 'h-2', 'h-5', 'text-xs', 'text-sm', 'text-lg', 'text-xl', 'text-2xl', 'text-3xl',
                'font-medium', 'font-semibold', 'font-bold', 'font-mono', 'truncate', 'uppercase',
                'hover:shadow-md', 'hover:bg-hover', 'hover:-translate-y-1', 'hover:text-foreground', 'hover:opacity-90',
                'hover:scale-110', 'transition-all', 'duration-200', 'duration-300', 'cursor-pointer',
                'opacity-50', 'hidden', 'block', 'relative', 'absolute', 'fixed', 'z-50', 'overflow-hidden',
                'col-span-full', 'text-center', 'min-h-screen', 'max-w-7xl',
            ],
            theme: {
                extend: {
                    colors: {
                        background: 'hsl(var(--background))',
                        foreground: 'hsl(var(--foreground))',
                        card: 'hsl(var(--card))',
                        'card-foreground': 'hsl(var(--card-foreground))',
                        border: 'hsl(var(--border))',
                        primary: 'hsl(var(--primary))',
                        'primary-foreground': 'hsl(var(--primary-foreground))',
                        accent: 'hsl(var(--accent))',
                        'accent-foreground': 'hsl(var(--accent-foreground))',
                        muted: 'hsl(var(--muted))',
                        'muted-foreground': 'hsl(var(--muted-foreground))',
                        hover: 'hsl(var(--hover))',
                        success: 'hsl(var(--success))',
                        'success-light': 'hsl(var(--success-light))',
                        warning: 'hsl(var(--warning))',
                        'warning-light': 'hsl(var(--warning-light))',
                    },
                    fontFamily: {
                        sans: ['Inter', 'system-ui', '-apple-system', 'sans-serif'],
                    },
                },
            },
        }
    </script>
    <style>
        /* CSS Custom Properties - Light Mode */
        :root {
            --background: 0 0% 98%;
            --foreground: 0 0% 13%;
            --card: 0 0% 100%;
            --card-foreground: 0 0% 13%;
            --border: 0 0% 90%;
            --primary: 220 65% 50%;
            --primary-foreground: 0 0% 100%;
            --accent: 220 40% 95%;
            --accent-foreground: 0 0% 13%;
            --muted: 0 0% 96%;
            --muted-foreground: 0 0% 45%;
            --hover: 0 0% 93%;
            --success: 142 71% 45%;
            --success-light: 142 76% 90%;
            --warning: 38 92% 50%;
            --warning-light: 48 96% 89%;
        }

        /* Dark Mode */
        [data-theme="dark"] {
            --background: 220 13% 10%;
            --foreground: 0 0% 90%;
            --card: 220 13% 14%;
            --card-foreground: 0 0% 90%;
            --border: 220 13% 20%;
            --primary: 220 65% 55%;
            --primary-foreground: 0 0% 100%;
            --accent: 220 30% 20%;
            --accent-foreground: 0 0% 90%;
            --muted: 220 13% 18%;
            --muted-foreground: 0 0% 55%;
            --hover: 220 13% 22%;
            --success: 142 71% 40%;
            --success-light: 142 50% 20%;
            --warning: 38 85% 45%;
            --warning-light: 40 50% 20%;
        }

        /* Progress bar gradient */
        .progress-fill {
            background: linear-gradient(90deg, hsl(var(--primary)), hsl(var(--success)));
        }

        /* Task checkbox pseudo-elements */
        .task-checkbox.completed::after { content: '✓'; }
        .task-checkbox.in_progress::after { content: '⟳'; }
    </style>
</head>
<body class="font-sans bg-background text-foreground leading-normal min-h-screen">
    <div class="max-w-7xl mx-auto px-5 py-5">
        <!-- Header -->
        <header class="bg-card shadow rounded-lg p-5 mb-7 border border-border">
            <h1 class="text-2xl font-bold text-primary mb-2">🚀 Workflow Dashboard</h1>
            <p class="text-muted-foreground">Task Board - Active and Archived Sessions</p>

            <div class="flex flex-wrap gap-4 items-center mt-4">
                <!-- Search Box -->
                <div class="flex-1 min-w-[250px] relative">
                    <input type="text" id="searchInput" placeholder="🔍 Search tasks or sessions..."
                        class="w-full px-4 py-2.5 border border-border rounded-lg bg-background text-foreground text-sm focus:outline-none focus:border-primary focus:ring-2 focus:ring-primary/20 transition-all" />
                </div>

                <!-- Filter Buttons -->
                <div class="flex gap-2 flex-wrap">
                    <button class="btn px-5 py-2.5 border border-border rounded-lg text-sm font-medium bg-primary text-primary-foreground hover:opacity-90 transition-all" data-filter="all">All</button>
                    <button class="btn px-5 py-2.5 border border-border rounded-lg text-sm font-medium bg-card text-foreground hover:bg-hover transition-all" data-filter="active">Active</button>
                    <button class="btn px-5 py-2.5 border border-border rounded-lg text-sm font-medium bg-card text-foreground hover:bg-hover transition-all" data-filter="archived">Archived</button>
                </div>
            </div>
        </header>

        <!-- Stats Grid -->
        <div class="grid grid-cols-[repeat(auto-fit,minmax(200px,1fr))] gap-5 mb-7">
            <div class="bg-card p-5 rounded-lg border border-border shadow-sm hover:shadow-md hover:-translate-y-0.5 transition-all duration-200">
                <div class="text-3xl font-bold text-primary" id="totalSessions">0</div>
                <div class="text-sm text-muted-foreground mt-1">Total Sessions</div>
            </div>
            <div class="bg-card p-5 rounded-lg border border-border shadow-sm hover:shadow-md hover:-translate-y-0.5 transition-all duration-200">
                <div class="text-3xl font-bold text-primary" id="activeSessionsCount">0</div>
                <div class="text-sm text-muted-foreground mt-1">Active Sessions</div>
            </div>
            <div class="bg-card p-5 rounded-lg border border-border shadow-sm hover:shadow-md hover:-translate-y-0.5 transition-all duration-200">
                <div class="text-3xl font-bold text-primary" id="totalTasks">0</div>
                <div class="text-sm text-muted-foreground mt-1">Total Tasks</div>
            </div>
            <div class="bg-card p-5 rounded-lg border border-border shadow-sm hover:shadow-md hover:-translate-y-0.5 transition-all duration-200">
                <div class="text-3xl font-bold text-primary" id="completedTasks">0</div>
                <div class="text-sm text-muted-foreground mt-1">Completed Tasks</div>
            </div>
        </div>

        <!-- Active Sessions Section -->
        <div class="mb-10" id="activeSectionContainer">
            <div class="flex justify-between items-center mb-5">
                <h2 class="text-xl font-semibold text-foreground">📋 Active Sessions</h2>
            </div>
            <div class="grid grid-cols-[repeat(auto-fill,minmax(350px,1fr))] gap-5" id="activeSessionsGrid"></div>
        </div>

        <!-- Archived Sessions Section -->
        <div class="mb-10" id="archivedSectionContainer">
            <div class="flex justify-between items-center mb-5">
                <h2 class="text-xl font-semibold text-foreground">📦 Archived Sessions</h2>
            </div>
            <div class="grid grid-cols-[repeat(auto-fill,minmax(350px,1fr))] gap-5" id="archivedSessionsGrid"></div>
        </div>
    </div>

    <!-- Theme Toggle Button -->
    <button class="fixed bottom-7 right-7 w-14 h-14 rounded-full bg-primary text-primary-foreground text-2xl shadow-lg hover:scale-110 transition-all duration-200 z-50" id="themeToggle">🌙</button>

    <!-- Workflow data injected by dashboard-generator -->
    <script id="workflow-data" type="application/json">{{WORKFLOW_DATA}}</script>

    <script>
        // Parse workflow data from JSON script tag, with fallback for direct file access
        let workflowData;
        try {
            const dataScript = document.getElementById('workflow-data');
            const rawData = dataScript ? dataScript.textContent.trim() : '';
            // Check if placeholder was replaced (doesn't start with '{{')
            if (rawData && !rawData.startsWith('{{')) {
                workflowData = JSON.parse(rawData);
            } else {
                throw new Error('Data not injected');
            }
        } catch (e) {
            console.warn('Workflow data not injected, using empty defaults');
            workflowData = { activeSessions: [], archivedSessions: [] };
        }

        // Theme management
        function initTheme() {
            const savedTheme = localStorage.getItem('theme') || 'light';
            document.documentElement.setAttribute('data-theme', savedTheme);
            updateThemeIcon(savedTheme);
        }

        function toggleTheme() {
            const currentTheme = document.documentElement.getAttribute('data-theme');
            const newTheme = currentTheme === 'dark' ? 'light' : 'dark';
            document.documentElement.setAttribute('data-theme', newTheme);
            localStorage.setItem('theme', newTheme);
            updateThemeIcon(newTheme);
        }

        function updateThemeIcon(theme) {
            document.getElementById('themeToggle').textContent = theme === 'dark' ? '☀️' : '🌙';
        }

        // Statistics calculation
        function updateStatistics() {
            const stats = {
                totalSessions: workflowData.activeSessions.length + workflowData.archivedSessions.length,
                activeSessions: workflowData.activeSessions.length,
                totalTasks: 0,
                completedTasks: 0
            };

            workflowData.activeSessions.forEach(session => {
                stats.totalTasks += session.tasks.length;
                stats.completedTasks += session.tasks.filter(t => t.status === 'completed').length;
            });

            workflowData.archivedSessions.forEach(session => {
                stats.totalTasks += session.taskCount || 0;
                stats.completedTasks += session.taskCount || 0;
            });

            document.getElementById('totalSessions').textContent = stats.totalSessions;
            document.getElementById('activeSessionsCount').textContent = stats.activeSessions;
            document.getElementById('totalTasks').textContent = stats.totalTasks;
            document.getElementById('completedTasks').textContent = stats.completedTasks;
        }

        // Render session card with Tailwind classes
        function createSessionCard(session, isActive) {
            const card = document.createElement('div');
            card.className = 'bg-card rounded-lg border border-border shadow-sm p-5 transition-all duration-300 hover:-translate-y-1 hover:shadow-md';
            card.dataset.sessionType = isActive ? 'active' : 'archived';

            const completedTasks = isActive
                ? session.tasks.filter(t => t.status === 'completed').length
                : (session.taskCount || 0);
            const totalTasks = isActive ? session.tasks.length : (session.taskCount || 0);
            const progress = totalTasks > 0 ? (completedTasks / totalTasks * 100) : 0;

            let tasksHtml = '';
            if (isActive && session.tasks.length > 0) {
                tasksHtml = `
                    <div class="mt-4 space-y-2">
                        ${session.tasks.map(task => {
                            const statusClasses = {
                                completed: 'border-l-success bg-success-light/30',
                                in_progress: 'border-l-warning bg-warning-light/30',
                                pending: 'border-l-muted-foreground bg-muted/30'
                            };
                            const checkboxClasses = {
                                completed: 'bg-success border-success text-white',
                                in_progress: 'border-warning text-warning',
                                pending: 'border-border'
                            };
                            return `
                                <div class="flex items-center gap-3 p-2.5 rounded border-l-[3px] ${statusClasses[task.status] || statusClasses.pending}">
                                    <div class="task-checkbox w-5 h-5 rounded-full border-2 flex items-center justify-center text-xs font-bold flex-shrink-0 ${checkboxClasses[task.status] || checkboxClasses.pending} ${task.status}"></div>
                                    <div class="flex-1 text-sm text-foreground">${task.title || 'Untitled Task'}</div>
                                    <span class="text-xs font-mono text-muted-foreground">${task.task_id || ''}</span>
                                </div>
                            `;
                        }).join('')}
                    </div>
                `;
            }

            const statusBadgeClass = isActive
                ? 'bg-success-light text-success'
                : 'bg-hover text-muted-foreground';

            card.innerHTML = `
                <div class="flex justify-between items-start mb-4">
                    <div>
                        <h3 class="text-lg font-semibold text-foreground">${session.session_id || 'Unknown Session'}</h3>
                        <div class="text-sm text-muted-foreground mt-1">${session.project || ''}</div>
                    </div>
                    <span class="px-3 py-1 text-xs font-semibold uppercase rounded-full ${statusBadgeClass}">
                        ${isActive ? 'Active' : 'Archived'}
                    </span>
                </div>

                <div class="flex gap-4 text-sm text-muted-foreground mb-3">
                    <span>📅 ${session.created_at || session.archived_at || 'N/A'}</span>
                    <span>📊 ${completedTasks}/${totalTasks} tasks</span>
                </div>

                ${totalTasks > 0 ? `
                    <div class="h-2 bg-hover rounded overflow-hidden my-4">
                        <div class="progress-fill h-full rounded transition-all duration-300" style="width: ${progress}%"></div>
                    </div>
                    <div class="text-center text-sm text-muted-foreground">${Math.round(progress)}% Complete</div>
                ` : ''}

                ${tasksHtml}

                ${!isActive && session.archive_path ? `
                    <div class="mt-4 pt-4 border-t border-border text-sm text-muted-foreground">
                        📁 Archive: ${session.archive_path}
                    </div>
                ` : ''}
            `;

            return card;
        }

        // Render all sessions
        function renderSessions(filter = 'all') {
            const activeContainer = document.getElementById('activeSessionsGrid');
            const archivedContainer = document.getElementById('archivedSessionsGrid');

            activeContainer.innerHTML = '';
            archivedContainer.innerHTML = '';

            if (filter === 'all' || filter === 'active') {
                if (workflowData.activeSessions.length === 0) {
                    activeContainer.innerHTML = `
                        <div class="text-center py-16 text-muted-foreground col-span-full">
                            <div class="text-5xl mb-4 opacity-50">📭</div>
                            <p>No active sessions</p>
                        </div>
                    `;
                } else {
                    workflowData.activeSessions.forEach(session => {
                        activeContainer.appendChild(createSessionCard(session, true));
                    });
                }
            }

            if (filter === 'all' || filter === 'archived') {
                if (workflowData.archivedSessions.length === 0) {
                    archivedContainer.innerHTML = `
                        <div class="text-center py-16 text-muted-foreground col-span-full">
                            <div class="text-5xl mb-4 opacity-50">📦</div>
                            <p>No archived sessions</p>
                        </div>
                    `;
                } else {
                    workflowData.archivedSessions.forEach(session => {
                        archivedContainer.appendChild(createSessionCard(session, false));
                    });
                }
            }

            // Show/hide sections
            document.getElementById('activeSectionContainer').style.display =
                (filter === 'all' || filter === 'active') ? 'block' : 'none';
            document.getElementById('archivedSectionContainer').style.display =
                (filter === 'all' || filter === 'archived') ? 'block' : 'none';
        }

        // Search functionality
        function setupSearch() {
            const searchInput = document.getElementById('searchInput');
            searchInput.addEventListener('input', (e) => {
                const query = e.target.value.toLowerCase();
                const cards = document.querySelectorAll('[data-session-type]');

                cards.forEach(card => {
                    const text = card.textContent.toLowerCase();
                    card.style.display = text.includes(query) ? 'block' : 'none';
                });
            });
        }

        // Filter functionality
        function setupFilters() {
            const filterButtons = document.querySelectorAll('[data-filter]');
            filterButtons.forEach(btn => {
                btn.addEventListener('click', () => {
                    filterButtons.forEach(b => {
                        b.classList.remove('bg-primary', 'text-primary-foreground');
                        b.classList.add('bg-card', 'text-foreground');
                    });
                    btn.classList.remove('bg-card', 'text-foreground');
                    btn.classList.add('bg-primary', 'text-primary-foreground');
                    renderSessions(btn.dataset.filter);
                });
            });
        }

        // Initialize
        document.addEventListener('DOMContentLoaded', () => {
            initTheme();
            updateStatistics();
            renderSessions();
            setupSearch();
            setupFilters();

            document.getElementById('themeToggle').addEventListener('click', toggleTheme);
        });
    </script>
</body>
</html>
