<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{{brand_name}} - Tester Manager</title>
    <style>
        :root {
            --primary-color: #4B7BEC;
            --secondary-color: #45AEF5;
            --background-dark: #1E2337;
            --background-card: #2A2F45;
            --text-primary: #FFFFFF;
            --text-secondary: #A0A7B7;
        }

        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Segoe UI', system-ui, sans-serif;
        }

        body {
            background: var(--background-dark);
            color: var(--text-primary);
            min-height: 100vh;
            padding: 2rem;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
        }

        .header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 1rem;
            padding: 1rem;
            background: var(--background-card);
            border-radius: 10px;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.3);
        }

        .header-content {
            display: flex;
            align-items: center;
            gap: 1rem;
        }

        .logo {
            height: 40px;
            width: auto;
        }

        .header-text h1 {
            font-size: 1.5rem;
            margin-bottom: 0.25rem;
        }

        .header-text p {
            color: var(--text-secondary);
            font-size: 0.9rem;
        }

        .intro-section {
            background: var(--background-card);
            border-radius: 10px;
            padding: 1.5rem;
            margin-bottom: 2rem;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.3);
        }

        .intro-section h2 {
            color: var(--primary-color);
            margin-bottom: 1rem;
        }

        .intro-section p {
            color: var(--text-secondary);
            line-height: 1.6;
        }

        .btn {
            background: var(--primary-color);
            color: white;
            border: none;
            padding: 0.75rem 1.5rem;
            border-radius: 5px;
            cursor: pointer;
            transition: all 0.3s ease;
        }

        .btn:hover {
            background: var(--secondary-color);
            transform: translateY(-2px);
        }

        .testers-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
            gap: 1.5rem;
            margin-top: 2rem;
        }

        .tester-card {
            background: var(--background-card);
            border-radius: 10px;
            padding: 1.5rem;
            position: relative;
            transition: transform 0.3s ease;
        }

        .tester-card:hover {
            transform: translateY(-5px);
        }

        .tester-image {
            width: 100px;
            height: 100px;
            border-radius: 50%;
            object-fit: cover;
            margin-bottom: 1rem;
        }

        .tester-name {
            font-size: 1.5rem;
            margin-bottom: 0.5rem;
            color: var(--text-primary);
        }

        .tester-byline {
            color: var(--secondary-color);
            margin-bottom: 1rem;
        }

        .checks-list {
            list-style: none;
            margin: 1rem 0;
        }

        .checks-list li {
            margin-bottom: 0.5rem;
            padding-left: 1.5rem;
            position: relative;
            color: var(--text-secondary);
        }

        .checks-list li::before {
            content: "✓";
            position: absolute;
            left: 0;
            color: var(--primary-color);
        }

        .card-actions {
            display: flex;
            gap: 0.5rem;
            margin-top: 1rem;
        }

        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.8);
            justify-content: center;
            align-items: center;
            z-index: 1000;
        }

        .modal-content {
            background: var(--background-card);
            padding: 2rem;
            border-radius: 10px;
            width: 90%;
            max-width: 600px;
            max-height: 90vh;
            overflow-y: auto;
        }

        .form-group {
            margin-bottom: 1.5rem;
        }

        .form-group label {
            display: block;
            margin-bottom: 0.5rem;
            color: var(--text-primary);
        }

        .form-group input,
        .form-group textarea {
            width: 100%;
            padding: 0.5rem;
            background: var(--background-dark);
            border: 1px solid var(--secondary-color);
            color: var(--text-primary);
            border-radius: 5px;
        }

        .form-group input:focus,
        .form-group textarea:focus {
            outline: none;
            border-color: var(--primary-color);
            box-shadow: 0 0 0 2px rgba(75, 123, 236, 0.2);
        }

        .field-hint {
            display: block;
            color: var(--text-secondary);
            font-size: 0.85rem;
            margin-top: 0.25rem;
        }

        .error-message {
            color: #f44336;
            font-size: 0.85rem;
            margin-top: 0.25rem;
        }

        .checks-container {
            margin-top: 1rem;
        }

        .check-input-group {
            display: flex;
            gap: 0.5rem;
            margin-bottom: 0.5rem;
        }

        .notification {
            position: fixed;
            bottom: 20px;
            right: 20px;
            padding: 1rem;
            border-radius: 5px;
            color: white;
            display: none;
        }

        .success {
            background: #4CAF50;
        }

        .error {
            background: #f44336;
        }

        .initial-state {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: var(--background-dark);
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            padding: 2rem;
            z-index: 1000;
        }

        .initial-state.hidden {
            display: none;
        }

        .initial-state img {
            height: 60px;
            margin-bottom: 2rem;
        }

        .initial-state h1 {
            color: var(--text-primary);
            margin-bottom: 1rem;
            text-align: center;
        }

        .initial-state p {
            color: var(--text-secondary);
            max-width: 600px;
            text-align: center;
            margin-bottom: 2rem;
            line-height: 1.6;
        }

        @keyframes pulse {
            0% { transform: scale(1); }
            50% { transform: scale(1.05); }
            100% { transform: scale(1); }
        }

        .pulse-button {
            animation: pulse 2s infinite;
            background: var(--primary-color);
        }

        .btn.active {
            background: var(--secondary-color);
            transform: translateY(-2px);
        }
        #teamList .btn {
            padding: 0.5rem 1rem;
        }
        .header-actions {
            display: flex;
            gap: 0.5rem;
        }
    </style>
