<!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>Code Review Dashboard - {{SESSION_ID}}</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', 'bg-red-100', 'bg-orange-100', 'bg-blue-100', 'bg-gray-100',
                'text-foreground', 'text-muted-foreground', 'text-primary', 'text-success', 'text-warning',
                'text-red-700', 'text-orange-700', 'text-blue-700', 'text-gray-700', 'text-primary-foreground',
                'border', 'border-border', 'border-l-4', 'rounded', 'rounded-lg', 'rounded-full',
                'shadow', 'shadow-sm', 'shadow-md', 'p-2', 'p-3', 'p-4', 'p-5', 'px-3', 'px-4', 'py-2',
                'mb-2', 'mb-4', 'mt-4', 'gap-2', 'gap-4', 'space-y-2', 'space-y-4',
                'flex', 'flex-1', 'flex-col', 'flex-wrap', 'items-center', 'justify-between', 'justify-center',
                'grid', 'w-full', 'text-xs', 'text-sm', 'text-lg', 'text-xl', 'text-2xl',
                'font-medium', 'font-semibold', 'font-bold', 'font-mono', 'truncate',
                'hover:shadow-md', 'hover:bg-hover', 'transition-all', 'duration-200', 'cursor-pointer',
                'hidden', 'block', 'relative', 'fixed', 'z-50', 'overflow-hidden', 'min-h-screen', 'max-w-6xl', 'mx-auto',
            ],
            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))',
                        input: 'hsl(var(--input))',
                        ring: 'hsl(var(--ring))',
                        primary: 'hsl(var(--primary))',
                        'primary-foreground': 'hsl(var(--primary-foreground))',
                        secondary: 'hsl(var(--secondary))',
                        'secondary-foreground': 'hsl(var(--secondary-foreground))',
                        accent: 'hsl(var(--accent))',
                        'accent-foreground': 'hsl(var(--accent-foreground))',
                        destructive: 'hsl(var(--destructive))',
                        'destructive-foreground': 'hsl(var(--destructive-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'],
                        mono: ['Consolas', 'Monaco', 'Courier New', 'monospace'],
                    },
                    boxShadow: {
                        'sm': '0 1px 2px 0 rgb(0 0 0 / 0.05)',
                        'DEFAULT': '0 2px 8px rgb(0 0 0 / 0.08)',
                        'md': '0 4px 12px rgb(0 0 0 / 0.1)',
                        'lg': '0 8px 24px rgb(0 0 0 / 0.12)',
                    },
                },
            },
        }
    </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%;
            --input: 0 0% 90%;
            --ring: 220 65% 50%;
            --primary: 220 65% 50%;
            --primary-foreground: 0 0% 100%;
            --secondary: 220 60% 65%;
            --secondary-foreground: 0 0% 100%;
            --accent: 220 40% 95%;
            --accent-foreground: 0 0% 13%;
            --destructive: 8 75% 55%;
            --destructive-foreground: 0 0% 100%;
            --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%;
            --input: 220 13% 20%;
            --ring: 220 65% 55%;
            --primary: 220 65% 55%;
            --primary-foreground: 0 0% 100%;
            --secondary: 220 60% 60%;
            --secondary-foreground: 0 0% 100%;
            --accent: 220 30% 20%;
            --accent-foreground: 0 0% 90%;
            --destructive: 8 70% 50%;
            --destructive-foreground: 0 0% 100%;
            --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%;
        }

        /* Scrollbar styling */
        ::-webkit-scrollbar { width: 6px; height: 6px; }
        ::-webkit-scrollbar-track { background: transparent; }
        ::-webkit-scrollbar-thumb { background: hsl(var(--border)); border-radius: 3px; }
        ::-webkit-scrollbar-thumb:hover { background: hsl(var(--muted-foreground)); }

        /* Animations */
        @keyframes pulse {
            0%, 100% { opacity: 1; }
            50% { opacity: 0.6; }
        }

        @keyframes spin {
            to { transform: rotate(360deg); }
        }

        .pulse { animation: pulse 2s ease-in-out infinite; }
        .spin { animation: spin 1s linear infinite; }

        /* History drawer */
        .history-drawer {
            transform: translateX(100%);
            transition: transform 0.3s ease;
        }
        .history-drawer.active {
            transform: translateX(0);
        }

        /* Detail drawer */
        .drawer {
            transform: translateX(100%);
            transition: transform 0.3s ease;
        }
        .drawer.open {
            transform: translateX(0);
        }
    </style>

        /* JavaScript-generated element styles */

        /* Finding items */
        .finding-item {
            padding: 1rem;
            background-color: hsl(var(--card));
            border-left: 4px solid;
            border-radius: 0.5rem;
            cursor: pointer;
            transition: all 0.2s;
        }
        .finding-item:hover {
            box-shadow: 0 4px 12px rgb(0 0 0 / 0.1);
        }
        .finding-item.critical { border-left-color: #ef4444; background-color: #fef2f2; }
        .finding-item.high { border-left-color: #f97316; background-color: #fff7ed; }
        .finding-item.medium { border-left-color: #3b82f6; background-color: #eff6ff; }
        .finding-item.low { border-left-color: #6b7280; background-color: #f9fafb; }
        [data-theme="dark"] .finding-item.critical { background-color: rgba(127, 29, 29, 0.1); }
        [data-theme="dark"] .finding-item.high { background-color: rgba(154, 52, 18, 0.1); }
        [data-theme="dark"] .finding-item.medium { background-color: rgba(30, 58, 138, 0.1); }
        [data-theme="dark"] .finding-item.low { background-color: rgba(55, 65, 81, 0.1); }

        /* Severity badges */
        .severity-badge {
            display: inline-block;
            padding: 0.25rem 0.5rem;
            font-size: 0.75rem;
            font-weight: 600;
            border-radius: 0.25rem;
            text-transform: uppercase;
        }
        .severity-badge.critical { background-color: #fee2e2; color: #b91c1c; }
        .severity-badge.high { background-color: #ffedd5; color: #c2410c; }
        .severity-badge.medium { background-color: #dbeafe; color: #1e40af; }
        .severity-badge.low { background-color: #f3f4f6; color: #374151; }
        [data-theme="dark"] .severity-badge.critical { background-color: rgba(127, 29, 29, 0.3); color: #fca5a5; }
        [data-theme="dark"] .severity-badge.high { background-color: rgba(154, 52, 18, 0.3); color: #fb923c; }
        [data-theme="dark"] .severity-badge.medium { background-color: rgba(30, 58, 138, 0.3); color: #60a5fa; }
        [data-theme="dark"] .severity-badge.low { background-color: rgba(55, 65, 81, 0.5); color: #9ca3af; }

        /* Dimension badge */
        .dimension-badge {
            display: inline-block;
            padding: 0.25rem 0.5rem;
            font-size: 0.75rem;
            font-weight: 500;
            border-radius: 0.25rem;
            background-color: hsl(var(--muted));
            color: hsl(var(--muted-foreground));
        }

        /* Finding details */
        .finding-title { font-size: 1rem; font-weight: 600; color: hsl(var(--foreground)); margin-bottom: 0.25rem; }
        .finding-file { font-size: 0.875rem; color: hsl(var(--muted-foreground)); margin-bottom: 0.5rem; }
        .finding-description { font-size: 0.875rem; color: hsl(var(--foreground)); line-height: 1.6; }
        .finding-badges { display: flex; gap: 0.5rem; }
        .finding-header { display: flex; align-items: flex-start; justify-content: space-between; margin-bottom: 0.5rem; }
        .finding-checkbox { width: 20px; height: 20px; cursor: pointer; accent-color: hsl(var(--primary)); }

        /* Drawer sections */
        .drawer-section { margin-bottom: 1.5rem; }
        .drawer-section:last-child { margin-bottom: 0; }
        .drawer-section-title { font-size: 0.875rem; font-weight: 600; color: hsl(var(--foreground)); margin-bottom: 0.75rem; text-transform: uppercase; letter-spacing: 0.05em; }

        /* Other dynamically generated elements */
        .code-snippet { padding: 0.75rem; background-color: hsl(var(--muted)); border-radius: 0.375rem; font-size: 0.875rem; font-family: Consolas, Monaco, 'Courier New', monospace; overflow-x: auto; }
        .recommendation-box { padding: 1rem; background-color: hsl(var(--success-light)); border-radius: 0.5rem; font-size: 0.875rem; line-height: 1.6; }
        .metadata-grid { display: grid; grid-template-columns: repeat(2, 1fr); gap: 1rem; }
        .metadata-item { display: flex; flex-direction: column; gap: 0.25rem; }
        .metadata-label { font-size: 0.75rem; font-weight: 500; color: hsl(var(--muted-foreground)); text-transform: uppercase; letter-spacing: 0.05em; }
        .metadata-value { font-size: 0.875rem; color: hsl(var(--foreground)); }
        .reference-list { list-style: disc; padding-left: 1.25rem; }
        .reference-list li { font-size: 0.875rem; color: hsl(var(--foreground)); margin-bottom: 0.25rem; }
        .reference-list a { color: hsl(var(--primary)); text-decoration: none; }
        .reference-list a:hover { text-decoration: underline; }

        /* Fix status badges */
        .fix-status-badge { display: inline-block; padding: 0.25rem 0.75rem; border-radius: 9999px; font-size: 0.75rem; font-weight: 600; margin-top: 0.5rem; }
        .fix-status-badge.status-pending { background-color: transparent; color: hsl(var(--muted-foreground)); border: 1px solid hsl(var(--border)); }
        .fix-status-badge.status-in-progress { background-color: hsl(var(--primary)); color: hsl(var(--primary-foreground)); }
        .fix-status-badge.status-fixed { background-color: hsl(var(--success)); color: white; }
        .fix-status-badge.status-failed { background-color: hsl(var(--destructive)); color: white; }

        /* Dimension table */
        .dimension-name { display: flex; align-items: center; gap: 0.5rem; }
        .dimension-icon { font-size: 1.125rem; }
        .count-badge { display: inline-block; padding: 0.25rem 0.5rem; font-size: 0.75rem; font-weight: 600; border-radius: 0.25rem; }
        .count-badge.critical { background-color: #fee2e2; color: #b91c1c; }
        .count-badge.high { background-color: #ffedd5; color: #c2410c; }
        .count-badge.medium { background-color: #dbeafe; color: #1e40af; }
        .count-badge.low { background-color: #f3f4f6; color: #374151; }
        .count-badge.total { background-color: rgba(59, 130, 246, 0.1); color: hsl(var(--primary)); font-weight: 700; }
        .count-badge.zero { opacity: 0.5; }
        [data-theme="dark"] .count-badge.critical { background-color: rgba(127, 29, 29, 0.3); color: #fca5a5; }
        [data-theme="dark"] .count-badge.high { background-color: rgba(154, 52, 18, 0.3); color: #fb923c; }
        [data-theme="dark"] .count-badge.medium { background-color: rgba(30, 58, 138, 0.3); color: #60a5fa; }
        [data-theme="dark"] .count-badge.low { background-color: rgba(55, 65, 81, 0.5); color: #9ca3af; }
        .status-indicator { display: inline-flex; align-items: center; justify-center; width: 1.5rem; height: 1.5rem; border-radius: 9999px; font-size: 0.875rem; }
        .status-indicator.reviewed { background-color: rgba(34, 197, 94, 0.2); color: hsl(var(--success)); }
        .status-indicator.pending { background-color: hsl(var(--muted)); color: hsl(var(--muted-foreground)); }

        /* Active group/agent cards */
        .active-group-card { background-color: hsl(var(--card)); border: 1px solid hsl(var(--border)); border-radius: 0.5rem; padding: 1rem; }
        .group-header { display: flex; align-items: center; justify-content: space-between; margin-bottom: 0.5rem; }
        .group-id { font-size: 0.875rem; font-weight: 600; color: hsl(var(--foreground)); }
        .group-status { font-size: 0.75rem; padding: 0.25rem 0.5rem; border-radius: 9999px; background-color: rgba(59, 130, 246, 0.1); color: hsl(var(--primary)); font-weight: 500; }
        .group-findings { font-size: 0.875rem; color: hsl(var(--muted-foreground)); }
        .group-active-items { margin-top: 0.5rem; padding: 0.5rem; background-color: rgba(59, 130, 246, 0.1); border-left: 4px solid hsl(var(--primary)); border-radius: 0.25rem; font-size: 0.875rem; color: hsl(var(--foreground)); }
        .active-agent-item { padding: 0.75rem; background-color: hsl(var(--muted)); border-radius: 0.5rem; margin-bottom: 0.5rem; }
        .agent-status { font-size: 0.875rem; font-weight: 500; color: hsl(var(--foreground)); }
        .agent-status-badge { display: inline-block; padding: 0.125rem 0.5rem; margin-left: 0.5rem; font-size: 0.75rem; background-color: hsl(var(--primary)); color: hsl(var(--primary-foreground)); border-radius: 9999px; font-weight: 500; }
        .agent-task { font-size: 0.875rem; color: hsl(var(--foreground)); margin-top: 0.25rem; }
        .agent-file { font-size: 0.75rem; color: hsl(var(--muted-foreground)); margin-top: 0.25rem; }

        /* Flow control & stages */
        .flow-control-container { margin-top: 0.75rem; padding: 0.625rem; background-color: rgba(139, 92, 246, 0.05); border-radius: 0.5rem; border: 1px solid rgba(139, 92, 246, 0.2); }
        .flow-control-header { font-size: 0.75rem; font-weight: 600; color: hsl(var(--muted-foreground)); margin-bottom: 0.5rem; text-transform: uppercase; letter-spacing: 0.05em; }
        .flow-steps { display: flex; flex-direction: column; gap: 0.375rem; }
        .flow-step { display: flex; align-items: center; gap: 0.5rem; padding: 0.375rem 0.625rem; border-radius: 0.25rem; font-size: 0.875rem; transition: all 0.2s; }
        .flow-step-completed { background-color: rgba(34, 197, 94, 0.1); color: #22c55e; }
        .flow-step-in-progress { background-color: rgba(59, 130, 246, 0.1); color: hsl(var(--primary)); }
        .flow-step-failed { background-color: rgba(239, 68, 68, 0.1); color: #ef4444; }
        .flow-step-pending { background-color: rgba(156, 163, 175, 0.1); color: hsl(var(--muted-foreground)); }
        .flow-step-icon { font-size: 1rem; }
        .flow-step-name { font-weight: 500; }
        .stage-item { flex: 1; min-width: 150px; padding: 0.75rem; background-color: hsl(var(--card)); border-radius: 0.375rem; border: 2px solid; text-align: center; transition: all 0.3s; }
        .stage-item.pending { opacity: 0.6; border-color: hsl(var(--border)); }
        .stage-item.in-progress { border-color: hsl(var(--primary)); box-shadow: 0 0 10px rgba(59, 130, 246, 0.3); }
        .stage-item.completed { border-color: hsl(var(--success)); background-color: rgba(34, 197, 94, 0.05); }
        .stage-number { font-size: 0.875rem; font-weight: 600; color: hsl(var(--muted-foreground)); margin-bottom: 0.25rem; }
        .stage-mode { font-size: 0.9rem; font-weight: 600; margin-bottom: 0.25rem; }
        .stage-groups { font-size: 0.75rem; color: hsl(var(--muted-foreground)); }

        /* Phase & status badges */
        .phase-badge { padding: 0.25rem 0.75rem; font-size: 0.75rem; font-weight: 600; border-radius: 9999px; text-transform: uppercase; }
        .phase-badge.phase-planning { background-color: hsl(var(--warning)); color: white; }
        .phase-badge.phase-execution { background-color: hsl(var(--primary)); color: hsl(var(--primary-foreground)); }
        .phase-badge.phase-completion { background-color: hsl(var(--success)); color: white; }
        .phase-badge.phase-parallel { background-color: hsl(var(--primary)); color: hsl(var(--primary-foreground)); }
        .phase-badge.phase-iterate { background-color: hsl(var(--warning)); color: white; }
        .phase-badge.phase-aggregate { background-color: hsl(var(--secondary)); color: hsl(var(--secondary-foreground)); }
        .phase-badge.phase-complete { background-color: hsl(var(--success)); color: white; }

        /* History items */
        .history-item { padding: 1rem; background-color: hsl(var(--muted)); border-radius: 0.5rem; margin-bottom: 1rem; border-left: 4px solid hsl(var(--primary)); }
        .history-item.status-fixed { border-left-color: hsl(var(--success)); }
        .history-item.status-failed { border-left-color: hsl(var(--destructive)); }
        .history-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 0.5rem; }
        .history-status { font-weight: 600; color: hsl(var(--foreground)); }
        .history-time { font-size: 0.75rem; color: hsl(var(--muted-foreground)); }
        .history-details { display: flex; flex-direction: column; gap: 0.25rem; font-size: 0.875rem; }

        /* Empty state */
        .empty-state { text-center: center; padding: 3rem 0; }
        .empty-state-icon { font-size: 4rem; margin-bottom: 1rem; }

        /* Tab active state */
        .tab { padding: 0.5rem 1rem; border-radius: 0.5rem; font-weight: 500; font-size: 0.875rem; white-space: nowrap; transition: all 0.2s; border: 1px solid hsl(var(--border)); background-color: hsl(var(--card)); cursor: pointer; }
        .tab:hover { background-color: hsl(var(--hover)); }
        .tab.active { background-color: hsl(var(--primary)); color: hsl(var(--primary-foreground)); border-color: hsl(var(--primary)); }

        /* Drawer overlay states */
        #drawerOverlay.show, #historyDrawerOverlay.active { display: block !important; }
</head>
<body class="font-sans bg-background text-foreground leading-normal">
    <div class="max-w-[1600px] mx-auto p-5">
        <!-- Header -->
        <header class="bg-card shadow rounded-lg p-5 mb-8">
            <div class="flex items-center justify-between mb-4">
                <h1 class="text-3xl font-bold text-primary flex items-center gap-2">
                    <span>🔍</span>
                    <span>Code Review Dashboard</span>
                </h1>
                <button class="p-2 text-xl hover:bg-hover rounded transition-colors" id="themeToggle" title="Toggle theme">🌙</button>
            </div>

            <div class="flex gap-5 flex-wrap items-center text-sm text-muted-foreground mb-4">
                <span>📋 Session: <strong class="text-foreground" id="sessionId">Loading...</strong></span>
                <span>🆔 Review ID: <strong class="text-foreground" id="reviewId">Loading...</strong></span>
                <span>🕒 Last Updated: <strong class="text-foreground" id="lastUpdate">Loading...</strong></span>
            </div>

            <div class="flex gap-4 flex-wrap items-center">
                <div class="flex-1 min-w-[250px] relative">
                    <input type="text" id="searchInput" placeholder="🔍 Search findings..."
                        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>

                <div class="flex gap-2.5 items-center">
                    <span class="text-sm text-muted-foreground font-medium" id="selectionCounter">0 findings selected</span>
                    <button class="px-3 py-1.5 text-xs border border-border rounded-lg bg-card text-foreground hover:bg-hover transition-all" onclick="selectAll()">Select All</button>
                    <button class="px-3 py-1.5 text-xs border border-border rounded-lg bg-card text-foreground hover:bg-hover transition-all" onclick="deselectAll()">Deselect All</button>
                </div>

                <button class="px-5 py-2.5 border border-border rounded-lg bg-card text-foreground font-medium text-sm hover:bg-hover hover:shadow transition-all" onclick="exportToMarkdown()">📥 Export Report</button>
                <button class="px-5 py-2.5 rounded-lg bg-success text-white font-medium text-sm hover:bg-success/90 transition-all disabled:opacity-50 disabled:cursor-not-allowed" id="exportFixBtn" onclick="exportSelectedFindings()" disabled>🔧 Export Selected for Fixing</button>
            </div>
        </header>

        <!-- Fix Progress Section -->
        <div class="hidden bg-card rounded-lg shadow p-5 mb-5" id="fixProgressSection">
            <div class="flex justify-between items-center mb-4">
                <h3 class="text-lg font-semibold text-foreground">Fix Progress</h3>
                <div class="flex items-center gap-2.5">
                    <span class="px-3 py-1 text-xs font-semibold rounded-full bg-primary text-primary-foreground uppercase" id="fixPhaseBadge">PLANNING</span>
                    <button class="px-3 py-1.5 text-xs border border-border rounded-lg bg-card text-foreground hover:bg-hover transition-all" onclick="toggleFixProgress()">Collapse</button>
                    <button class="px-3 py-1.5 text-xs border border-border rounded-lg bg-card text-foreground hover:bg-hover transition-all" onclick="openHistoryDrawer()">📜 View Fix History</button>
                </div>
            </div>

            <!-- Planning Phase Indicator -->
            <div id="planningPhase" class="hidden text-center py-5">
                <div class="text-4xl mb-2.5">🤖</div>
                <div class="text-lg font-semibold mb-1.5">Planning Fixes</div>
                <div class="text-muted-foreground">AI is analyzing findings and generating fix plan...</div>
            </div>

            <!-- Stage Timeline -->
            <div id="stageTimeline" class="hidden flex gap-2.5 my-5 p-4 bg-muted rounded-lg overflow-x-auto">
                <!-- Stages populated by JavaScript -->
            </div>

            <!-- Execution Phase UI -->
            <div id="executionPhase" class="hidden">
                <!-- Progress Bar -->
                <div class="h-2 bg-muted rounded overflow-hidden mb-4">
                    <div class="h-full bg-success transition-all duration-300" id="fixProgressFill" style="width: 0%"></div>
                </div>
                <div class="text-center text-sm text-muted-foreground mt-2.5">
                    <span id="fixProgressText">No active fix session</span>
                </div>

                <!-- Active Groups -->
                <div id="activeGroupsList" class="grid grid-cols-[repeat(auto-fit,minmax(300px,1fr))] gap-4 my-5">
                    <!-- Active groups populated by JavaScript -->
                </div>

                <!-- Active Agents -->
                <div id="activeAgentsList" class="mt-4 border-t border-border pt-4">
                    <!-- Active agents populated by JavaScript -->
                </div>
            </div>
        </div>

        <!-- Progress Section -->
        <div class="bg-card rounded-lg shadow p-5 mb-5">
            <div class="flex justify-between items-center mb-4">
                <h3 class="text-lg font-semibold text-foreground">Review Progress</h3>
                <span class="px-3 py-1 text-xs font-semibold rounded-full bg-primary text-primary-foreground uppercase" id="phaseBadge">LOADING</span>
            </div>

            <div class="h-2 bg-muted rounded overflow-hidden mb-4">
                <div class="h-full bg-primary transition-all duration-300" id="progressFill" style="width: 0%"></div>
            </div>

            <div class="text-center text-sm text-muted-foreground">
                <span id="progressText">Initializing...</span>
            </div>
        </div>

        <!-- Severity Summary Cards -->
        <div class="grid grid-cols-[repeat(auto-fit,minmax(200px,1fr))] gap-4 mb-5">
            <div class="text-center p-5 bg-red-100 dark:bg-red-900/20 rounded-lg cursor-pointer hover:shadow-md transition-all" onclick="filterBySeverity('critical')">
                <div class="text-3xl mb-2">🔴</div>
                <div class="text-3xl font-bold text-red-700 dark:text-red-400" id="criticalCount">0</div>
                <div class="text-sm text-muted-foreground mt-1">Critical</div>
            </div>
            <div class="text-center p-5 bg-orange-100 dark:bg-orange-900/20 rounded-lg cursor-pointer hover:shadow-md transition-all" onclick="filterBySeverity('high')">
                <div class="text-3xl mb-2">🟠</div>
                <div class="text-3xl font-bold text-orange-700 dark:text-orange-400" id="highCount">0</div>
                <div class="text-sm text-muted-foreground mt-1">High</div>
            </div>
            <div class="text-center p-5 bg-blue-100 dark:bg-blue-900/20 rounded-lg cursor-pointer hover:shadow-md transition-all" onclick="filterBySeverity('medium')">
                <div class="text-3xl mb-2">🟡</div>
                <div class="text-3xl font-bold text-blue-700 dark:text-blue-400" id="mediumCount">0</div>
                <div class="text-sm text-muted-foreground mt-1">Medium</div>
            </div>
            <div class="text-center p-5 bg-gray-100 dark:bg-gray-800/50 rounded-lg cursor-pointer hover:shadow-md transition-all" onclick="filterBySeverity('low')">
                <div class="text-3xl mb-2">🟢</div>
                <div class="text-3xl font-bold text-gray-700 dark:text-gray-400" id="lowCount">0</div>
                <div class="text-sm text-muted-foreground mt-1">Low</div>
            </div>
        </div>

        <!-- Dimension Summary Table -->
        <div class="bg-card rounded-lg shadow p-5 mb-5">
            <div class="text-lg font-semibold text-foreground mb-4">Findings by Dimension</div>
            <div class="overflow-x-auto">
                <table class="w-full">
                    <thead>
                        <tr class="border-b border-border">
                            <th class="text-left py-3 px-4 text-sm font-semibold text-foreground">Dimension</th>
                            <th class="text-center py-3 px-4 text-sm font-semibold text-foreground">Critical</th>
                            <th class="text-center py-3 px-4 text-sm font-semibold text-foreground">High</th>
                            <th class="text-center py-3 px-4 text-sm font-semibold text-foreground">Medium</th>
                            <th class="text-center py-3 px-4 text-sm font-semibold text-foreground">Low</th>
                            <th class="text-center py-3 px-4 text-sm font-semibold text-foreground">Total</th>
                            <th class="text-center py-3 px-4 text-sm font-semibold text-foreground">Status</th>
                        </tr>
                    </thead>
                    <tbody id="dimensionSummaryBody">
                        <!-- Populated by JavaScript -->
                    </tbody>
                </table>
            </div>
        </div>

        <!-- Dimension Tabs -->
        <div class="flex gap-2 mb-5 overflow-x-auto pb-2">
            <button class="px-4 py-2 rounded-lg font-medium text-sm whitespace-nowrap transition-all border border-border bg-primary text-primary-foreground" data-dimension="all" onclick="filterByDimension('all')">All Findings</button>
            <button class="px-4 py-2 rounded-lg font-medium text-sm whitespace-nowrap transition-all border border-border hover:bg-hover" data-dimension="security" onclick="filterByDimension('security')">Security</button>
            <button class="px-4 py-2 rounded-lg font-medium text-sm whitespace-nowrap transition-all border border-border hover:bg-hover" data-dimension="architecture" onclick="filterByDimension('architecture')">Architecture</button>
            <button class="px-4 py-2 rounded-lg font-medium text-sm whitespace-nowrap transition-all border border-border hover:bg-hover" data-dimension="quality" onclick="filterByDimension('quality')">Quality</button>
            <button class="px-4 py-2 rounded-lg font-medium text-sm whitespace-nowrap transition-all border border-border hover:bg-hover" data-dimension="action-items" onclick="filterByDimension('action-items')">Action Items</button>
            <button class="px-4 py-2 rounded-lg font-medium text-sm whitespace-nowrap transition-all border border-border hover:bg-hover" data-dimension="performance" onclick="filterByDimension('performance')">Performance</button>
            <button class="px-4 py-2 rounded-lg font-medium text-sm whitespace-nowrap transition-all border border-border hover:bg-hover" data-dimension="maintainability" onclick="filterByDimension('maintainability')">Maintainability</button>
            <button class="px-4 py-2 rounded-lg font-medium text-sm whitespace-nowrap transition-all border border-border hover:bg-hover" data-dimension="best-practices" onclick="filterByDimension('best-practices')">Best Practices</button>
        </div>

        <!-- Advanced Filters -->
        <div class="bg-card rounded-lg shadow p-5 mb-5">
            <div class="flex justify-between items-center mb-4">
                <div class="text-lg font-semibold text-foreground">🎯 Advanced Filters & Sort</div>
                <button class="px-4 py-2 border border-border rounded-lg text-sm font-medium hover:bg-hover transition-all" onclick="resetFilters()">Reset All Filters</button>
            </div>

            <div class="space-y-4">
                <!-- Severity Filter -->
                <div class="flex gap-2.5 flex-wrap items-center">
                    <span class="text-sm font-medium text-muted-foreground min-w-[80px]">Severity:</span>
                    <div class="flex gap-2.5 flex-wrap">
                        <label class="flex items-center gap-1.5 px-3 py-2 rounded-lg bg-muted cursor-pointer transition-all hover:bg-primary hover:text-white border-2 border-transparent has-[:checked]:bg-primary has-[:checked]:text-white" id="filter-critical">
                            <input type="checkbox" value="critical" onchange="toggleSeverityFilter('critical')" class="cursor-pointer">
                            <span>🔴 Critical</span>
                        </label>
                        <label class="flex items-center gap-1.5 px-3 py-2 rounded-lg bg-muted cursor-pointer transition-all hover:bg-primary hover:text-white border-2 border-transparent has-[:checked]:bg-primary has-[:checked]:text-white" id="filter-high">
                            <input type="checkbox" value="high" onchange="toggleSeverityFilter('high')" class="cursor-pointer">
                            <span>🟠 High</span>
                        </label>
                        <label class="flex items-center gap-1.5 px-3 py-2 rounded-lg bg-muted cursor-pointer transition-all hover:bg-primary hover:text-white border-2 border-transparent has-[:checked]:bg-primary has-[:checked]:text-white" id="filter-medium">
                            <input type="checkbox" value="medium" onchange="toggleSeverityFilter('medium')" class="cursor-pointer">
                            <span>🟡 Medium</span>
                        </label>
                        <label class="flex items-center gap-1.5 px-3 py-2 rounded-lg bg-muted cursor-pointer transition-all hover:bg-primary hover:text-white border-2 border-transparent has-[:checked]:bg-primary has-[:checked]:text-white" id="filter-low">
                            <input type="checkbox" value="low" onchange="toggleSeverityFilter('low')" class="cursor-pointer">
                            <span>🟢 Low</span>
                        </label>
                    </div>
                </div>

                <!-- Sort Controls -->
                <div class="flex gap-2.5 flex-wrap items-center">
                    <span class="text-sm font-medium text-muted-foreground min-w-[80px]">Sort:</span>
                    <select id="sortSelect" class="px-4 py-2 border border-border rounded-lg text-sm bg-card hover:bg-hover transition-all cursor-pointer" onchange="sortFindings()">
                        <option value="severity">By Severity</option>
                        <option value="dimension">By Dimension</option>
                        <option value="file">By File</option>
                        <option value="title">By Title</option>
                    </select>
                    <button class="flex items-center gap-2 px-4 py-2 border border-border rounded-lg text-sm hover:bg-hover transition-all min-w-[140px] justify-center" id="sortOrderBtn" onclick="toggleSortOrder()">
                        <span class="text-lg" id="sortOrderIcon">↓</span>
                        <span id="sortOrderText">Descending</span>
                    </button>
                </div>

                <!-- Selection Actions -->
                <div class="flex gap-2.5 flex-wrap items-center">
                    <span class="text-sm font-medium text-muted-foreground min-w-[80px]">Select:</span>
                    <button class="px-3 py-2 border border-border rounded-lg text-sm hover:bg-hover transition-all" onclick="selectAllVisible()">Select Visible</button>
                    <button class="px-3 py-2 border border-border rounded-lg text-sm hover:bg-hover transition-all" onclick="selectBySeverity('critical')">Critical Only</button>
                    <button class="px-3 py-2 border border-border rounded-lg text-sm hover:bg-hover transition-all" onclick="deselectAll()">Clear</button>
                </div>
            </div>
        </div>

        <!-- Findings Container -->
        <div class="bg-card rounded-lg shadow p-5">
            <div class="flex items-center justify-between mb-4">
                <h3 class="text-lg font-semibold text-foreground">Findings <span id="findingsCount">(0)</span></h3>
            </div>
            <div id="findingsList" class="space-y-3">
                <div class="text-center py-12">
                    <div class="text-6xl mb-4">⏳</div>
                    <p class="text-lg text-muted-foreground">Loading findings...</p>
                </div>
            </div>
        </div>
    </div>

    <!-- Detail Drawer -->
    <div class="fixed inset-0 bg-black/50 z-40 hidden" id="drawerOverlay" onclick="closeDrawer()"></div>
    <div class="drawer fixed top-0 right-0 w-[600px] max-w-full h-screen bg-card shadow-lg z-50 flex flex-col" id="findingDrawer">
        <div class="flex items-center justify-between px-5 py-4 border-b border-border">
            <h3 class="text-lg font-semibold text-foreground" id="drawerTitle">Finding Details</h3>
            <button class="w-8 h-8 flex items-center justify-center text-xl text-muted-foreground hover:text-foreground hover:bg-hover rounded transition-colors" onclick="closeDrawer()">&times;</button>
        </div>
        <div class="flex-1 overflow-y-auto p-5" id="drawerContent">
            <!-- Content populated by JavaScript -->
        </div>
    </div>

    <!-- History Timeline Drawer -->
    <div class="fixed inset-0 bg-black/50 z-40 hidden" id="historyDrawerOverlay" onclick="closeHistoryDrawer()"></div>
    <div class="history-drawer fixed top-0 right-0 w-[600px] max-w-full h-screen bg-card shadow-lg z-50 overflow-y-auto" id="historyDrawer">
        <div class="sticky top-0 bg-card border-b border-border p-5 flex justify-between items-center z-10">
            <h3 class="text-xl font-semibold text-foreground">📜 Fix History</h3>
            <button class="w-8 h-8 flex items-center justify-center text-xl text-muted-foreground hover:text-foreground hover:bg-hover rounded transition-colors" onclick="closeHistoryDrawer()">&times;</button>
        </div>
        <div class="p-5" id="historyTimeline">
            <!-- History items populated by JavaScript -->
        </div>
    </div>

    <script>

        // State
        let allFindings = [];
        let filteredFindings = [];
        let currentFilters = {
            dimension: 'all',
            severities: new Set(), // ✨ NEW: Multiple severity selection
            search: ''
        };
        let sortConfig = {
            field: 'severity',
            order: 'desc' // ✨ NEW: 'asc' or 'desc'
        };
        let pollingInterval = null;
        let reviewState = null;

        // Fix-related state
        let selectedFindings = new Set();
        let fixSession = null;
        let fixProgressInterval = null;
        let fixProgressCollapsed = false;

        // Selection management
        function toggleFindingSelection(findingId, event) {
            event.stopPropagation(); // Prevent triggering showFindingDetail

            if (selectedFindings.has(findingId)) {
                selectedFindings.delete(findingId);
            } else {
                selectedFindings.add(findingId);
            }

            updateSelectionUI();
        }

        function selectAll() {
            allFindings.forEach(finding => {
                selectedFindings.add(finding.id);
            });
            updateSelectionUI();
        }

        // ✨ NEW: Select only currently visible findings
        function selectAllVisible() {
            filteredFindings.forEach(finding => {
                selectedFindings.add(finding.id);
            });
            updateSelectionUI();
        }

        // ✨ NEW: Select findings by severity
        function selectBySeverity(severity) {
            allFindings.forEach(finding => {
                if (finding.severity.toLowerCase() === severity) {
                    selectedFindings.add(finding.id);
                }
            });
            updateSelectionUI();
        }

        function deselectAll() {
            selectedFindings.clear();
            updateSelectionUI();
        }

        // ✨ NEW: Toggle severity filter
        function toggleSeverityFilter(severity) {
            if (currentFilters.severities.has(severity)) {
                currentFilters.severities.delete(severity);
                document.getElementById(`filter-${severity}`).classList.remove('active');
            } else {
                currentFilters.severities.add(severity);
                document.getElementById(`filter-${severity}`).classList.add('active');
            }
            applyFilters();
        }

        // ✨ NEW: Toggle sort order
        function toggleSortOrder() {
            sortConfig.order = sortConfig.order === 'asc' ? 'desc' : 'asc';

            // Update UI
            const icon = document.getElementById('sortOrderIcon');
            const text = document.getElementById('sortOrderText');

            if (sortConfig.order === 'asc') {
                icon.textContent = '↑';
                text.textContent = 'Ascending';
            } else {
                icon.textContent = '↓';
                text.textContent = 'Descending';
            }

            sortFindings();
        }

        // ✨ NEW: Reset all filters
        function resetFilters() {
            // Reset severity filters
            currentFilters.severities.clear();
            document.querySelectorAll('.filter-checkbox-item').forEach(item => {
                item.classList.remove('active');
                const checkbox = item.querySelector('input[type="checkbox"]');
                if (checkbox) checkbox.checked = false;
            });

            // Reset dimension filter
            currentFilters.dimension = 'all';
            document.querySelectorAll('.tab').forEach(tab => {
                tab.classList.toggle('active', tab.dataset.dimension === 'all');
            });

            // Reset search
            currentFilters.search = '';
            document.getElementById('searchInput').value = '';

            // Reset sort
            sortConfig.field = 'severity';
            sortConfig.order = 'desc';
            document.getElementById('sortSelect').value = 'severity';
            document.getElementById('sortOrderIcon').textContent = '↓';
            document.getElementById('sortOrderText').textContent = 'Descending';

            applyFilters();
        }

        function updateSelectionUI() {
            // Update counter
            const counter = document.getElementById('selectionCounter');
            counter.textContent = `${selectedFindings.size} finding${selectedFindings.size !== 1 ? 's' : ''} selected`;

            // Update export button state
            const exportBtn = document.getElementById('exportFixBtn');
            exportBtn.disabled = selectedFindings.size === 0;

            // Update checkbox states
            document.querySelectorAll('.finding-checkbox').forEach(checkbox => {
                checkbox.checked = selectedFindings.has(checkbox.dataset.findingId);
            });
        }

        // Export selected findings for fixing
        async function exportSelectedFindings() {
            if (selectedFindings.size === 0) {
                alert('Please select at least one finding to export');
                return;
            }

            // Gather selected findings
            const selectedFindingsData = allFindings.filter(f => selectedFindings.has(f.id));

            // Create export data structure
            const exportData = {
                export_id: `${Date.now()}`,
                export_timestamp: new Date().toISOString(),
                review_id: reviewState?.review_id || 'unknown',
                session_id: reviewState?.session_id || 'unknown',
                findings_count: selectedFindingsData.length,
                findings: selectedFindingsData.map(f => ({
                    id: f.id,
                    title: f.title,
                    description: f.description,
                    severity: f.severity,
                    dimension: f.dimension,
                    category: f.category || 'uncategorized',
                    file: f.file,
                    line: f.line,
                    code_context: f.code_context || null,
                    recommendations: f.recommendations || [],
                    root_cause: f.root_cause || null
                }))
            };

            // Convert to JSON and download
            const jsonStr = JSON.stringify(exportData, null, 2);
            const blob = new Blob([jsonStr], { type: 'application/json' });
            const url = URL.createObjectURL(blob);
            const a = document.createElement('a');
            const filename = `fix-export-${exportData.export_id}.json`;
            a.href = url;
            a.download = filename;
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
            URL.revokeObjectURL(url);

            // ✨ Show export path and usage instructions with session directory recommendation
            const reviewDir = window.location.pathname.replace('/dashboard.html', '').replace('/.review/dashboard.html', '/.review');
            // Extract absolute path from file:// URL
            const absolutePath = decodeURIComponent(window.location.pathname).replace(/^\/([A-Z]:)/, '$1');
            const sessionDir = absolutePath.replace('/.review/dashboard.html', '');
            const reviewSessionDir = `${sessionDir}/.review`;

            const notification = `
✅ Exported ${selectedFindingsData.length} finding${selectedFindingsData.length !== 1 ? 's' : ''} for automated fixing!

📁 File: ${filename}
📂 Browser download: Your Downloads folder

📋 Recommended Location:
   ${reviewSessionDir}/

🔄 Move to session directory (recommended):
   # On Windows:
   move "%USERPROFILE%\\Downloads\\${filename}" "${reviewSessionDir.replace(/\//g, '\\')}\\${filename}"

   # On Mac/Linux:
   mv ~/Downloads/${filename} ${reviewSessionDir}/${filename}

🔧 Usage (after moving file):
   /workflow:review-fix ${reviewSessionDir}/${filename}

   Or directly from Downloads:
   /workflow:review-fix ~/Downloads/${filename}

📋 Review Session: ${exportData.session_id}
📊 Findings by Severity:
   • Critical: ${selectedFindingsData.filter(f => f.severity === 'critical').length}
   • High: ${selectedFindingsData.filter(f => f.severity === 'high').length}
   • Medium: ${selectedFindingsData.filter(f => f.severity === 'medium').length}
   • Low: ${selectedFindingsData.filter(f => f.severity === 'low').length}

💡 The automated fix workflow will:
   1. Group findings by file and relationship
   2. Execute fixes in parallel where safe
   3. Run tests after each fix
   4. Track progress in this dashboard
            `.trim();

            alert(notification);
        }

        // Fix progress tracking
        function detectFixSession() {
            // Check if there's an active fix session in the review directory
            fetch('./fixes/active-fix-session.json')
                .then(response => {
                    if (response.ok) {
                        return response.json();
                    }
                    throw new Error('No active fix session');
                })
                .then(data => {
                    fixSession = data;
                    startFixProgressPolling(data.fix_session_id);
                })
                .catch(() => {
                    // No active fix session, hide progress section
                    document.getElementById('fixProgressSection').classList.remove('active');
                });
        }

        function startFixProgressPolling(fixSessionId) {
            // Show progress section
            document.getElementById('fixProgressSection').classList.add('active');

            // Initial load
            loadFixProgress(fixSessionId);

            // Start polling every 3 seconds
            if (fixProgressInterval) {
                clearInterval(fixProgressInterval);
            }
            fixProgressInterval = setInterval(() => {
                loadFixProgress(fixSessionId);
            }, 3000);
        }

        async function loadFixProgress(fixSessionId) {
            try {
                // Step 1: Load fix plan to get progress file list
                const planResponse = await fetch(`./fixes/${fixSessionId}/fix-plan.json`);
                if (!planResponse.ok) throw new Error('Fix plan not found');
                const fixPlan = await planResponse.json();

                // Step 2: Load all progress files in parallel
                const progressFiles = fixPlan.groups.map(g => g.progress_file);
                const progressPromises = progressFiles.map(file =>
                    fetch(`./fixes/${fixSessionId}/${file}`)
                        .then(r => r.ok ? r.json() : null)
                        .catch(() => null)
                );
                const progressDataArray = await Promise.all(progressPromises);

                // Step 3: Aggregate data from all progress files
                const progressData = aggregateProgressData(fixPlan, progressDataArray.filter(d => d !== null));

                updateFixStatus(progressData);

                // If complete, stop polling and update history
                if (progressData.status === 'completed' || progressData.status === 'failed') {
                    clearInterval(fixProgressInterval);
                    fixProgressInterval = null;

                    // Reload fix history
                    await loadFixHistory();

                    // Mark findings as fixed
                    if (progressData.status === 'completed') {
                        progressData.fixes.forEach(fix => {
                            if (fix.status === 'fixed') {
                                markFindingAsFixed(fix.finding_id);
                            }
                        });
                    }
                }
            } catch (error) {
                console.error('Error loading fix progress:', error);
            }
        }

        function aggregateProgressData(fixPlan, progressDataArray) {
            // Aggregate all findings from progress files
            const allFindings = [];
            const activeAgents = [];
            let hasAnyInProgress = false;
            let hasAnyFailed = false;
            let allCompleted = true;

            progressDataArray.forEach(progressFile => {
                // Collect all findings with group_id
                if (progressFile.findings) {
                    progressFile.findings.forEach(finding => {
                        allFindings.push({
                            finding_id: finding.finding_id,
                            finding_title: finding.finding_title,
                            status: finding.status,
                            group_id: progressFile.group_id,
                            completion_time: finding.completion_time
                        });
                    });
                }

                // Collect active agents
                if (progressFile.assigned_agent && progressFile.status === 'in-progress') {
                    const currentFinding = progressFile.current_finding;
                    activeAgents.push({
                        agent_id: progressFile.assigned_agent,
                        group_id: progressFile.group_id,
                        current_task: currentFinding ? currentFinding.finding_title : 'Working...',
                        finding_id: currentFinding ? currentFinding.finding_id : null,
                        finding_title: currentFinding ? currentFinding.finding_title : null,
                        file: currentFinding ? currentFinding.file : null,
                        status: progressFile.phase || 'analyzing',
                        started_at: progressFile.started_at
                    });
                }

                // Track statuses
                if (progressFile.status === 'in-progress') hasAnyInProgress = true;
                if (progressFile.status === 'failed') hasAnyFailed = true;
                if (progressFile.status !== 'completed' && progressFile.status !== 'failed') {
                    allCompleted = false;
                }
            });

            // Calculate completion metrics
            const totalFindings = allFindings.length;
            const completedCount = allFindings.filter(f => f.status === 'fixed' || f.status === 'failed').length;
            const percentComplete = totalFindings > 0 ? (completedCount / totalFindings) * 100 : 0;

            // Determine overall status
            let overallStatus = 'pending';
            if (allCompleted) {
                overallStatus = hasAnyFailed ? 'failed' : 'completed';
            } else if (hasAnyInProgress) {
                overallStatus = 'in_progress';
            }

            // Determine phase
            let phase = 'planning';
            if (hasAnyInProgress || allCompleted) {
                phase = allCompleted ? 'completion' : 'execution';
            }

            // Build stages from fix plan and update with current progress
            const stages = fixPlan.timeline.stages.map(stage => {
                // Check if all groups in this stage are completed
                const groupStatuses = stage.groups.map(groupId => {
                    const progressFile = progressDataArray.find(p => p.group_id === groupId);
                    return progressFile ? progressFile.status : 'pending';
                });

                let stageStatus = 'pending';
                if (groupStatuses.every(s => s === 'completed' || s === 'failed')) {
                    stageStatus = 'completed';
                } else if (groupStatuses.some(s => s === 'in-progress')) {
                    stageStatus = 'in-progress';
                }

                return {
                    stage: stage.stage,
                    status: stageStatus,
                    groups: stage.groups,
                    execution_mode: stage.execution_mode
                };
            });

            // Get earliest start time
            const startTimes = progressDataArray
                .map(p => p.started_at)
                .filter(t => t)
                .map(t => new Date(t).getTime());
            const startTime = startTimes.length > 0 ? new Date(Math.min(...startTimes)).toISOString() : null;

            // Find current stage
            const currentStageObj = stages.find(s => s.status === 'in-progress') || stages.find(s => s.status === 'pending');
            const currentStage = currentStageObj ? currentStageObj.stage : stages.length;

            return {
                fix_session_id: fixPlan.fix_session_id,
                review_id: fixPlan.review_id,
                status: overallStatus,
                phase: phase,
                start_time: startTime,
                total_findings: totalFindings,
                current_stage: currentStage,
                total_stages: fixPlan.timeline.stages.length,
                percent_complete: percentComplete,
                fixes: allFindings,
                active_agents: activeAgents,
                stages: stages
            };
        }

        function updateFixStatus(progressData) {
            const fixPhaseBadge = document.getElementById('fixPhaseBadge');
            const planningPhase = document.getElementById('planningPhase');
            const executionPhase = document.getElementById('executionPhase');
            const stageTimeline = document.getElementById('stageTimeline');

            // Update phase badge
            const phase = progressData.phase || 'planning';
            fixPhaseBadge.textContent = phase.toUpperCase();
            fixPhaseBadge.className = `phase-badge phase-${phase}`;

            // Update stage timeline (show if stages exist, regardless of phase)
            updateStageTimeline(progressData);

            // Show appropriate phase UI
            if (phase === 'planning') {
                planningPhase.style.display = 'block';
                executionPhase.style.display = 'none';
            } else if (phase === 'execution' || phase === 'completion') {
                planningPhase.style.display = 'none';
                executionPhase.style.display = 'block';

                // Update progress bar
                const progressFill = document.getElementById('fixProgressFill');
                const progressText = document.getElementById('fixProgressText');
                const percentComplete = progressData.percent_complete || 0;
                progressFill.style.width = `${percentComplete}%`;

                const completedCount = progressData.fixes?.filter(f => f.status === 'fixed' || f.status === 'failed').length || 0;
                const totalCount = progressData.total_findings || 0;
                const currentStage = progressData.current_stage || 1;
                const totalStages = progressData.total_stages || 1;

                // Format start time
                let startTimeText = '';
                if (progressData.start_time) {
                    const startTime = new Date(progressData.start_time);
                    const elapsed = Math.floor((Date.now() - startTime.getTime()) / 1000 / 60); // minutes
                    startTimeText = ` • Started ${startTime.toLocaleTimeString()} (${elapsed}m ago)`;
                }

                progressText.textContent = `Stage ${currentStage}/${totalStages}: ${completedCount}/${totalCount} findings completed (${percentComplete.toFixed(1)}%)${startTimeText}`;

                // Update active groups
                updateActiveGroups(progressData);

                // Update active agents
                updateActiveAgents(progressData);
            }
        }

        function updateStageTimeline(progressData) {
            const stageTimeline = document.getElementById('stageTimeline');
            const stages = progressData.stages || [];

            if (stages.length === 0) {
                stageTimeline.style.display = 'none';
                stageTimeline.innerHTML = '';
                return;
            }

            // Show timeline when stages are available
            stageTimeline.style.display = 'flex';
            stageTimeline.innerHTML = stages.map(stage => `
                <div class="stage-item ${stage.status}">
                    <div class="stage-number">Stage ${stage.stage}</div>
                    <div class="stage-mode">${stage.execution_mode === 'parallel' ? '⚡ Parallel' : '➡️ Serial'}</div>
                    <div class="stage-groups">${stage.groups.length} group${stage.groups.length !== 1 ? 's' : ''}</div>
                </div>
            `).join('');
        }

        function updateActiveGroups(progressData) {
            const activeGroupsList = document.getElementById('activeGroupsList');
            const stages = progressData.stages || [];
            const activeStage = stages.find(s => s.status === 'in-progress');

            if (!activeStage) {
                activeGroupsList.innerHTML = '';
                return;
            }

            // Get fixes for groups in active stage
            const groupFixes = {};
            progressData.fixes?.forEach(fix => {
                if (fix.group_id && activeStage.groups.includes(fix.group_id)) {
                    if (!groupFixes[fix.group_id]) {
                        groupFixes[fix.group_id] = [];
                    }
                    groupFixes[fix.group_id].push(fix);
                }
            });

            const groupCards = activeStage.groups.map(groupId => {
                const fixes = groupFixes[groupId] || [];
                const inProgressCount = fixes.filter(f => f.status === 'in-progress').length;
                const completedCount = fixes.filter(f => f.status === 'fixed' || f.status === 'failed').length;

                // Get in-progress finding titles
                const inProgressFindings = fixes
                    .filter(f => f.status === 'in-progress')
                    .map(f => f.finding_title)
                    .filter(title => title);

                const inProgressText = inProgressFindings.length > 0
                    ? `<div class="group-active-items">🔧 ${inProgressFindings.join(', ')}</div>`
                    : '';

                return `
                    <div class="active-group-card">
                        <div class="group-header">
                            <div class="group-id">${groupId}</div>
                            <div class="group-status">${inProgressCount > 0 ? 'In Progress' : 'Pending'}</div>
                        </div>
                        <div class="group-findings">${completedCount}/${fixes.length} findings completed</div>
                        ${inProgressText}
                    </div>
                `;
            }).join('');

            activeGroupsList.innerHTML = groupCards || '';
        }

        function getAgentStatusIcon(status) {
            const icons = {
                'analyzing': '🔍',
                'fixing': '🔧',
                'testing': '🧪',
                'committing': '💾'
            };
            return icons[status] || '⚡';
        }

        function updateActiveAgents(progressData) {
            const activeAgentsList = document.getElementById('activeAgentsList');

            if (!progressData.active_agents || progressData.active_agents.length === 0) {
                activeAgentsList.innerHTML = '';
                return;
            }

            activeAgentsList.innerHTML = '<h4 style="margin-bottom: 10px;">Active Agents:</h4>' +
                progressData.active_agents.map(agent => {
                    const statusIcon = getAgentStatusIcon(agent.status);
                    const statusText = agent.status ? agent.status.charAt(0).toUpperCase() + agent.status.slice(1) : '';
                    const findingTitle = agent.finding_title || agent.finding_id || '';

                    // Render flow control steps if available
                    const flowControlHtml = agent.flow_control && agent.flow_control.steps && agent.flow_control.steps.length > 0
                        ? `<div class="agent-flow-control">${renderFlowControlSteps(agent.flow_control)}</div>`
                        : '';

                    return `
                        <div class="active-agent-item">
                            <div class="agent-status">
                                ${statusIcon} ${agent.agent_id} (${agent.group_id || 'unknown'})
                                ${statusText ? `<span class="agent-status-badge">${statusText}</span>` : ''}
                            </div>
                            <div class="agent-task">${agent.current_task || findingTitle || 'Initializing...'}</div>
                            ${agent.file ? `<div class="agent-file">📄 ${agent.file}</div>` : ''}
                            ${flowControlHtml}
                        </div>
                    `;
                }).join('');
        }

        function renderFlowControlSteps(flowControl) {
            if (!flowControl || !flowControl.implementation_approach || flowControl.implementation_approach.length === 0) {
                return '';
            }

            const stepsHtml = flowControl.implementation_approach.map(step => {
                let stepIcon = '';
                let stepClass = '';

                if (step.status === 'completed') {
                    stepIcon = '✅';
                    stepClass = 'flow-step-completed';
                } else if (step.status === 'in-progress') {
                    stepIcon = '⏳';
                    stepClass = 'flow-step-in-progress';
                } else if (step.status === 'failed') {
                    stepIcon = '❌';
                    stepClass = 'flow-step-failed';
                } else {
                    stepIcon = '⏸';
                    stepClass = 'flow-step-pending';
                }

                // Format step name: "analyze_context" -> "Analyze Context"
                const stepName = step.action || step.step.split('_').map(word =>
                    word.charAt(0).toUpperCase() + word.slice(1)
                ).join(' ');

                return `
                    <div class="flow-step ${stepClass}">
                        <span class="flow-step-icon">${stepIcon}</span>
                        <span class="flow-step-name">${stepName}</span>
                    </div>
                `;
            }).join('');

            return `
                <div class="flow-control-container">
                    <div class="flow-control-header">Progress Steps:</div>
                    <div class="flow-steps">${stepsHtml}</div>
                </div>
            `;
        }

        function markFindingAsFixed(findingId) {
            const finding = allFindings.find(f => f.id === findingId);
            if (finding) {
                finding.fix_status = 'fixed';
                renderFindings(); // Re-render to show fix badge
            }
        }

        function toggleFixProgress() {
            fixProgressCollapsed = !fixProgressCollapsed;
            const section = document.getElementById('fixProgressSection');
            section.classList.toggle('collapsed', fixProgressCollapsed);
        }

        // History drawer functions
        function openHistoryDrawer() {
            document.getElementById('historyDrawer').classList.add('active');
            document.getElementById('historyDrawerOverlay').classList.add('active');
            loadFixHistory();
        }

        function closeHistoryDrawer() {
            document.getElementById('historyDrawer').classList.remove('active');
            document.getElementById('historyDrawerOverlay').classList.remove('active');
        }

        async function loadFixHistory() {
            try {
                const response = await fetch('./fixes/fix-history.json');
                if (!response.ok) throw new Error('Fix history not found');

                const historyData = await response.json();
                renderFixHistory(historyData);
            } catch (error) {
                console.error('Error loading fix history:', error);
                document.getElementById('historyTimeline').innerHTML = `
                    <div class="empty-state">
                        <div class="empty-state-icon">📜</div>
                        <p>No fix history available</p>
                    </div>
                `;
            }
        }

        function renderFixHistory(historyData) {
            const timeline = document.getElementById('historyTimeline');

            if (!historyData.sessions || historyData.sessions.length === 0) {
                timeline.innerHTML = `
                    <div class="empty-state">
                        <div class="empty-state-icon">📜</div>
                        <p>No fix sessions yet</p>
                    </div>
                `;
                return;
            }

            timeline.innerHTML = historyData.sessions.map(session => {
                const timestamp = new Date(session.timestamp).toLocaleString();
                const statusEmoji = session.status === 'completed' ? '✅' :
                                   session.status === 'failed' ? '❌' : '⏳';

                return `
                    <div class="history-item">
                        <div class="history-header">
                            <span class="history-status">${statusEmoji} ${session.status}</span>
                            <span class="history-time">${timestamp}</span>
                        </div>
                        <div class="history-details">
                            <div><strong>Session:</strong> ${session.fix_session_id}</div>
                            <div><strong>Findings:</strong> ${session.findings_count} issues</div>
                            <div><strong>Fixed:</strong> ${session.fixed_count || 0} issues</div>
                            <div><strong>Failed:</strong> ${session.failed_count || 0} issues</div>
                        </div>
                    </div>
                `;
            }).join('');
        }

        // 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' ? '☀️' : '🌙';
        }

        // Polling mechanism
        function startPolling() {
            loadProgress();
            pollingInterval = setInterval(() => {
                loadProgress();
            }, 5000); // Poll every 5 seconds
        }

        function stopPolling() {
            if (pollingInterval) {
                clearInterval(pollingInterval);
                pollingInterval = null;
            }
        }

        // Load progress from review-progress.json
        async function loadProgress() {
            try {
                const response = await fetch('./review-progress.json');
                if (!response.ok) throw new Error('Progress file not found');

                const progress = await response.json();

                // ✨ NEW: Load available dimensions incrementally and get actual count
                const loadedCount = await loadAvailableDimensions();

                // ✨ NEW: Update progress UI with actual file count
                updateProgressUI(progress, loadedCount);

                // If complete, stop polling
                if (progress.phase === 'complete') {
                    stopPolling();
                }
            } catch (error) {
                console.error('Error loading progress:', error);
            }
        }

        // ✨ NEW: Load all available dimension files (even if review not complete)
        async function loadAvailableDimensions() {
            try {
                // Load review state to get expected dimensions
                const stateResponse = await fetch('./review-state.json');
                if (!stateResponse.ok) return;

                reviewState = await stateResponse.json();
                document.getElementById('sessionId').textContent = reviewState.session_id;

                // Try to load all expected dimensions
                const allDimensions = reviewState.metadata?.dimensions ||
                                     Object.keys(dimensionConfig);

                const dimensionPromises = allDimensions.map(dim =>
                    fetch(`./dimensions/${dim}.json`)
                        .then(r => {
                            if (r.ok) return r.json();
                            return null; // Dimension not ready yet
                        })
                        .catch(err => {
                            // Silently skip dimensions that don't exist yet
                            return null;
                        })
                );

                const dimensions = await Promise.all(dimensionPromises);

                // Aggregate findings from completed dimensions
                allFindings = [];
                const loadedDimensions = [];
                const severityCounts = { critical: 0, high: 0, medium: 0, low: 0 };

                dimensions.forEach(dim => {
                    if (dim) {
                        // Handle both array and object formats
                        const dimData = Array.isArray(dim) ? dim[0] : dim;

                        if (dimData && dimData.findings) {
                            loadedDimensions.push(dimData.dimension);

                            // Aggregate findings
                            allFindings.push(...dimData.findings.map(f => ({
                                ...f,
                                dimension: dimData.dimension
                            })));

                            // Aggregate severity counts
                            if (dimData.summary) {
                                severityCounts.critical += dimData.summary.critical || 0;
                                severityCounts.high += dimData.summary.high || 0;
                                severityCounts.medium += dimData.summary.medium || 0;
                                severityCounts.low += dimData.summary.low || 0;
                            }
                        }
                    }
                });

                // Update severity counts with real data
                if (loadedDimensions.length > 0) {
                    updateSeverityCounts(severityCounts);
                    updateDimensionSummary();
                    renderFindings();
                }

                // ✨ NEW: Return loaded count for progress calculation
                return {
                    loaded: loadedDimensions.length,
                    total: allDimensions.length,
                    findings: allFindings.length
                };
            } catch (error) {
                console.error('Error loading available dimensions:', error);
                return { loaded: 0, total: 7, findings: 0 };
            }
        }

        // Update progress UI
        function updateProgressUI(progress, loadedCount) {
            document.getElementById('reviewId').textContent = progress.review_id || 'N/A';
            document.getElementById('lastUpdate').textContent = new Date(progress.last_update).toLocaleString();

            const phaseBadge = document.getElementById('phaseBadge');
            phaseBadge.textContent = progress.phase.toUpperCase();
            phaseBadge.className = `phase-badge phase-${progress.phase}`;

            let percentComplete = 0;
            let progressText = '';

            // ✨ NEW: Calculate progress based on actual loaded dimension files
            if (loadedCount && loadedCount.total > 0) {
                percentComplete = Math.round((loadedCount.loaded / loadedCount.total) * 100);

                if (progress.phase === 'parallel' || progress.phase === 'aggregate') {
                    progressText = `Parallel Review: ${loadedCount.loaded}/${loadedCount.total} dimensions completed`;
                    if (loadedCount.findings > 0) {
                        progressText += ` • ${loadedCount.findings} finding${loadedCount.findings !== 1 ? 's' : ''} discovered`;
                    }
                } else if (progress.phase === 'iterate' && progress.progress.deep_dive) {
                    percentComplete = progress.progress.deep_dive.percent_complete;
                    progressText = `Deep-Dive: ${progress.progress.deep_dive.analyzed}/${progress.progress.deep_dive.total_findings} findings analyzed`;
                } else if (progress.phase === 'complete') {
                    percentComplete = 100;
                    progressText = `Review Complete • ${loadedCount.findings} total finding${loadedCount.findings !== 1 ? 's' : ''}`;
                }
            } else {
                // Fallback to original logic if loadedCount not available
                if (progress.progress.parallel_review) {
                    percentComplete = progress.progress.parallel_review.percent_complete;
                    progressText = `Parallel Review: ${progress.progress.parallel_review.completed}/${progress.progress.parallel_review.total_dimensions} dimensions`;
                }

                if (progress.progress.deep_dive) {
                    percentComplete = progress.progress.deep_dive.percent_complete;
                    progressText = `Deep-Dive: ${progress.progress.deep_dive.analyzed}/${progress.progress.deep_dive.total_findings} findings`;
                }

                if (progress.phase === 'complete') {
                    percentComplete = 100;
                    progressText = 'Review Complete';
                }
            }

            document.getElementById('progressFill').style.width = `${percentComplete}%`;
            document.getElementById('progressText').textContent = progressText;
        }

        // Load final results (now delegates to loadAvailableDimensions)
        async function loadFinalResults() {
            // ✨ NEW: This function now just ensures one final load
            // since loadAvailableDimensions() handles all the heavy lifting
            await loadAvailableDimensions();
        }

        // Update severity counts
        function updateSeverityCounts(distribution) {
            document.getElementById('criticalCount').textContent = distribution.critical || 0;
            document.getElementById('highCount').textContent = distribution.high || 0;
            document.getElementById('mediumCount').textContent = distribution.medium || 0;
            document.getElementById('lowCount').textContent = distribution.low || 0;
        }

        // Dimension summary table configuration
        const dimensionConfig = {
            'security': { icon: '🔒', label: 'Security' },
            'architecture': { icon: '🏛', label: 'Architecture' },
            'quality': { icon: '✅', label: 'Quality' },
            'action-items': { icon: '📋', label: 'Action-Items' },
            'performance': { icon: '⚡', label: 'Performance' },
            'maintainability': { icon: '🔧', label: 'Maintainability' },
            'best-practices': { icon: '📚', label: 'Best-Practices' }
        };

        // Update dimension summary table
        function updateDimensionSummary() {
            const tbody = document.getElementById('dimensionSummaryBody');
            if (!tbody) return;

            // Get all dimension names from config
            const dimensions = Object.keys(dimensionConfig);

            // Calculate counts per dimension
            const dimensionStats = {};
            dimensions.forEach(dim => {
                dimensionStats[dim] = { critical: 0, high: 0, medium: 0, low: 0, total: 0, reviewed: false };
            });

            // Aggregate findings by dimension
            allFindings.forEach(finding => {
                const dim = finding.dimension;
                if (dimensionStats[dim]) {
                    const severity = finding.severity.toLowerCase();
                    if (dimensionStats[dim][severity] !== undefined) {
                        dimensionStats[dim][severity]++;
                    }
                    dimensionStats[dim].total++;
                    // ✨ NEW: Mark as reviewed if we have findings from this dimension
                    dimensionStats[dim].reviewed = true;
                }
            });

            // Also check reviewed status from reviewState (backward compatibility)
            if (reviewState && reviewState.dimensions_reviewed) {
                reviewState.dimensions_reviewed.forEach(dim => {
                    if (dimensionStats[dim]) {
                        dimensionStats[dim].reviewed = true;
                    }
                });
            }

            // Generate table rows
            const rows = dimensions.map(dim => {
                const config = dimensionConfig[dim];
                const stats = dimensionStats[dim];
                const hasFindings = stats.total > 0;

                // Create count badge with appropriate styling
                const createCountBadge = (count, severity) => {
                    const zeroClass = count === 0 ? ' zero' : '';
                    return `<span class="count-badge ${severity}${zeroClass}">${count}</span>`;
                };

                // ✨ NEW: Enhanced status indicator with 3 states
                let statusClass, statusIcon, statusTooltip;
                if (stats.reviewed && hasFindings) {
                    statusClass = 'reviewed';
                    statusIcon = '✓';
                    statusTooltip = 'Completed';
                } else if (stats.reviewed && !hasFindings) {
                    statusClass = 'reviewed';
                    statusIcon = '✓';
                    statusTooltip = 'Completed (no findings)';
                } else {
                    statusClass = 'pending';
                    statusIcon = '⏳';
                    statusTooltip = 'Processing...';
                }

                return `
                    <tr onclick="filterByDimension('${dim}')" style="cursor: pointer;">
                        <td>
                            <div class="dimension-name">
                                <div class="dimension-icon ${dim}">${config.icon}</div>
                                <span>${config.label}</span>
                            </div>
                        </td>
                        <td>${createCountBadge(stats.critical, 'critical')}</td>
                        <td>${createCountBadge(stats.high, 'high')}</td>
                        <td>${createCountBadge(stats.medium, 'medium')}</td>
                        <td>${createCountBadge(stats.low, 'low')}</td>
                        <td><span class="count-badge total">${stats.total}</span></td>
                        <td><span class="status-indicator ${statusClass}" title="${statusTooltip}">${statusIcon}</span></td>
                    </tr>
                `;
            }).join('');

            tbody.innerHTML = rows;
        }

        // Filter functions
        function filterByDimension(dimension) {
            currentFilters.dimension = dimension;

            // Update tab UI
            document.querySelectorAll('.tab').forEach(tab => {
                tab.classList.toggle('active', tab.dataset.dimension === dimension);
            });

            applyFilters();
        }

        function setupSearch() {
            const searchInput = document.getElementById('searchInput');
            searchInput.addEventListener('input', (e) => {
                currentFilters.search = e.target.value.toLowerCase();
                applyFilters();
            });
        }

        function applyFilters() {
            filteredFindings = allFindings.filter(finding => {
                // Dimension filter
                if (currentFilters.dimension !== 'all' && finding.dimension !== currentFilters.dimension) {
                    return false;
                }

                // ✨ NEW: Multi-select severity filter
                if (currentFilters.severities.size > 0) {
                    if (!currentFilters.severities.has(finding.severity.toLowerCase())) {
                        return false;
                    }
                }

                // Search filter
                if (currentFilters.search) {
                    const searchText = `${finding.title} ${finding.description} ${finding.file} ${finding.category || ''}`.toLowerCase();
                    if (!searchText.includes(currentFilters.search)) {
                        return false;
                    }
                }

                return true;
            });

            // Auto-sort after filtering
            sortFindings();
        }

        // ✨ UPDATED: Sort findings with order support
        function sortFindings() {
            const sortBy = document.getElementById('sortSelect').value;
            sortConfig.field = sortBy;

            const severityOrder = { critical: 0, high: 1, medium: 2, low: 3 };

            filteredFindings.sort((a, b) => {
                let comparison = 0;

                if (sortBy === 'severity') {
                    comparison = severityOrder[a.severity.toLowerCase()] - severityOrder[b.severity.toLowerCase()];
                } else if (sortBy === 'dimension') {
                    comparison = a.dimension.localeCompare(b.dimension);
                } else if (sortBy === 'file') {
                    comparison = a.file.localeCompare(b.file);
                } else if (sortBy === 'title') {
                    comparison = a.title.localeCompare(b.title);
                }

                // ✨ NEW: Apply sort order (asc/desc)
                return sortConfig.order === 'asc' ? comparison : -comparison;
            });

            renderFindings();
        }

        // Render findings list
        function renderFindings() {
            const container = document.getElementById('findingsList');
            document.getElementById('findingsCount').textContent = `(${filteredFindings.length})`;

            if (filteredFindings.length === 0) {
                container.innerHTML = `
                    <div class="empty-state">
                        <div class="empty-state-icon">✨</div>
                        <p>No findings match your filters</p>
                    </div>
                `;
                return;
            }

            container.innerHTML = filteredFindings.map(finding => {
                // Determine fix status badge
                const fixStatusBadge = finding.fix_status ?
                    `<span class="fix-status-badge status-${finding.fix_status}">
                        ${finding.fix_status === 'pending' ? '⏳ Pending' :
                          finding.fix_status === 'in-progress' ? '⚡ In Progress' :
                          finding.fix_status === 'fixed' ? '✅ Fixed' :
                          finding.fix_status === 'failed' ? '❌ Failed' : ''}
                    </span>` : '';

                return `
                    <div class="finding-item ${finding.severity}" onclick='showFindingDetail(${JSON.stringify(finding).replace(/'/g, "\\'")})'  style="display: flex; gap: 12px;">
                        <input type="checkbox"
                               class="finding-checkbox"
                               data-finding-id="${finding.id}"
                               onclick='toggleFindingSelection("${finding.id}", event)'
                               ${selectedFindings.has(finding.id) ? 'checked' : ''}>
                        <div style="flex: 1;">
                            <div class="finding-header">
                                <div class="finding-title">${finding.title}</div>
                                <div class="finding-badges">
                                    <span class="severity-badge ${finding.severity}">${finding.severity}</span>
                                    <span class="dimension-badge">${finding.dimension}</span>
                                </div>
                            </div>
                            <div class="finding-file">📄 ${finding.file}:${finding.line}</div>
                            <div class="finding-description">${finding.description.substring(0, 200)}${finding.description.length > 200 ? '...' : ''}</div>
                            ${fixStatusBadge}
                        </div>
                    </div>
                `;
            }).join('');
        }

        // Show finding detail in drawer
        function showFindingDetail(finding) {
            const drawer = document.getElementById('findingDrawer');
            const overlay = document.getElementById('drawerOverlay');
            const content = document.getElementById('drawerContent');

            document.getElementById('drawerTitle').textContent = finding.title;

            content.innerHTML = `
                <div class="drawer-section">
                    <div style="display: flex; gap: 10px; margin-bottom: 15px;">
                        <span class="severity-badge ${finding.severity}">${finding.severity}</span>
                        <span class="dimension-badge">${finding.dimension}</span>
                    </div>
                </div>

                <div class="drawer-section">
                    <div class="drawer-section-title">📄 Location</div>
                    <div class="metadata-grid">
                        <div class="metadata-item">
                            <div class="metadata-label">File</div>
                            <div class="metadata-value" style="font-family: monospace; font-size: 0.85rem;">${finding.file}</div>
                        </div>
                        <div class="metadata-item">
                            <div class="metadata-label">Line</div>
                            <div class="metadata-value">${finding.line}</div>
                        </div>
                        ${finding.category ? `
                        <div class="metadata-item">
                            <div class="metadata-label">Category</div>
                            <div class="metadata-value">${finding.category}</div>
                        </div>
                        ` : ''}
                    </div>
                </div>

                <div class="drawer-section">
                    <div class="drawer-section-title">📝 Description</div>
                    <p style="line-height: 1.8;">${finding.description}</p>
                </div>

                ${finding.snippet ? `
                <div class="drawer-section">
                    <div class="drawer-section-title">💻 Code Snippet</div>
                    <div class="code-snippet">${escapeHtml(finding.snippet)}</div>
                </div>
                ` : ''}

                <div class="drawer-section">
                    <div class="drawer-section-title">✅ Recommendation</div>
                    <div class="recommendation-box">
                        ${finding.recommendation}
                    </div>
                </div>

                ${finding.impact ? `
                <div class="drawer-section">
                    <div class="drawer-section-title">⚠️ Impact</div>
                    <p style="line-height: 1.8;">${finding.impact}</p>
                </div>
                ` : ''}

                ${finding.references && finding.references.length > 0 ? `
                <div class="drawer-section">
                    <div class="drawer-section-title">🔗 References</div>
                    <ul class="reference-list">
                        ${finding.references.map(ref => {
                            const isUrl = ref.startsWith('http');
                            return `<li>${isUrl ? `<a href="${ref}" target="_blank">${ref}</a>` : ref}</li>`;
                        }).join('')}
                    </ul>
                </div>
                ` : ''}

                ${finding.metadata ? `
                <div class="drawer-section">
                    <div class="drawer-section-title">ℹ️ Metadata</div>
                    <div class="metadata-grid">
                        ${finding.metadata.cwe_id ? `
                        <div class="metadata-item">
                            <div class="metadata-label">CWE ID</div>
                            <div class="metadata-value">${finding.metadata.cwe_id}</div>
                        </div>
                        ` : ''}
                        ${finding.metadata.owasp_category ? `
                        <div class="metadata-item">
                            <div class="metadata-label">OWASP Category</div>
                            <div class="metadata-value">${finding.metadata.owasp_category}</div>
                        </div>
                        ` : ''}
                        ${finding.metadata.pattern_type ? `
                        <div class="metadata-item">
                            <div class="metadata-label">Pattern Type</div>
                            <div class="metadata-value">${finding.metadata.pattern_type}</div>
                        </div>
                        ` : ''}
                        ${finding.metadata.complexity_score ? `
                        <div class="metadata-item">
                            <div class="metadata-label">Complexity Score</div>
                            <div class="metadata-value">${finding.metadata.complexity_score}</div>
                        </div>
                        ` : ''}
                    </div>
                </div>
                ` : ''}
            `;

            drawer.classList.add('open');
            overlay.classList.add('show');
        }

        function closeDrawer() {
            document.getElementById('findingDrawer').classList.remove('open');
            document.getElementById('drawerOverlay').classList.remove('show');
        }

        function escapeHtml(text) {
            const map = {
                '&': '&amp;',
                '<': '&lt;',
                '>': '&gt;',
                '"': '&quot;',
                "'": '&#039;'
            };
            return text.replace(/[&<>"']/g, m => map[m]);
        }

        // Export to Markdown
        function exportToMarkdown() {
            if (!reviewState) {
                alert('Review data not yet loaded. Please wait.');
                return;
            }

            let markdown = `# Code Review Report\n\n`;
            markdown += `**Session**: ${reviewState.session_id}\n`;
            markdown += `**Review ID**: ${reviewState.review_id}\n`;
            markdown += `**Date**: ${new Date().toLocaleDateString()}\n`;
            markdown += `**Dimensions**: ${reviewState.dimensions_reviewed.join(', ')}\n\n`;

            markdown += `## Summary\n\n`;
            markdown += `- **Total Findings**: ${allFindings.length}\n`;
            markdown += `- **Critical**: ${reviewState.severity_distribution.critical}\n`;
            markdown += `- **High**: ${reviewState.severity_distribution.high}\n`;
            markdown += `- **Medium**: ${reviewState.severity_distribution.medium}\n`;
            markdown += `- **Low**: ${reviewState.severity_distribution.low}\n\n`;

            // Group by dimension
            reviewState.dimensions_reviewed.forEach(dim => {
                const dimFindings = allFindings.filter(f => f.dimension === dim);
                if (dimFindings.length === 0) return;

                markdown += `## ${dim.charAt(0).toUpperCase() + dim.slice(1)} (${dimFindings.length} findings)\n\n`;

                dimFindings.forEach(finding => {
                    markdown += `### ${finding.title}\n\n`;
                    markdown += `**Severity**: ${finding.severity}  \n`;
                    markdown += `**File**: \`${finding.file}:${finding.line}\`  \n`;
                    markdown += `**Category**: ${finding.category || 'N/A'}  \n\n`;
                    markdown += `${finding.description}\n\n`;
                    markdown += `**Recommendation**: ${finding.recommendation}\n\n`;
                    if (finding.impact) {
                        markdown += `**Impact**: ${finding.impact}\n\n`;
                    }
                    markdown += `---\n\n`;
                });
            });

            // Download
            const blob = new Blob([markdown], { type: 'text/markdown' });
            const url = URL.createObjectURL(blob);
            const a = document.createElement('a');
            const filename = `review-report-${reviewState.review_id}.md`;
            a.download = filename;
            a.click();
            URL.revokeObjectURL(url);

            // ✨ Show export path notification with session directory recommendation
            const reviewDir = window.location.pathname.replace('/dashboard.html', '').replace('/.review/dashboard.html', '/.review');
            // Extract absolute path from file:// URL
            const absolutePath = decodeURIComponent(window.location.pathname).replace(/^\/([A-Z]:)/, '$1');
            const sessionDir = absolutePath.replace('/.review/dashboard.html', '');
            const reportsDir = `${sessionDir}/.review/reports`;

            const notification = `
✅ Report exported successfully!

📁 File: ${filename}
📂 Browser download: Your Downloads folder

📋 Recommended Location:
   ${reportsDir}/

🔄 Move to session directory:
   # On Windows:
   move "%USERPROFILE%\\Downloads\\${filename}" "${reportsDir.replace(/\//g, '\\')}\\${filename}"

   # On Mac/Linux:
   mv ~/Downloads/${filename} ${reportsDir}/${filename}

💡 All review files in:
   ${reportsDir}/
            `.trim();

            alert(notification);
        }

        // Initialize
        document.addEventListener('DOMContentLoaded', () => {
            initTheme();
            setupSearch();
            startPolling();
            detectFixSession(); // Check for active fix sessions

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