<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>testers.ai - Test Case Manager</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <style>
        :root {
            --primary-color: #4B7BEC;
            --secondary-color: #45AEF5;
            --background-dark: #1E2337;
            --background-card: #2A2F45;
            --text-primary: #FFFFFF;
            --text-secondary: #A0A7B7;
            --header-height: 64px;
        }

        body {
            background: var(--background-dark);
            color: var(--text-primary);
            min-height: 100vh;
            margin: 0;
            padding: 0;
            display: flex;
            flex-direction: column;
        }

        .branded-header {
            height: var(--header-height);
            background: var(--background-card);
            border-bottom: 1px solid rgba(255, 255, 255, 0.1);
            padding: 0 1.5rem;
            display: flex;
            align-items: center;
            justify-content: space-between;
        }

        .container {
            flex: 1;
            max-height: calc(100vh - var(--header-height));
            overflow: hidden;
        }

        .test-case-grid {
            display: grid;
            grid-template-columns: 300px 1fr;
            gap: 1rem;
            height: calc(100vh - var(--header-height) - 2rem);
            min-height: 0;
            padding: 1rem;
        }
        
        .filters-panel {
            background: var(--background-card);
            border-radius: 0.5rem;
            padding: 1rem;
            display: flex;
            flex-direction: column;
            gap: 1rem;
            height: 100%;
            overflow-y: auto;
            border: 1px solid rgba(255, 255, 255, 0.1);
        }
        
        .main-panel {
            display: grid;
            grid-template-columns: 350px 1fr;
            gap: 1rem;
            height: 100%;
            min-height: 0; /* Needed for nested grid scrolling */
        }

        .test-list-panel {
            background: var(--background-card);
            border-radius: 0.5rem;
            padding: 1rem;
            height: 100%;
            overflow-y: auto;
            border: 1px solid rgba(255, 255, 255, 0.1);
            display: flex;
            flex-direction: column;
            min-height: 0; /* Needed for flex container scrolling */
        }
        
        .test-details-panel {
            background: var(--background-card);
            border-radius: 0.5rem;
            padding: 1rem;
            height: 100%;
            overflow-y: auto;
            border: 1px solid rgba(255, 255, 255, 0.1);
            display: flex;
            flex-direction: column;
            min-height: 0; /* Needed for flex container scrolling */
        }

        .test-case-list {
            flex: 1;
            overflow-y: auto;
            padding-right: 0.5rem;
        }

        .test-case-details {
            flex: 1;
            overflow-y: auto;
            padding-right: 0.5rem;
        }

        .test-case-card {
            background: var(--background-card);
            border: 1px solid rgba(255, 255, 255, 0.1);
            border-radius: 0.5rem;
            padding: 1rem;
            cursor: pointer;
            transition: all 0.2s;
        }

        .test-case-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
        }

        .test-case-card.edge-category {
            border: 2px solid var(--primary-color);
            background: linear-gradient(to bottom right, var(--background-card), rgba(75, 123, 236, 0.1));
        }

        .profile-section {
            display: flex;
            align-items: center;
            gap: 1rem;
            margin-bottom: 1rem;
            padding-bottom: 1rem;
            border-bottom: 1px solid rgba(255, 255, 255, 0.1);
        }

        .profile-section.edge-profile {
            background: linear-gradient(to right, rgba(75, 123, 236, 0.1), transparent);
            margin: -1rem -1rem 1rem -1rem;
            padding: 1rem;
            border-top-left-radius: 0.5rem;
            border-top-right-radius: 0.5rem;
        }

        .profile-image {
            width: 48px;
            height: 48px;
            border-radius: 50%;
            object-fit: cover;
            border: 2px solid transparent;
        }

        .edge-profile .profile-image {
            width: 64px;
            height: 64px;
            border-color: var(--primary-color);
            box-shadow: 0 0 10px rgba(75, 123, 236, 0.3);
        }

        .profile-info {
            flex: 1;
        }

        .profile-name {
            font-weight: 600;
            color: var(--text-primary);
            font-size: 1.1rem;
        }

        .edge-profile .profile-name {
            color: var(--primary-color);
            font-size: 1.25rem;
        }

        .profile-role {
            color: var(--text-secondary);
            font-size: 0.875rem;
        }

        .edge-profile .profile-role {
            color: var(--primary-color);
            opacity: 0.8;
        }

        .test-content {
            color: var(--text-secondary);
        }

        .test-header {
            display: flex;
            justify-content: space-between;
            align-items: flex-start;
            margin-bottom: 0.5rem;
        }

        .category-badge {
            display: inline-flex;
            align-items: center;
            padding: 0.25rem 0.75rem;
            border-radius: 1rem;
            font-size: 0.875rem;
            font-weight: 500;
            background: rgba(255, 255, 255, 0.1);
        }

        .category-badge.edge {
            background: rgba(75, 123, 236, 0.2);
            color: var(--primary-color);
        }

        .test-card {
            background: var(--background-dark);
            border: 1px solid rgba(255, 255, 255, 0.1);
            border-radius: 0.5rem;
            padding: 1rem;
            transition: all 0.3s ease;
            position: relative;
            height: fit-content;
            overflow: visible;
        }

        .test-header {
            display: flex;
            justify-content: space-between;
            align-items: flex-start;
            margin-bottom: 1rem;
        }

        .test-content {
            flex-grow: 1;
            margin-right: 1rem;
        }

        .tester-profile {
            display: flex;
            align-items: center;
            padding-left: 1rem;
            border-left: 1px solid rgba(255, 255, 255, 0.1);
            min-width: 120px;
        }

        .tester-profile img, .category-button img {
            width: 32px;
            height: 32px;
            border-radius: 50%;
            margin-right: 0.5rem;
        }

        .tester-name {
            color: var(--text-secondary);
            font-size: 0.875rem;
        }

        .test-card.expanded {
            grid-column: 1 / -1;
            margin-bottom: 1rem;
            height: auto;
            z-index: 1;
        }

        .test-card .check-icon {
            color: var(--primary-color);
            opacity: 0.7;
            margin-right: 0.5rem;
        }

        .test-title {
            display: flex;
            align-items: center;
            margin-bottom: 0.5rem;
        }

        .test-title-text {
            font-weight: 500;
        }

        .test-card:hover {
            border-color: var(--primary-color);
            background: rgba(75, 123, 236, 0.1);
        }

        .test-card.active {
            background: rgba(75, 123, 236, 0.2);
            border-color: var(--primary-color);
        }
        
        .filter-section {
            border-bottom: 1px solid rgba(255, 255, 255, 0.1);
            padding-bottom: 1rem;
            position: relative;
        }
        
        .filter-section:last-child {
            border-bottom: none;
        }

        .filter-section h3 {
            color: var(--text-primary);
            font-weight: 600;
            margin-bottom: 1rem;
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }
        
        .section-title {
            color: var(--primary-color);
            font-weight: 600;
            margin-bottom: 1rem;
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }
        
        .section-title::after {
            content: "?";
            display: inline-flex;
            align-items: center;
            justify-content: center;
            width: 18px;
            height: 18px;
            border-radius: 50%;
            background: var(--primary-color);
            color: white;
            font-size: 12px;
            cursor: help;
        }
        
        .section-title[data-tooltip]::after {
            position: relative;
        }
        
        .section-title[data-tooltip]:hover::before {
            content: attr(data-tooltip);
            position: absolute;
            top: -8px;
            transform: translateY(-100%);
            background: var(--background-dark);
            color: var(--text-primary);
            padding: 0.5rem;
            border-radius: 0.25rem;
            font-size: 0.875rem;
            white-space: nowrap;
            z-index: 10;
            border: 1px solid var(--primary-color);
            box-shadow: 0 2px 4px rgba(0,0,0,0.2);
        }

        .app-button {
            background: var(--background-dark);
            color: var(--text-primary);
            padding: 0.5rem 1rem;
            border-radius: 0.5rem;
            border: 1px solid rgba(255, 255, 255, 0.1);
            width: 100%;
            text-align: left;
            margin-bottom: 0.5rem;
            transition: all 0.2s;
        }

        .app-button:hover {
            border-color: var(--primary-color);
            background: rgba(75, 123, 236, 0.1);
        }

        .app-button.active {
            background: var(--primary-color);
            border-color: var(--primary-color);
            color: white;
        }

        .category-button {
            display: flex;
            align-items: center;
            background: var(--background-dark);
            color: var(--text-primary);
            padding: 0.5rem 1rem;
            border-radius: 0.5rem;
            border: 1px solid rgba(255, 255, 255, 0.1);
            width: 100%;
            text-align: left;
            margin-bottom: 0.5rem;
            transition: all 0.2s;
        }

        .category-button:hover {
            border-color: var(--primary-color);
            background: rgba(75, 123, 236, 0.1);
        }

        .category-button.active {
            background: var(--primary-color);
            border-color: var(--primary-color);
            color: white;
        }

        .welcome-banner {
            background: var(--background-card);
            border: 1px solid rgba(255, 255, 255, 0.1);
            color: var(--text-primary);
        }

        .btn-primary {
            background: var(--primary-color);
            color: white;
            padding: 0.75rem 1.5rem;
            border-radius: 0.5rem;
            font-weight: 500;
            transition: all 0.2s;
        }

        .btn-primary:hover {
            background: var(--secondary-color);
        }

        .search-bar {
            background: var(--background-dark);
            border: 1px solid rgba(255, 255, 255, 0.1);
            color: var(--text-primary);
            padding: 0.5rem 1rem;
            border-radius: 0.5rem;
            width: 100%;
            margin-bottom: 1rem;
        }

        .search-bar:focus {
            outline: none;
            border-color: var(--primary-color);
        }

        .test-count {
            background: rgba(255, 255, 255, 0.1);
            padding: 0.25rem 0.75rem;
            border-radius: 999px;
            font-size: 0.875rem;
            color: var(--text-secondary);
            margin-left: 0.5rem;
        }

        .editable {
            background: var(--background-dark);
            border: 1px solid rgba(255, 255, 255, 0.1);
            border-radius: 0.5rem;
            padding: 0.75rem;
            color: var(--text-primary);
            margin-bottom: 1rem;
            transition: all 0.2s;
        }

        .editable:hover {
            border-color: var(--primary-color);
        }

        .editable:focus {
            outline: none;
            border-color: var(--primary-color);
            background: rgba(75, 123, 236, 0.1);
        }

        .collapsed {
            height: 40px;
            overflow: hidden;
            transition: height 0.3s ease-out;
        }
        
        .expanded {
            height: 300px;
            transition: height 0.3s ease-in;
        }
        
        .log-toggle {
            cursor: pointer;
            user-select: none;
        }
        
        .test-case-item {
            padding: 0.75rem 1rem;
            margin-bottom: 0.5rem;
            background: rgba(255, 255, 255, 0.05);
            border-radius: 4px;
            color: var(--text-primary);
            cursor: pointer;
            transition: all 0.2s;
        }

        .test-case-item:hover {
            background: rgba(255, 255, 255, 0.1);
        }

        .test-case-item.active {
            background: var(--secondary-color);
            color: white;
        }

        .welcome-banner h1 {
            color: var(--text-primary);
        }

        .welcome-banner p {
            color: var(--text-secondary);
        }

        .section-title {
            color: var(--text-primary);
            font-size: 1.25rem;
            font-weight: 600;
            margin-bottom: 1rem;
        }

        .loading {
            position: relative;
        }
        
        .loading::after {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(30, 35, 55, 0.7);
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 1.25rem;
            color: var(--text-primary);
        }

        .test-details-grid {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 1rem;
            margin-bottom: 1rem;
        }

        .test-detail-card {
            background: rgba(255, 255, 255, 0.05);
            border-radius: 0.5rem;
            padding: 1rem;
        }

        .test-detail-label {
            color: var(--text-secondary);
            font-size: 0.875rem;
            margin-bottom: 0.5rem;
        }

        .keyboard-shortcut {
            background: rgba(255, 255, 255, 0.1);
            padding: 0.25rem 0.5rem;
            border-radius: 0.25rem;
            font-size: 0.75rem;
            color: var(--text-secondary);
            margin-left: 0.5rem;
        }

        .error-message {
            background: rgba(239, 68, 68, 0.1);
            border: 1px solid rgba(239, 68, 68, 0.2);
            color: rgb(239, 68, 68);
            padding: 1rem;
            border-radius: 0.5rem;
            margin-bottom: 1rem;
        }

        .success-message {
            background: rgba(34, 197, 94, 0.1);
            border: 1px solid rgba(34, 197, 94, 0.2);
            color: rgb(34, 197, 94);
            padding: 1rem;
            border-radius: 0.5rem;
            margin-bottom: 1rem;
        }

        .breadcrumb {
            color: var(--text-secondary);
            font-size: 0.875rem;
            margin-bottom: 0.5rem;
        }

        .breadcrumb-item {
            color: var(--text-secondary);
            text-decoration: none;
            cursor: pointer;
            transition: color 0.2s;
        }

        .breadcrumb-item:hover {
            color: var(--text-primary);
        }

        .breadcrumb-separator {
            color: var(--text-secondary);
            margin: 0 0.5rem;
            opacity: 0.5;
        }

        .test-details {
            margin-top: 1.5rem;
            padding-top: 1.5rem;
            border-top: 1px solid rgba(255, 255, 255, 0.1);
            overflow: visible;
        }

        .test-details-section {
            margin-bottom: 1.5rem;
            overflow: visible;
        }

        .test-details-section h4 {
            color: var(--primary-color);
            font-weight: 600;
            margin-bottom: 0.5rem;
        }

        .test-details-section p {
            white-space: pre-line;
            line-height: 1.6;
            color: var(--text-secondary);
        }

        .test-details-section ul {
            list-style-type: disc;
            padding-left: 1.5rem;
            margin-top: 0.5rem;
            color: var(--text-secondary);
        }

        .test-details-section li {
            margin-bottom: 0.5rem;
            line-height: 1.6;
        }

        .button-icon {
            margin-right: 0.75rem;
            width: 1.25rem;
            text-align: center;
        }

        #testCaseGrid {
            overflow: visible;
        }

        /* Add branded header styles */
        .brand-section {
            display: flex;
            align-items: center;
            gap: 1rem;
        }

        .brand-logo {
            width: 40px;
            height: 40px;
            object-fit: contain;
        }

        .brand-text {
            font-size: 1.5rem;
            font-weight: bold;
            background: linear-gradient(45deg, #4B7BEC, #3867D6);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
        }

        .header-divider {
            margin: 0 1.5rem;
            height: 24px;
            width: 1px;
            background: rgba(255, 255, 255, 0.2);
        }

        .header-title {
            font-size: 1.25rem;
            color: #e1e1e1;
            font-weight: 500;
        }

        .app-list-container {
            max-height: 250px;
            overflow-y: auto;
        }

        .categories-container {
            max-height: 500px;
            overflow-y: auto;
        }

        /* Add breadcrumb styles */
        .breadcrumbs {
            display: flex;
            align-items: center;
            gap: 0.5rem;
            padding: 0.5rem 0;
            margin-bottom: 1rem;
            font-size: 0.9rem;
            color: var(--text-secondary);
        }

        .breadcrumb-item {
            cursor: pointer;
            color: var(--text-secondary);
            transition: color 0.2s;
        }

        .breadcrumb-item:hover {
            color: var(--primary-color);
        }

        .breadcrumb-separator {
            color: var(--text-secondary);
            opacity: 0.5;
        }

        .breadcrumb-current {
            color: var(--text-primary);
            font-weight: 500;
        }
    </style>
</head>
<body>
    <div class="branded-header">
        <div class="brand-section">
            <img src="images/logo_clear.png" alt="testers.ai Logo" class="brand-logo">
            <div class="brand-text">testers.ai</div>
        </div>
        <div class="header-divider"></div>
        <div class="header-title">AI Test Case Manager</div>
    </div>
    <div class="container mx-auto px-4 py-8">
        <!-- Welcome Banner -->
        <div id="initialState" class="welcome-banner text-center py-12 rounded-lg shadow mb-8">
            <h1 class="text-4xl font-bold mb-4">AI Test Manager</h1>
            <p class="mb-8">Select your test data directory to begin exploring and managing test cases.</p>
            <button onclick="selectDirectory()" class="btn-primary">
                Select Directory
            </button>
        </div>

        <!-- Main Application View -->
        <div id="testDataView" class="hidden">
            <!-- Test Case Management Interface -->
            <div class="test-case-grid">
                <!-- Left Panel - Filters -->
                <div class="filters-panel">
                    <div class="filter-section">
                        <h3 class="section-title">Applications</h3>
                        <div id="appList" class="space-y-2 app-list-container">
                            <!-- Apps will be listed here as buttons -->
                        </div>
                    </div>
                    
                    <div class="filter-section">
                        <h3 class="section-title">Test Categories</h3>
                        <div id="categories" class="categories-container">
                            <!-- Categories will be populated here -->
                        </div>
                    </div>
                    
                    <div class="filter-section" style="display: none;">
                        <h3 class="section-title">Test Cases</h3>
                        <input type="text" id="searchInput" class="search-bar" placeholder="Search test cases..." />
                        <div id="testCaseList" class="space-y-2">
                            <!-- Test cases will be populated here -->
                        </div>
                    </div>
                </div>

                <!-- Right Panel - Test Case Details -->
                <div class="main-panel">
                    <div class="test-list-panel" id="testListPanel">
                        <div class="test-case-list">
                            <!-- Test cases will be listed here -->
                        </div>
                    </div>
                    <div class="test-details-panel" id="testDetailsPanel">
                        <div class="test-case-details">
                            <!-- Test case details will be shown here -->
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script>
        let currentDirectoryHandle = null;
        let currentCompany = null;
        let currentApp = null;
        let currentTestData = {};
        let selectedCategory = null;
        let selectedTestCase = null;
        let searchTimeout = null;
        let allCategories = {}; // Store all categories across all apps

        async function loadTestData(appPath) {
            if (!currentDirectoryHandle) return;
            
            const [company, app] = appPath ? appPath.split('/') : [null, null];
            currentApp = app;
            
            try {
                if (appPath) {
                    // Load specific app data
                    const dataHandle = await currentDirectoryHandle.getDirectoryHandle('data');
                    const companyHandle = await dataHandle.getDirectoryHandle(company);
                    const appHandle = await companyHandle.getDirectoryHandle(app);
                    
                    let mostRecentTimestamp = '';
                    let recentRunHandle = null;

                    for await (const entry of appHandle.values()) {
                        if (entry.kind === 'directory' && entry.name > mostRecentTimestamp) {
                            mostRecentTimestamp = entry.name;
                            recentRunHandle = entry;
                        }
                    }

                    if (recentRunHandle) {
                        const pagesHandle = await recentRunHandle.getDirectoryHandle('pages');
                        currentTestData = {};
                        
                        for await (const pageEntry of pagesHandle.values()) {
                            if (pageEntry.kind === 'directory') {
                                try {
                                    const aiTestsHandle = await pageEntry.getFileHandle('ai_tests.json');
                                    const pageTests = await readJsonFile(aiTestsHandle);
                                    
                                    // Merge the tests into categories
                                    Object.entries(pageTests).forEach(([category, testCases]) => {
                                        if (!currentTestData[category]) {
                                            currentTestData[category] = [];
                                        }
                                        testCases.forEach(testCase => {
                                            testCase.category = category;
                                            testCase.company = company;
                                            testCase.app = app;
                                            currentTestData[category].push(testCase);
                                        });
                                    });
                                } catch (error) {
                                    console.error(`Error reading tests for page ${pageEntry.name}:`, error);
                                }
                            }
                        }

                        // Display categories in sidebar
                        displayCategories(currentTestData);
                        
                        // Display all test cases for the app
                        const allCases = Object.values(currentTestData).flat();
                        displayAllTestCases(allCases, {
                            title: `All Test Cases for ${app}`,
                            description: `${allCases.length} test cases found across all categories`
                        });
                    }
                } else {
                    // No app selected, show all categories
                    displayCategories(allCategories);
                    if (selectedCategory) {
                        // If a category is selected, show all tests from that category across all apps
                        const allCasesInCategory = allCategories[selectedCategory] || [];
                        displayAllTestCases(allCasesInCategory, {
                            title: `All ${selectedCategory} Test Cases`,
                            description: `${allCasesInCategory.length} test cases found across all applications`
                        });
                    } else {
                        // Show all test cases
                        const allCases = Object.values(allCategories).flat();
                        displayAllTestCases(allCases, {
                            title: 'All Test Cases',
                            description: `${allCases.length} test cases found across all applications`
                        });
                    }
                }
            } catch (error) {
                console.error('Error loading test data:', error);
            }
        }

        async function scanAllTestData() {
            if (!currentDirectoryHandle) return;
            
            try {
                const dataHandle = await currentDirectoryHandle.getDirectoryHandle('data');
                allCategories = {};
                const companies = {};
                
                // Scan through all companies and apps
                for await (const companyEntry of dataHandle.values()) {
                    if (companyEntry.kind === 'directory') {
                        const companyName = companyEntry.name;
                        const companyHandle = await dataHandle.getDirectoryHandle(companyName);
                        companies[companyName] = [];
                        
                        for await (const appEntry of companyHandle.values()) {
                            if (appEntry.kind === 'directory') {
                                const appName = appEntry.name;
                                companies[companyName].push(appName);
                                let mostRecentTimestamp = '';
                                let recentRunHandle = null;

                                // Find most recent run
                                for await (const runEntry of appEntry.values()) {
                                    if (runEntry.kind === 'directory' && runEntry.name > mostRecentTimestamp) {
                                        mostRecentTimestamp = runEntry.name;
                                        recentRunHandle = runEntry;
                                    }
                                }

                                if (recentRunHandle) {
                                    try {
                                        const pagesHandle = await recentRunHandle.getDirectoryHandle('pages');
                                        
                                        for await (const pageEntry of pagesHandle.values()) {
                                            if (pageEntry.kind === 'directory') {
                                                try {
                                                    const aiTestsHandle = await pageEntry.getFileHandle('ai_tests.json');
                                                    const pageTests = await readJsonFile(aiTestsHandle);
                                                    
                                                    // Merge tests into global categories
                                                    Object.entries(pageTests).forEach(([category, testCases]) => {
                                                        if (!allCategories[category]) {
                                                            allCategories[category] = [];
                                                        }
                                                        testCases.forEach(testCase => {
                                                            testCase.category = category;
                                                            testCase.company = companyName;
                                                            testCase.app = appName;
                                                            allCategories[category].push(testCase);
                                                        });
                                                    });
                                                } catch (error) {
                                                    console.error(`Error reading tests for page ${pageEntry.name}:`, error);
                                                }
                                            }
                                        }
                                    } catch (error) {
                                        console.error(`Error processing app ${appName}:`, error);
                                    }
                                }
                            }
                        }
                    }
                }
                
                // Display apps immediately
                displayApps(companies);
                
                // Display all categories initially
                displayCategories(allCategories);
                const allCases = Object.values(allCategories).flat();
                displayAllTestCases(allCases, {
                    title: 'All Test Cases',
                    description: `${allCases.length} test cases found across all applications`
                });
                
                return companies;
                
            } catch (error) {
                console.error('Error scanning all test data:', error);
                return {};
            }
        }

        async function selectDirectory() {
            try {
                currentDirectoryHandle = await window.showDirectoryPicker();
                document.getElementById('initialState').classList.add('hidden');
                document.getElementById('testDataView').classList.remove('hidden');
                
                log('Loading companies and applications...');
                
                try {
                    const dataHandle = await currentDirectoryHandle.getDirectoryHandle('data');
                    log('Found data directory');
                    
                    // Scan all test data which will also populate the apps list
                    await scanAllTestData();
                    
                } catch (error) {
                    log('Error: Could not find "data" directory. Please ensure you selected the correct root directory.');
                    console.error('Error accessing data directory:', error);
                }
            } catch (error) {
                log(`Error picking directory: ${error.message}`);
                console.error('Error picking directory:', error);
            }
        }

        function displayApps(companies) {
            const appList = document.getElementById('appList');
            appList.innerHTML = '';
            
            Object.entries(companies).forEach(([company, apps]) => {
                if (apps.length > 0) {
                    const companyDiv = document.createElement('div');
                    companyDiv.className = 'mb-4';
                    companyDiv.innerHTML = `<div class="text-secondary mb-2">${company}</div>`;
                    
                    apps.forEach(app => {
                        const button = document.createElement('button');
                        button.className = 'app-button';
                        button.innerHTML = `
                            <i class="fas fa-square button-icon"></i>
                            ${app}
                        `;
                        button.value = `${company}/${app}`;
                        button.addEventListener('click', (e) => {
                            const isActive = button.classList.contains('active');
                            document.querySelectorAll('.app-button').forEach(b => b.classList.remove('active'));
                            if (!isActive) {
                                button.classList.add('active');
                                loadTestData(e.target.value);
                            } else {
                                // If clicking an active app button, deselect it and show all tests
                                loadTestData();
                            }
                        });
                        companyDiv.appendChild(button);
                    });
                    
                    appList.appendChild(companyDiv);
                }
            });
        }

        function displayCategories(testData) {
            const categoryList = document.getElementById('categories');
            if (!categoryList) return;
            categoryList.innerHTML = '';

            // Get categories from the object structure
            const categories = Object.keys(testData).filter(Boolean);
            
            categories.forEach(category => {
                const button = document.createElement('button');
                button.className = 'category-button';
                const categoryLower = category.toLowerCase();
                
                const categoryImage = getProfileImage({ category });
                const profileName = getProfileName({ category });
                const isSpecial = isSpecialCategory({ category });
                
                const testCount = testData[category] ? testData[category].length : 0;
                
                button.innerHTML = `
                    <img src="${categoryImage}" alt="Category Icon" onerror="this.src='data:image/svg+xml,<svg xmlns=%22http://www.w3.org/2000/svg%22 width=%2232%22 height=%2232%22 viewBox=%220 0 24 24%22><circle cx=%2212%22 cy=%228%22 r=%224%22 fill=%22%234B7BEC%22/><path d=%22M24 24H0v-3c0-4.4 3.6-8 8-8h8c4.4 0 8 3.6 8 8v3z%22 fill=%22%234B7BEC%22/></svg>';">
                    <div class="category-info">
                        <div class="category-name">${category}</div>
                        <div class="profile-name">${profileName}</div>
                        <div class="test-count">${testCount} tests</div>
                    </div>
                `;
                
                button.addEventListener('click', () => {
                    // Get test cases for this category
                    const categoryTests = testData[category] || [];
                    displayAllTestCases(categoryTests, {
                        title: `${category.replace(/_/g, ' ').replace(/\b\w/g, l => l.toUpperCase())} Tests`,
                        description: `${categoryTests.length} test cases found in the ${category} category`
                    });
                });
                
                categoryList.appendChild(button);
            });
        }

        function getProfileImage(testCase) {
            const category = testCase.category.toLowerCase();
            switch (category) {
                case 'edge':
                    return 'images/zachary.jpg';
                case 'interesting':
                    return 'images/zara.jpg';
                case 'basic':
                    return 'images/ravi.jpg';
                case 'ai_unique':
                    return 'images/akira.jpg';
                case 'search':
                    return 'images/jason.jpg';
                case 'forms':
                    return 'images/carlos.jpg';
                default:
                    return 'images/aiden.jpg';
            }
        }

        function getProfileName(testCase) {
            const category = testCase.category.toLowerCase();
            switch (category) {
                case 'edge':
                    return 'Zachary';
                case 'interesting':
                    return 'Zara';
                case 'basic':
                    return 'Ravi';
                case 'ai_unique':
                    return 'Richard';
                default:
                    return 'Aiden';
            }
        }

        function getProfileRole(testCase) {
            const category = testCase.category.toLowerCase();
            switch (category) {
                case 'edge':
                    return 'Edge Case Specialist';
                case 'interesting':
                    return 'Exploratory Test Specialist';
                case 'basic':
                    return 'Basic Test Engineer';
                case 'ai_unique':
                    return 'AI Test Specialist';
                default:
                    return 'Test Engineer';
            }
        }

        function isSpecialCategory(testCase) {
            const category = testCase.category.toLowerCase();
            return ['edge', 'interesting', 'basic', 'ai_unique'].includes(category);
        }

        async function loadTestData(appPath) {
            try {
                const response = await fetch(`/api/tests/${appPath}`);
                const data = await response.json();
                
                // Store the path for breadcrumbs
                window.currentPath = appPath;
                
                displayCategories(data);
            } catch (error) {
                console.error('Error loading test data:', error);
            }
        }

        function displayAllTestCases(cases, context) {
            const testListContainer = document.querySelector('#testListPanel .test-case-list');
            if (!testListContainer) return;

            // Store test cases with their paths
            window.currentTestCases = cases.map(testCase => ({
                ...testCase,
                path: window.currentPath
            }));

            testListContainer.innerHTML = cases.map((testCase, index) => `
                <div class="test-case-card mb-4 ${isSpecialCategory(testCase) ? 'edge-category' : ''}" 
                     data-test-index="${index}"
                     onclick="showTestCaseDetails(${index}, this)">
                    <div class="flex items-center justify-between">
                        <div class="flex-1">
                            <h3 class="font-semibold">${testCase.title}</h3>
                        </div>
                    </div>
                </div>
            `).join('');

            // Show first test case by default
            if (cases.length > 0) {
                const firstCard = testListContainer.querySelector('.test-case-card');
                if (firstCard) {
                    showTestCaseDetails(0, firstCard);
                }
            }
        }

        function getBreadcrumbsFromPath(testCase) {
            if (!testCase || !testCase.path) return null;
            
            const pathParts = testCase.path.split('/').filter(part => part);
            if (pathParts.length < 2) return null;

            return {
                company: pathParts[0],
                app: pathParts[1],
                testName: testCase.title
            };
        }

        function showTestCaseDetails(testIndex, clickedCard) {
            const testCase = window.currentTestCases[testIndex];
            if (!testCase) return;

            // Update selected card styling
            document.querySelectorAll('.test-case-card').forEach(card => card.classList.remove('selected'));
            if (clickedCard) clickedCard.classList.add('selected');

            const detailsContainer = document.querySelector('#testDetailsPanel .test-case-details');
            if (!detailsContainer) return;

            const breadcrumbs = getBreadcrumbsFromPath(testCase);
            const breadcrumbsHtml = breadcrumbs ? `
                <div class="breadcrumbs">
                    <span class="breadcrumb-item" onclick="selectCompany('${breadcrumbs.company}')">${breadcrumbs.company}</span>
                    <span class="breadcrumb-separator">/</span>
                    <span class="breadcrumb-item" onclick="loadTestData('${testCase.path}')">${breadcrumbs.app}</span>
                    <span class="breadcrumb-separator">/</span>
                    <span class="breadcrumb-current">${breadcrumbs.testName}</span>
                </div>
            ` : '';

            detailsContainer.innerHTML = `
                ${breadcrumbsHtml}
                <div class="profile-section ${isSpecialCategory(testCase) ? 'edge-profile' : ''}">
                    <img src="${getProfileImage(testCase)}" alt="Profile" class="profile-image">
                    <div>
                        <h2 class="text-xl font-bold">${getProfileName(testCase)}</h2>
                        <p class="text-sm text-gray-400">${getProfileRole(testCase)}</p>
                    </div>
                </div>

                <div class="test-details-section">
                    <div class="mb-6">
                        <h3 class="text-lg font-semibold mb-2">Test Case ID</h3>
                        <p class="text-gray-300">${testCase.id || 'N/A'}</p>
                    </div>

                    <div class="mb-6">
                        <h3 class="text-lg font-semibold mb-2">Test Case Name</h3>
                        <p class="text-gray-300">${testCase.title || 'N/A'}</p>
                    </div>

                    <div class="mb-6">
                        <h3 class="text-lg font-semibold mb-2">Validation Conditions</h3>
                        <p class="text-gray-300">${testCase.validation_conditions || 'N/A'}</p>
                    </div>

                    <div class="mb-6">
                        <h3 class="text-lg font-semibold mb-2">Test Steps</h3>
                        <p class="text-gray-300 whitespace-pre-line">${testCase.test_steps || 'N/A'}</p>
                    </div>

                    <div class="mb-6">
                        <h3 class="text-lg font-semibold mb-2">Priority Reason</h3>
                        <p class="text-gray-300">${testCase.priority_reason || 'N/A'}</p>
                    </div>

                    <div class="mb-6">
                        <h3 class="text-lg font-semibold mb-2">Test Data</h3>
                        <div class="space-y-4">
                            <div>
                                <h4 class="text-md font-semibold text-gray-400">Inputs:</h4>
                                <ul class="list-disc list-inside text-gray-300">
                                    ${testCase.data?.inputs?.length ? 
                                        testCase.data.inputs.map(input => `<li>${input}</li>`).join('') :
                                        '<li>No inputs specified</li>'
                                    }
                                </ul>
                            </div>
                            <div>
                                <h4 class="text-md font-semibold text-gray-400">Expected Outputs:</h4>
                                <ul class="list-disc list-inside text-gray-300">
                                    ${testCase.data?.expected_outputs?.length ?
                                        testCase.data.expected_outputs.map(output => `<li>${output}</li>`).join('') :
                                        '<li>No expected outputs specified</li>'
                                    }
                                </ul>
                            </div>
                            <div>
                                <h4 class="text-md font-semibold text-gray-400">Edge Cases:</h4>
                                <ul class="list-disc list-inside text-gray-300">
                                    ${testCase.data?.edge_cases?.length ?
                                        testCase.data.edge_cases.map(edge => `<li>${edge}</li>`).join('') :
                                        '<li>No edge cases specified</li>'
                                    }
                                </ul>
                            </div>
                        </div>
                    </div>
                </div>
            `;
        }

        function selectCompany(company) {
            currentCompany = company;
            // Highlight the company in the list
            document.querySelectorAll('.app-button').forEach(b => {
                if (b.textContent === company) {
                    b.classList.add('active');
                } else {
                    b.classList.remove('active');
                }
            });
            getAllTestCasesForCompany(company);
        }

        function selectCategory(category) {
            selectedCategory = category;
            
            // If an app is selected, show only that app's tests for the category
            if (currentApp) {
                const appCases = currentTestData[category] || [];
                displayAllTestCases(appCases, {
                    title: `${category.replace(/_/g, ' ').replace(/\b\w/g, l => l.toUpperCase())} Tests for ${currentApp}`,
                    description: `${appCases.length} test cases found`
                });
            } else {
                // Show all tests for this category across all apps
                const allCasesInCategory = allCategories[category] || [];
                displayAllTestCases(allCasesInCategory, {
                    title: `All ${category} Test Cases`,
                    description: `${allCasesInCategory.length} test cases found across all applications`
                });
            }
        }

        async function getAllTestCasesForCompany(company) {
            const allCases = [];
            try {
                const dataHandle = await currentDirectoryHandle.getDirectoryHandle('data');
                const companyHandle = await dataHandle.getDirectoryHandle(company);
                
                for await (const appEntry of companyHandle.values()) {
                    if (appEntry.kind === 'directory') {
                        const cases = await getTestCasesForApp(company, appEntry.name);
                        cases.forEach(testCase => {
                            testCase.company = company;
                            allCases.push(testCase);
                        });
                    }
                }

                displayAllTestCases(allCases, {
                    title: `All Test Cases for ${company}`,
                    description: `${allCases.length} test cases found across all applications`
                });
            } catch (error) {
                console.error('Error getting test cases:', error);
            }
        }

        async function getTestCasesForApp(company, app) {
            const cases = [];
            try {
                const dataHandle = await currentDirectoryHandle.getDirectoryHandle('data');
                const companyHandle = await dataHandle.getDirectoryHandle(company);
                const appHandle = await companyHandle.getDirectoryHandle(app);
                
                let mostRecentTimestamp = '';
                let recentRunHandle = null;

                for await (const entry of appHandle.values()) {
                    if (entry.kind === 'directory' && entry.name > mostRecentTimestamp) {
                        mostRecentTimestamp = entry.name;
                        recentRunHandle = entry;
                    }
                }

                if (recentRunHandle) {
                    const pagesHandle = await recentRunHandle.getDirectoryHandle('pages');
                    for await (const pageEntry of pagesHandle.values()) {
                        if (pageEntry.kind === 'directory') {
                            try {
                                const aiTestsHandle = await pageEntry.getFileHandle('ai_tests.json');
                                const pageTests = await readJsonFile(aiTestsHandle);
                                
                                Object.entries(pageTests).forEach(([category, testCases]) => {
                                    testCases.forEach(testCase => {
                                        testCase.category = category;
                                        testCase.company = company;
                                        testCase.app = app;
                                        cases.push(testCase);
                                    });
                                });
                            } catch (error) {
                                console.error(`Error reading tests for page ${pageEntry.name}:`, error);
                            }
                        }
                    }
                }
            } catch (error) {
                console.error('Error getting test cases:', error);
            }
            return cases;
        }

        function log(message) {
            // Removed
        }

        async function readJsonFile(fileHandle) {
            const file = await fileHandle.getFile();
            const content = await file.text();
            return JSON.parse(content);
        }

        function showLoadingState(element) {
            element.classList.add('loading');
        }

        function hideLoadingState(element) {
            element.classList.remove('loading');
        }

        function showError(message) {
            // TODO: Implement error display
        }

        function showSuccess(message) {
            // TODO: Implement success display
        }

        function showTestCaseDetails(testIndex, clickedCard) {
            const testCase = window.currentTestCases[testIndex];
            if (!testCase) return;

            // Update selected card styling
            document.querySelectorAll('.test-case-card').forEach(card => card.classList.remove('selected'));
            if (clickedCard) clickedCard.classList.add('selected');

            const detailsContainer = document.querySelector('#testDetailsPanel .test-case-details');
            if (!detailsContainer) return;

            const breadcrumbs = getBreadcrumbsFromPath(testCase);
            const breadcrumbsHtml = breadcrumbs ? `
                <div class="breadcrumbs">
                    <span class="breadcrumb-item" onclick="selectCompany('${breadcrumbs.company}')">${breadcrumbs.company}</span>
                    <span class="breadcrumb-separator">/</span>
                    <span class="breadcrumb-item" onclick="loadTestData('${testCase.path}')">${breadcrumbs.app}</span>
                    <span class="breadcrumb-separator">/</span>
                    <span class="breadcrumb-current">${breadcrumbs.testName}</span>
                </div>
            ` : '';

            detailsContainer.innerHTML = `
                ${breadcrumbsHtml}
                <div class="profile-section ${isSpecialCategory(testCase) ? 'edge-profile' : ''}">
                    <img src="${getProfileImage(testCase)}" alt="Profile" class="profile-image">
                    <div>
                        <h2 class="text-xl font-bold">${getProfileName(testCase)}</h2>
                        <p class="text-sm text-gray-400">${getProfileRole(testCase)}</p>
                    </div>
                </div>

                <div class="test-details-section">
                    <div class="mb-6">
                        <h3 class="text-lg font-semibold mb-2">Test Case ID</h3>
                        <p class="text-gray-300">${testCase.id || 'N/A'}</p>
                    </div>

                    <div class="mb-6">
                        <h3 class="text-lg font-semibold mb-2">Test Case Name</h3>
                        <p class="text-gray-300">${testCase.title || 'N/A'}</p>
                    </div>

                    <div class="mb-6">
                        <h3 class="text-lg font-semibold mb-2">Validation Conditions</h3>
                        <p class="text-gray-300">${testCase.validation_conditions || 'N/A'}</p>
                    </div>

                    <div class="mb-6">
                        <h3 class="text-lg font-semibold mb-2">Test Steps</h3>
                        <p class="text-gray-300 whitespace-pre-line">${testCase.test_steps || 'N/A'}</p>
                    </div>

                    <div class="mb-6">
                        <h3 class="text-lg font-semibold mb-2">Priority Reason</h3>
                        <p class="text-gray-300">${testCase.priority_reason || 'N/A'}</p>
                    </div>

                    <div class="mb-6">
                        <h3 class="text-lg font-semibold mb-2">Test Data</h3>
                        <div class="space-y-4">
                            <div>
                                <h4 class="text-md font-semibold text-gray-400">Inputs:</h4>
                                <ul class="list-disc list-inside text-gray-300">
                                    ${testCase.data?.inputs?.length ? 
                                        testCase.data.inputs.map(input => `<li>${input}</li>`).join('') :
                                        '<li>No inputs specified</li>'
                                    }
                                </ul>
                            </div>
                            <div>
                                <h4 class="text-md font-semibold text-gray-400">Expected Outputs:</h4>
                                <ul class="list-disc list-inside text-gray-300">
                                    ${testCase.data?.expected_outputs?.length ?
                                        testCase.data.expected_outputs.map(output => `<li>${output}</li>`).join('') :
                                        '<li>No expected outputs specified</li>'
                                    }
                                </ul>
                            </div>
                            <div>
                                <h4 class="text-md font-semibold text-gray-400">Edge Cases:</h4>
                                <ul class="list-disc list-inside text-gray-300">
                                    ${testCase.data?.edge_cases?.length ?
                                        testCase.data.edge_cases.map(edge => `<li>${edge}</li>`).join('') :
                                        '<li>No edge cases specified</li>'
                                    }
                                </ul>
                            </div>
                        </div>
                    </div>
                </div>
            `;
        }

        function selectApp(company, app) {
            currentCompany = company;
            currentApp = app;
            loadTestData(`${company}/${app}`);
        }

        document.addEventListener('keydown', (e) => {
            if (e.ctrlKey || e.metaKey) {
                switch(e.key) {
                    case 'f':
                        e.preventDefault();
                        document.getElementById('searchInput')?.focus();
                        break;
                    case 's':
                        e.preventDefault();
                        saveChanges();
                        break;
                }
            }
        });

        document.getElementById('searchInput')?.addEventListener('input', (e) => {
            clearTimeout(searchTimeout);
            searchTimeout = setTimeout(() => filterTestCases(e.target.value), 300);
        });

        async function updateTestCase(field, value) {
            if (!selectedTestCase) return;
            
            try {
                selectedTestCase[field] = value;
                showSuccess('Test case updated successfully');
                
                // Update the test case in the current data
                const index = currentTestData[selectedCategory].findIndex(tc => tc.title === selectedTestCase.title);
                if (index !== -1) {
                    currentTestData[selectedCategory][index] = selectedTestCase;
                }
            } catch (error) {
                showError('Failed to update test case: ' + error.message);
                console.error('Error updating test case:', error);
            }
        }
    </script>
</body>
</html>