</head>
<body>
    <div class="initial-state" id="initialState">
        <img src="{{brand_url}}" alt="Logo">
        <h1>Welcome to {{brand_name}} Tester Manager</h1>
        <p>To get started, please select your working directory. This should be the folder where your {{brand_name}} application is installed and where your AI tester configuration files are stored.</p>
        <p>The application will manage your AI testers in files named <code>ai_testers_&lt;teamname&gt;.json</code> within your selected directory.</p>
        <button class="btn pulse-button" onclick="selectDirectory()">Select Working Directory</button>
    </div>

    <div class="container">
        <div class="header">
            <div class="header-content">
                <img src="{{brand_url}}" alt="Logo" class="logo">
                <div class="header-text">
                    <h1>{{brand_name}} Tester Manager</h1>
                    <p>Create and manage AI testers for your quality assurance needs</p>
                </div>
            </div>
            <div class="header-actions">
                <button class="btn" onclick="selectDirectory()">Select Working Directory</button>
                <button class="btn" onclick="showAddModal()" style="display: none;" id="addTesterBtn">Add New Tester</button>
            </div>
        </div>

        <div class="intro-section">
            <h2>Welcome to {{brand_name}} Tester Manager</h2>
            <p>Create, manage, and organize your AI testers in one place. Each tester is designed with specific expertise and focus areas, helping you maintain quality across your applications. Use these AI testers in your {{brand_name}} runs to ensure comprehensive testing coverage and catch issues before they reach production.</p>
            <div id="teamSelector" style="display: none; margin-top: 1rem;">
                <h3 style="margin-bottom: 0.5rem;">Available Teams</h3>
                <div id="teamList" style="display: flex; flex-wrap: wrap; gap: 0.5rem;"></div>
                <button class="btn" onclick="showNewTeamModal()" style="margin-top: 1rem;">Create New Team</button>
            </div>
        </div>

        <div class="testers-grid" id="testersGrid"></div>
    </div>

    <div class="modal" id="testerModal">
        <div class="modal-content">
            <h2 id="modalTitle">Add New Tester</h2>
            <form id="testerForm">
                <div class="form-group">
                    <label for="name">Name</label>
                    <input type="text" id="name" required placeholder="e.g., Ryan">
                    <small class="field-hint">The name of your AI tester</small>
                </div>
                <div class="form-group">
                    <label for="byline">Byline</label>
                    <input type="text" id="byline" required placeholder="e.g., Branding Expert">
                    <small class="field-hint">A short description of the tester's specialty</small>
                </div>
                <div class="form-group">
                    <label for="imageUrl">Image URL</label>
                    <input type="url" id="imageUrl" required 
                           value="images/pete.jpg"
                           placeholder="images/pete.jpg">
                    <small class="field-hint">A profile image URL for the tester (default provided)</small>
                </div>
                <div class="form-group">
                    <label for="biography">Biography</label>
                    <textarea id="biography" rows="3" required placeholder="e.g., I am an experienced UI tester specializing in brand consistency and user experience. Previously, I worked at Nike and Apple, where I developed a keen eye for minimalist, impactful branding. I studied Graphic Design at Rhode Island School of Design (RISD) and have a particular passion for typography and color theory. Based in San Francisco, I spend my weekends exploring Bay Area hiking trails on my Ducati Monster when I'm not perfecting pixel-perfect designs."></textarea>
                    <small class="field-hint">A detailed description of the tester's background and expertise</small>
                </div>
                <div class="form-group">
                    <label for="prompt">Prompt</label>
                    <textarea id="prompt" rows="3" required placeholder="e.g., You are a UI testing expert focusing on brand consistency. You ensure that the brand color scheme is correctly implemented and that brand names are properly formatted according to the latest guidelines."></textarea>
                    <small class="field-hint">The AI prompt that defines this tester's behavior and expertise</small>
                </div>
                <div class="checks-container">
                    <label>Specific things I Check for</label>
                    <div id="checksContainer"></div>
                    <button type="button" class="btn" onclick="addCheckField()">Add Check</button>
                    <small class="field-hint">Specific items this tester will verify</small>
                </div>
                <div style="margin-top: 1rem;">
                    <button type="submit" class="btn">Save</button>
                    <button type="button" class="btn" onclick="hideModal()">Cancel</button>
                </div>
            </form>
        </div>
    </div>

    <div class="notification" id="notification"></div>

    <script>
        let currentEditId = null;
        let directoryHandle = null;
        let currentTeam = null;
        const testersGrid = document.getElementById('testersGrid');
        const modal = document.getElementById('testerModal');
        const form = document.getElementById('testerForm');
        const notification = document.getElementById('notification');
        const addTesterBtn = document.getElementById('addTesterBtn');
        const teamSelector = document.getElementById('teamSelector');

        async function selectDirectory() {
            try {
                directoryHandle = await window.showDirectoryPicker();
                document.getElementById('initialState').classList.add('hidden');
                teamSelector.style.display = 'block';
                await loadTeams();
            } catch (error) {
                showNotification('Failed to access directory: ' + error.message, 'error');
            }
        }

        async function loadTeams() {
            try {
                const teamList = document.getElementById('teamList');
                teamList.innerHTML = '';
                
                for await (const entry of directoryHandle.values()) {
                    if (entry.kind === 'file' && entry.name.startsWith('ai_testers_') && entry.name.endsWith('.json')) {
                        const teamName = entry.name.replace('ai_testers_', '').replace('.json', '');
                        const teamButton = document.createElement('button');
                        teamButton.className = 'btn';
                        teamButton.textContent = teamName;
                        teamButton.onclick = () => loadTeam(teamName);
                        teamList.appendChild(teamButton);
                    }
                }
            } catch (error) {
                showNotification('Error loading teams: ' + error.message, 'error');
            }
        }

        function showNewTeamModal() {
            const teamName = prompt('Enter the new team name:');
            if (teamName) {
                createNewTeam(teamName);
            }
        }

        async function createNewTeam(teamName) {
            try {
                const fileName = `ai_testers_${teamName}.json`;
                const fileHandle = await directoryHandle.getFileHandle(fileName, { create: true });
                const writable = await fileHandle.createWritable();
                await writable.write(JSON.stringify([], null, 2));
                await writable.close();
                await loadTeams();
                loadTeam(teamName);
            } catch (error) {
                showNotification('Error creating team: ' + error.message, 'error');
            }
        }

        async function loadTeam(teamName) {
            try {
                currentTeam = teamName;
                const fileName = `ai_testers_${teamName}.json`;
                const fileHandle = await directoryHandle.getFileHandle(fileName);
                const file = await fileHandle.getFile();
                const content = await file.text();
                const testers = JSON.parse(content);
                
                renderTesters(testers);
                addTesterBtn.style.display = 'inline-block';
                document.querySelectorAll('#teamList button').forEach(btn => {
                    btn.classList.toggle('active', btn.textContent === teamName);
                });
            } catch (error) {
                showNotification('Error loading team: ' + error.message, 'error');
            }
        }

        function showNotification(message, type) {
            notification.textContent = message;
            notification.className = `notification ${type}`;
            notification.style.display = 'block';
            setTimeout(() => {
                notification.style.display = 'none';
            }, 3000);
        }

        function renderTesters(testers) {
            testersGrid.innerHTML = testers.map(tester => `
                <div class="tester-card">
                    <img src="${tester.image_url}" alt="${tester.name}" class="tester-image">
                    <h3 class="tester-name">${tester.name}</h3>
                    <div class="tester-byline">${tester.byline}</div>
                    <p>${tester.biography}</p>
                    <ul class="checks-list">
                        ${tester.checks.map(check => `<li>${check}</li>`).join('')}
                    </ul>
                    <div class="card-actions">
                        <button class="btn" onclick='editTester(${JSON.stringify(tester)})'>Edit</button>
                        <button class="btn" onclick="deleteTester('${tester.name}')">Delete</button>
                    </div>
                </div>
            `).join('');
        }

        function showAddModal() {
            if (!currentTeam) {
                showNotification('Please select a team first', 'error');
                return;
            }
            currentEditId = null;
            document.getElementById('modalTitle').textContent = 'Add New Tester';
            form.reset();
            document.getElementById('imageUrl').value = 'images/pete.jpg';
            document.getElementById('checksContainer').innerHTML = '';
            addCheckField(); 
            modal.style.display = 'flex';
        }

        function editTester(tester) {
            currentEditId = tester.name;
            document.getElementById('modalTitle').textContent = 'Edit Tester';
            document.getElementById('name').value = tester.name;
            document.getElementById('byline').value = tester.byline;
            document.getElementById('imageUrl').value = tester.image_url;
            document.getElementById('biography').value = tester.biography;
            document.getElementById('prompt').value = tester.prompt;
            
            const checksContainer = document.getElementById('checksContainer');
            checksContainer.innerHTML = '';
            tester.checks.forEach(check => {
                addCheckField(check);
            });
            
            modal.style.display = 'flex';
        }

        function hideModal() {
            modal.style.display = 'none';
            form.reset();
        }

        function addCheckField(value = '') {
            const container = document.getElementById('checksContainer');
            const div = document.createElement('div');
            div.className = 'check-input-group';
            div.innerHTML = `
                <input type="text" class="check-input" value="${value}" required 
                       placeholder="e.g., Check that the brand logo appears in the correct size and position">
                <button type="button" class="btn" onclick="removeCheck(this)" ${container.children.length === 0 ? 'disabled' : ''}>Remove</button>
            `;
            container.appendChild(div);
            updateRemoveButtons();
        }

        function removeCheck(button) {
            const container = document.getElementById('checksContainer');
            if (container.children.length > 1) {
                button.parentElement.remove();
                updateRemoveButtons();
            }
        }

        function updateRemoveButtons() {
            const container = document.getElementById('checksContainer');
            const buttons = container.querySelectorAll('button');
            buttons.forEach(button => {
                button.disabled = container.children.length === 1;
            });
        }

        form.onsubmit = async (e) => {
            e.preventDefault();

            const checks = Array.from(document.querySelectorAll('.check-input')).map(input => input.value);
            if (checks.length === 0) {
                showNotification('At least one check is required', 'error');
                return;
            }

            const formData = {
                name: document.getElementById('name').value,
                byline: document.getElementById('byline').value,
                image_url: document.getElementById('imageUrl').value,
                biography: document.getElementById('biography').value,
                prompt: document.getElementById('prompt').value,
                checks: checks
            };

            try {
                const fileName = `ai_testers_${currentTeam}.json`;
                const fileHandle = await directoryHandle.getFileHandle(fileName);
                const file = await fileHandle.getFile();
                const content = await file.text();
                const testers = JSON.parse(content);

                if (currentEditId) {
                    const index = testers.findIndex(t => t.name === currentEditId);
                    if (index !== -1) {
                        testers[index] = formData;
                    }
                } else {
                    testers.push(formData);
                }

                const writable = await fileHandle.createWritable();
                await writable.write(JSON.stringify(testers, null, 2));
                await writable.close();

                hideModal();
                loadTeam(currentTeam);
                showNotification(`Tester ${currentEditId ? 'updated' : 'added'} successfully`, 'success');
            } catch (error) {
                showNotification('Error saving tester: ' + error.message, 'error');
            }
        };

        async function deleteTester(name) {
            if (!confirm(`Are you sure you want to delete ${name}?`)) return;

            try {
                const fileName = `ai_testers_${currentTeam}.json`;
                const fileHandle = await directoryHandle.getFileHandle(fileName);
                const file = await fileHandle.getFile();
                const content = await file.text();
                const testers = JSON.parse(content);
                
                const filteredTesters = testers.filter(t => t.name !== name);
                
                const writable = await fileHandle.createWritable();
                await writable.write(JSON.stringify(filteredTesters, null, 2));
                await writable.close();
                
                loadTeam(currentTeam);
                showNotification('Tester deleted successfully', 'success');
            } catch (error) {
                showNotification('Error deleting tester: ' + error.message, 'error');
            }
        }
    </script>
</body>
</html>
