{% extends "layout.html.twig" %}

{% block title %}Admin - Alpha Testing Feedback{% endblock %}

{% block content %}
<div class="container-fluid mt-4">
    <div class="row">
        <div class="col-12">
            <div class="d-flex justify-content-between align-items-center mb-4">
                <h1 class="giantish text-primary">
                    <i class="fas fa-exclamation-triangle me-2"></i>Alpha Testing Feedback
                </h1>
                <div class="d-flex align-items-center gap-3">
                    <div>
                        <span class="badge bg-primary me-2">Total: {{ feedbacks|length }}</span>
                        {% set resolvedCount = 0 %}
                        {% for feedback in feedbacks %}
                            {% if feedback.resolved %}
                                {% set resolvedCount = resolvedCount + 1 %}
                            {% endif %}
                        {% endfor %}
                        <span class="badge bg-warning">Unresolved: {{ feedbacks|length - resolvedCount }}</span>
                    </div>
                    <div class="btn-group" role="group">
                        <button type="button" class="btn btn-outline-primary active" id="showUnresolvedBtn" onclick="filterFeedback('unresolved')">
                            <i class="fas fa-exclamation-circle me-1"></i>Unresolved Only
                        </button>
                        <button type="button" class="btn btn-outline-primary" id="showAllBtn" onclick="filterFeedback('all')">
                            <i class="fas fa-list me-1"></i>Show All
                        </button>
                    </div>
                </div>
            </div>

            {% if feedbacks|length == 0 %}
                <div class="alert alert-info">
                    <i class="fas fa-info-circle me-2"></i>
                    No alpha testing feedback has been submitted yet.
                </div>
            {% else %}
                <div class="table-responsive">
                    <table class="table table-striped table-hover">
                        <thead class="table-dark">
                            <tr>
                                <th>ID</th>
                                <th>User</th>
                                <th>Comment Preview</th>
                                <th style="width: 8ch;">Reply</th>
                                <th>SS</th>
                                <th>Actions</th>
                                <th>Page</th>
                                <th>Timestamp</th>
                                <th>Status</th>
                            </tr>
                        </thead>
                        <tbody>
                            {% for feedback in feedbacks %}
                            <tr class="{% if not feedback.resolved %}table-warning{% endif %}" data-feedback-id="{{ feedback.id }}" data-resolved="{{ feedback.resolved ? 'true' : 'false' }}">
                                <td>
                                    <span class="badge bg-secondary">#{{ feedback.id }}</span>
                                </td>
                                <td>
                                    <div class="d-flex align-items-center">
                                        {% if feedback.user_avatar %}
                                            <img src="/ll_images/{{ feedback.user_avatar }}" 
                                                 class="rounded-circle me-2" 
                                                 style="width: 32px; height: 32px; object-fit: cover;" 
                                                 alt="Avatar">
                                        {% endif %}
                                        <div>
                                            <strong>{{ feedback.user_name }}</strong><br>
                                            <small class="text-muted">ID: {{ feedback.user_id }}</small>
                                        </div>
                                    </div>
                                </td>
                                <td style="max-width: 600px; min-width: 400px;">
                                    <div class="small" style="white-space: pre-wrap; word-wrap: break-word; text-indent: 0;">
                                        {{ feedback.tester_comments }}
                                    </div>
                                </td>
                                <td style="width: 8ch; text-align: center;">
                                    {% if feedback.admin_reply %}
                                        <a href="#" class="btn btn-sm btn-outline-primary" onclick="openReplyModal({{ feedback.id }}, '{{ feedback.user_name|e('js') }}', {{ feedback.user_id }})" title="{{ feedback.admin_reply|e('html_attr') }}">
                                            <i class="fas fa-reply" style="color: #0d6efd;"></i>
                                        </a>
                                    {% else %}
                                        <a href="#" class="btn btn-sm btn-outline-success" onclick="openReplyModal({{ feedback.id }}, '{{ feedback.user_name|e('js') }}', {{ feedback.user_id }})" title="Reply to user">
                                            <i class="fas fa-reply" style="color: #198754;"></i>
                                        </a>
                                    {% endif %}
                                </td>
                                <td class="text-center">
                                    {% set screenshotCount = 0 %}
                                    {% if feedback.screenshot1 %}{% set screenshotCount = screenshotCount + 1 %}{% endif %}
                                    {% if feedback.screenshot2 %}{% set screenshotCount = screenshotCount + 1 %}{% endif %}
                                    {% if feedback.screenshot3 %}{% set screenshotCount = screenshotCount + 1 %}{% endif %}
                                    
                                    {% if screenshotCount > 0 %}
                                        <button class="btn btn-sm btn-outline-info d-flex flex-column align-items-center" onclick="viewScreenshots({{ feedback.id }})" title="View {{ screenshotCount }} screenshot{{ screenshotCount != 1 ? 's' : '' }}" style="min-width: 40px; padding: 4px;">
                                            <i class="fas fa-images" style="font-size: 14px;"></i>
                                            <span class="badge bg-info mt-1" style="font-size: 10px;">{{ screenshotCount }}</span>
                                        </button>
                                    {% else %}
                                        <span class="text-muted small">-</span>
                                    {% endif %}
                                </td>
                                <td>
                                    <div class="btn-group btn-group-sm" role="group">
                                        <button type="button" 
                                                class="btn btn-primary" 
                                                onclick="viewUserPage({{ feedback.user_id }}, '{{ feedback.current_url }}')"
                                                title="View as User">
                                            <i class="fas fa-eye"></i>
                                        </button>
                                        <button type="button" 
                                                class="btn btn-info" 
                                                onclick="viewFeedbackDetails({{ feedback.id }})"
                                                title="View Details">
                                            <i class="fas fa-info-circle"></i>
                                        </button>
                                        <button type="button" 
                                                class="btn btn-secondary" 
                                                onclick="viewVisualContext({{ feedback.id }})"
                                                title="Visual Context">
                                            <i class="fas fa-desktop"></i>
                                        </button>

                                        {% if not feedback.resolved %}
                                            <button type="button" 
                                                    class="btn btn-success" 
                                                    onclick="markResolved({{ feedback.id }})"
                                                    title="Mark Resolved">
                                                <i class="fas fa-check"></i>
                                            </button>
                                        {% endif %}
                                    </div>
                                </td>
                                <td>
                                    <div class="small">
                                        <strong>{{ feedback.page_title }}</strong><br>
                                        {% set cleanUrl = feedback.current_url|replace({'https://locallendables.replit.app': '', 'https://local-lendables.replit.dev': '', 'http://localhost:5000': ''}) %}
                                        <span class="text-muted">{{ cleanUrl|slice(0, 30) }}{% if cleanUrl|length > 30 %}...{% endif %}</span>
                                    </div>
                                </td>
                                <td>
                                    <div class="small"><strong>{{ feedback.atlanticTimestamp }} AST</strong></div>
                                </td>
                                <td class="status-badge">
                                    {% if feedback.resolved %}
                                        <span class="badge bg-success">Resolved</span>
                                    {% else %}
                                        <span class="badge bg-warning">Open</span>
                                    {% endif %}
                                </td>
                            </tr>
                            {% endfor %}
                        </tbody>
                    </table>
                </div>
            {% endif %}
        </div>
    </div>
</div>

<!-- Feedback Details Modal -->
<div class="modal fade" id="feedbackDetailsModal" tabindex="-1" aria-labelledby="feedbackDetailsModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-xl">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="feedbackDetailsModalLabel">Feedback Details</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body" id="feedbackDetailsContent">
                <!-- Content loaded dynamically -->
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                <button type="button" class="btn btn-success" id="markResolvedBtn" onclick="">Mark Resolved</button>
            </div>
        </div>
    </div>
</div>

<!-- Reply Modal -->
<div class="modal fade" id="replyModal" tabindex="-1" aria-labelledby="replyModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="replyModalLabel">Reply to User</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="replyForm">
                    <div class="mb-3">
                        <label for="replyRecipient" class="form-label">Replying to:</label>
                        <input type="text" class="form-control" id="replyRecipient" readonly>
                        <input type="hidden" id="replyFeedbackId">
                        <input type="hidden" id="replyUserId">
                    </div>
                    <div class="mb-3">
                        <label for="replyMessage" class="form-label">Your Reply:</label>
                        <textarea class="form-control" id="replyMessage" rows="6" required 
                                  placeholder="Type your reply to the user's feedback..."></textarea>
                    </div>
                    <div class="form-check">
                        <input class="form-check-input" type="checkbox" id="markResolvedOnReply" checked>
                        <label class="form-check-label" for="markResolvedOnReply">
                            Mark this feedback as resolved after saving reply
                        </label>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-primary" onclick="sendReply()">
                    <i class="fas fa-save me-1"></i>Save Reply
                </button>
            </div>
        </div>
    </div>
</div>

<script>
// Open user page in consistently named window
function viewUserPage(userId, currentUrl) {
    // First, update session to simulate user
    fetch('/api/admin/simulate-user', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({ userId: userId })
    }).then(response => {
        if (response.ok) {
            // Open the page the user was on in the named window
            const userWindow = window.open(currentUrl, 'display_user_page', 'width=1200,height=800,scrollbars=yes,resizable=yes');
            if (userWindow) {
                userWindow.focus();
            }
        } else {
            showBootstrapAlert('Simulation Error', 'Failed to simulate user session', 'danger');
        }
    }).catch(error => {
        console.error('Error simulating user:', error);
        showBootstrapAlert('Connection Error', 'Error simulating user session', 'danger');
    });
}

// View feedback details
async function viewFeedbackDetails(feedbackId) {
    try {
        const response = await fetch(`/api/alpha-feedback/${feedbackId}`);
        const feedback = await response.json();
        
        const content = `
            <div class="row">
                <div class="col-md-6">
                    <h6>User Information</h6>
                    <table class="table table-sm">
                        <tr><td><strong>Name:</strong></td><td>${feedback.user_name}</td></tr>
                        <tr><td><strong>User ID:</strong></td><td>${feedback.user_id}</td></tr>
                        <tr><td><strong>Avatar:</strong></td><td>${feedback.user_avatar || 'None'}</td></tr>
                        <tr><td><strong>IP Address:</strong></td><td>${feedback.ip_address || 'Unknown'}</td></tr>
                    </table>
                    
                    <h6>Page Information</h6>
                    <table class="table table-sm">
                        <tr><td><strong>Page Title:</strong></td><td>${feedback.page_title}</td></tr>
                        <tr><td><strong>Current URL:</strong></td><td class="small">${feedback.current_url}</td></tr>
                        <tr><td><strong>Previous Page:</strong></td><td class="small">${feedback.previous_page || 'Unknown'}</td></tr>
                        <tr><td><strong>Timestamp:</strong></td><td>${new Date(feedback.timestamp).toLocaleString('en-US', { timeZone: 'America/Halifax', timeZoneName: 'short' })}</td></tr>
                    </table>
                </div>
                <div class="col-md-6">
                    <h6>Technical Information</h6>
                    <table class="table table-sm">
                        <tr><td><strong>User Agent:</strong></td><td class="small">${feedback.user_agent || 'Unknown'}</td></tr>
                        <tr><td><strong>Browser Info:</strong></td><td class="small">${feedback.browser_info || 'None'}</td></tr>
                        <tr><td><strong>Session Data:</strong></td><td class="small">${feedback.session_data || 'None'}</td></tr>
                    </table>
                    
                    <h6>Status</h6>
                    <p><span class="badge ${feedback.resolved ? 'bg-success' : 'bg-warning'}">${feedback.resolved ? 'Resolved' : 'Open'}</span></p>
                </div>
            </div>
            <div class="row mt-3">
                <div class="col-12">
                    <h6>Tester Comments</h6>
                    <div class="alert alert-light border">
                        ${feedback.tester_comments.replace(/\n/g, '<br>')}
                    </div>
                </div>
            </div>
        `;
        
        document.getElementById('feedbackDetailsContent').innerHTML = content;
        document.getElementById('markResolvedBtn').onclick = () => markResolved(feedbackId);
        
        const modal = new bootstrap.Modal(document.getElementById('feedbackDetailsModal'));
        modal.show();
    } catch (error) {
        console.error('Error loading feedback details:', error);
        showBootstrapAlert('Load Error', 'Error loading feedback details. Please try again.', 'danger');
    }
}

// Mark feedback as resolved with AJAX update
async function markResolved(feedbackId) {
    try {
        const response = await fetch(`/api/alpha-feedback/${feedbackId}/resolve`, {
            method: 'POST'
        });
        
        if (response.ok) {
            // Update the row styling and status badge without page reload
            const row = document.querySelector(`tr[data-feedback-id="${feedbackId}"]`);
            if (row) {
                // Remove warning styling
                row.classList.remove('table-warning');
                
                // Update status badge
                const statusCell = row.querySelector('.status-badge');
                if (statusCell) {
                    statusCell.innerHTML = '<span class="badge bg-success">Resolved</span>';
                }
                
                // Update resolve button
                const resolveBtn = row.querySelector(`button[onclick*="markResolved(${feedbackId})"]`);
                if (resolveBtn) {
                    resolveBtn.disabled = true;
                    resolveBtn.innerHTML = '<i class="fas fa-check text-success"></i>';
                    resolveBtn.title = 'Already Resolved';
                    resolveBtn.classList.remove('btn-success');
                    resolveBtn.classList.add('btn-outline-success');
                }
                
                // Update data attribute
                row.dataset.resolved = 'true';
                
                // Update counters in header
                updateCounters();
                
                // Add visual feedback
                row.style.transition = 'background-color 0.5s ease';
                row.style.backgroundColor = '#d4edda';
                setTimeout(() => {
                    row.style.backgroundColor = '';
                }, 1000);
            }
            
            showBootstrapAlert('Success', 'Feedback marked as resolved', 'success');
        } else {
            showBootstrapAlert('Error', 'Failed to mark feedback as resolved', 'danger');
        }
    } catch (error) {
        console.error('Error marking feedback as resolved:', error);
        showBootstrapAlert('Connection Error', 'Error marking feedback as resolved', 'danger');
    }
}

// Update the counters in the header
function updateCounters() {
    const allRows = document.querySelectorAll('tbody tr');
    const totalFeedbacks = allRows.length;
    const resolvedFeedbacks = document.querySelectorAll('tr[data-resolved="true"]').length;
    const unresolvedCount = totalFeedbacks - resolvedFeedbacks;
    
    const totalBadge = document.querySelector('.badge.bg-primary');
    const unresolvedBadge = document.querySelector('.badge.bg-warning');
    
    if (totalBadge) totalBadge.textContent = `Total: ${totalFeedbacks}`;
    if (unresolvedBadge) unresolvedBadge.textContent = `Unresolved: ${unresolvedCount}`;
}

// Filter feedback display
function filterFeedback(filter) {
    const allRows = document.querySelectorAll('tbody tr');
    const showUnresolvedBtn = document.getElementById('showUnresolvedBtn');
    const showAllBtn = document.getElementById('showAllBtn');
    
    // Update button states
    if (filter === 'unresolved') {
        showUnresolvedBtn.classList.add('active');
        showAllBtn.classList.remove('active');
        
        // Show only unresolved items
        allRows.forEach(row => {
            if (row.dataset.resolved === 'true') {
                row.style.display = 'none';
            } else {
                row.style.display = '';
            }
        });
    } else {
        showAllBtn.classList.add('active');
        showUnresolvedBtn.classList.remove('active');
        
        // Show all items
        allRows.forEach(row => {
            row.style.display = '';
        });
    }
}

// Initialize page with unresolved filter
document.addEventListener('DOMContentLoaded', function() {
    filterFeedback('unresolved');
});

// View visual context for feedback
function viewVisualContext(feedbackId) {
    fetch(`/api/alpha-feedback/${feedbackId}`)
        .then(response => response.json())
        .then(feedback => {
            try {
                const sessionData = JSON.parse(feedback.session_data || '{}');
                const visualContext = sessionData.visualContext || {};
                
                const contextWindow = window.open('', `context_${feedbackId}`, 'width=800,height=600,scrollbars=yes,resizable=yes');
                contextWindow.document.write(`
                    <html>
                    <head>
                        <title>Visual Context - Feedback #${feedbackId}</title>
                        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
                        <style>
                            .element-box { border: 1px solid #ddd; margin: 5px 0; padding: 10px; border-radius: 4px; }
                            .error-element { border-color: #dc3545; background-color: #f8d7da; }
                            .position { font-family: monospace; font-size: 12px; color: #666; }
                        </style>
                    </head>
                    <body class="p-4">
                        <h3>Visual Context for Feedback #${feedbackId}</h3>
                        <div class="mb-3">
                            <strong>Page:</strong> ${feedback.current_url || 'Unknown'}<br>
                            <strong>Timestamp:</strong> ${feedback.timestamp || 'Unknown'}<br>
                            <strong>Screen Size:</strong> ${sessionData.screen?.width || sessionData.screenWidth || 'Unknown'} x ${sessionData.screen?.height || sessionData.screenHeight || 'Unknown'}<br>
                            <strong>Viewport:</strong> ${sessionData.viewport?.width || sessionData.viewportWidth || 'Unknown'} x ${sessionData.viewport?.height || sessionData.viewportHeight || 'Unknown'}<br>
                            <strong>Scroll Position:</strong> ${sessionData.scroll?.x || sessionData.scrollX || 0}, ${sessionData.scroll?.y || sessionData.scrollY || 0}<br>
                            <strong>User Agent:</strong> ${feedback.user_agent || 'Unknown'}<br>
                            <strong>Browser Info:</strong> ${feedback.browser_info || 'Unknown'}
                        </div>
                        
                        ${visualContext.pageStructure?.errors?.length > 0 ? `
                        <div class="mb-4">
                            <h5 class="text-danger">Errors/Warnings on Page:</h5>
                            ${visualContext.pageStructure.errors.map(error => `
                                <div class="element-box error-element">
                                    <strong>Error Text:</strong> ${error.text}<br>
                                    <strong>Visible:</strong> ${error.visible ? 'Yes' : 'No'}
                                </div>
                            `).join('')}
                        </div>
                        ` : ''}
                        
                        <h5>Page State Information:</h5>
                        
                        ${visualContext.pageStructure?.focusedElement ? `
                        <div class="mb-3">
                            <h6 class="text-info">Focused Element:</h6>
                            <div class="element-box">
                                <strong>${visualContext.pageStructure.focusedElement.tag.toUpperCase()}</strong>
                                ${visualContext.pageStructure.focusedElement.id ? `<span class="badge bg-info">#${visualContext.pageStructure.focusedElement.id}</span>` : ''}
                                ${visualContext.pageStructure.focusedElement.text ? `<br><em>"${visualContext.pageStructure.focusedElement.text}"</em>` : ''}
                            </div>
                        </div>
                        ` : ''}
                        
                        ${visualContext.pageStructure?.uiStates && Object.keys(visualContext.pageStructure.uiStates).length > 0 ? `
                        <div class="mb-3">
                            <h6 class="text-warning">Active UI States:</h6>
                            ${visualContext.pageStructure.uiStates.openDropdowns ? `
                                <div class="element-box">
                                    <strong>Open Dropdowns:</strong> ${visualContext.pageStructure.uiStates.openDropdowns.length}
                                    ${visualContext.pageStructure.uiStates.openDropdowns.map(dd => `<br>• ${dd.text || dd.id || 'Unnamed dropdown'}`).join('')}
                                </div>
                            ` : ''}
                            ${visualContext.pageStructure.uiStates.openModals ? `
                                <div class="element-box">
                                    <strong>Open Modals:</strong> ${visualContext.pageStructure.uiStates.openModals.length}
                                    ${visualContext.pageStructure.uiStates.openModals.map(modal => `<br>• ${modal.title || modal.id || 'Unnamed modal'}`).join('')}
                                </div>
                            ` : ''}
                            ${visualContext.pageStructure.uiStates.formValidation ? `
                                <div class="element-box">
                                    <strong>Form Validation:</strong> ${visualContext.pageStructure.uiStates.formValidation.invalidFields} invalid fields
                                </div>
                            ` : ''}
                            ${visualContext.pageStructure.uiStates.notifications ? `
                                <div class="element-box">
                                    <strong>Active Notifications:</strong>
                                    ${visualContext.pageStructure.uiStates.notifications.map(notif => `<br>• ${notif.type}: ${notif.text?.substring(0, 50)}...`).join('')}
                                </div>
                            ` : ''}
                        </div>
                        ` : ''}
                        
                        <h6>Visible Interactive Elements:</h6>
                        <div class="row">
                            ${(visualContext.pageStructure?.visibleElements || []).map(el => `
                                <div class="col-md-6">
                                    <div class="element-box">
                                        <strong>${el.tag.toUpperCase()}</strong>
                                        ${el.id ? `<span class="badge bg-primary">#${el.id}</span>` : ''}
                                        ${el.class ? `<span class="badge bg-secondary">.${el.class.split(' ')[0]}</span>` : ''}<br>
                                        <div class="position">Position: ${el.position.left}, ${el.position.top} (${el.position.width}x${el.position.height})</div>
                                        ${el.text ? `<div class="mt-1"><em>"${el.text}"</em></div>` : ''}
                                        ${el.state ? `<div class="mt-1"><small class="text-muted">State: ${JSON.stringify(el.state)}</small></div>` : ''}
                                    </div>
                                </div>
                            `).join('')}
                        </div>
                        
                        <div class="mt-4">
                            <h6>Raw Session Data:</h6>
                            <pre class="bg-light p-2" style="font-size: 11px; max-height: 300px; overflow: auto; white-space: pre-wrap; word-break: break-all;">${JSON.stringify(sessionData, null, 2)}</pre>
                        </div>
                    </body>
                    </html>
                `);
                contextWindow.document.close();
            } catch (error) {
                alert('Could not parse visual context data: ' + error.message);
            }
        })
        .catch(error => {
            alert('Error loading feedback details: ' + error.message);
        });
}

// Bootstrap alert function for admin page
function showBootstrapAlert(title, message, type = 'info') {
    const existingAlert = document.getElementById('bootstrap-alert');
    if (existingAlert) existingAlert.remove();
    
    const alertHTML = `
        <div id="bootstrap-alert" class="alert alert-${type} alert-dismissible fade show position-fixed" 
             style="top: 20px; right: 20px; z-index: 9999; min-width: 300px; max-width: 400px; box-shadow: 0 4px 12px rgba(0,0,0,0.15);">
            <div class="d-flex align-items-start">
                <div class="me-3">
                    ${type === 'success' ? '<i class="fas fa-check-circle text-success fs-4"></i>' : 
                      type === 'danger' ? '<i class="fas fa-exclamation-triangle text-danger fs-4"></i>' : 
                      '<i class="fas fa-info-circle text-info fs-4"></i>'}
                </div>
                <div class="flex-grow-1">
                    <h6 class="alert-heading mb-1">${title}</h6>
                    <p class="mb-0 small">${message}</p>
                </div>
            </div>
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
    `;
    
    document.body.insertAdjacentHTML('beforeend', alertHTML);
    setTimeout(() => {
        const alert = document.getElementById('bootstrap-alert');
        if (alert) alert.style.opacity = '0.5';
    }, 1000);
    setTimeout(() => {
        const alert = document.getElementById('bootstrap-alert');
        if (alert) new bootstrap.Alert(alert).close();
    }, 2000);
}

// View screenshots for a feedback item
async function viewScreenshots(feedbackId) {
    try {
        const response = await fetch(`/api/alpha-feedback/${feedbackId}`);
        
        if (response.status === 401 || response.status === 403) {
            showBootstrapAlert('Admin Access Required', 'You must be logged in as an admin to view screenshots. Please return to admin user session.', 'warning');
            return;
        }
        
        if (!response.ok) {
            throw new Error(`HTTP ${response.status}: ${response.statusText}`);
        }
        
        const feedback = await response.json();
        
        // Check if we actually got the feedback data
        if (feedback.error) {
            throw new Error(feedback.error);
        }
        
        let screenshotsHtml = '<div class="row g-3">';
        let screenshotNumber = 1;
        
        // Add each screenshot if it exists
        if (feedback.screenshot1) {
            screenshotsHtml += `
                <div class="col-md-4">
                    <div class="card">
                        <img src="data:image/jpeg;base64,${feedback.screenshot1}" 
                             class="card-img-top screenshot-thumb" 
                             style="height: 200px; object-fit: contain; cursor: pointer;" 
                             alt="Screenshot ${screenshotNumber}"
                             onclick="showFullScreenshot('data:image/jpeg;base64,${feedback.screenshot1}', 'Screenshot ${screenshotNumber}')">
                        <div class="card-body p-2 text-center">
                            <small class="text-muted">Screenshot ${screenshotNumber}</small>
                        </div>
                    </div>
                </div>
            `;
            screenshotNumber++;
        }
        
        if (feedback.screenshot2) {
            screenshotsHtml += `
                <div class="col-md-4">
                    <div class="card">
                        <img src="data:image/jpeg;base64,${feedback.screenshot2}" 
                             class="card-img-top screenshot-thumb" 
                             style="height: 200px; object-fit: contain; cursor: pointer;" 
                             alt="Screenshot ${screenshotNumber}"
                             onclick="showFullScreenshot('data:image/jpeg;base64,${feedback.screenshot2}', 'Screenshot ${screenshotNumber}')">
                        <div class="card-body p-2 text-center">
                            <small class="text-muted">Screenshot ${screenshotNumber}</small>
                        </div>
                    </div>
                </div>
            `;
            screenshotNumber++;
        }
        
        if (feedback.screenshot3) {
            screenshotsHtml += `
                <div class="col-md-4">
                    <div class="card">
                        <img src="data:image/jpeg;base64,${feedback.screenshot3}" 
                             class="card-img-top screenshot-thumb" 
                             style="height: 200px; object-fit: contain; cursor: pointer;" 
                             alt="Screenshot ${screenshotNumber}"
                             onclick="showFullScreenshot('data:image/jpeg;base64,${feedback.screenshot3}', 'Screenshot ${screenshotNumber}')">
                        <div class="card-body p-2 text-center">
                            <small class="text-muted">Screenshot ${screenshotNumber}</small>
                        </div>
                    </div>
                </div>
            `;
        }
        
        screenshotsHtml += '</div>';
        
        // Add feedback context
        screenshotsHtml += `
            <hr class="mt-4">
            <h6>Feedback Context</h6>
            <div class="card bg-light">
                <div class="card-body">
                    <div class="row">
                        <div class="col-md-6">
                            <strong>User:</strong> ${feedback.user_name}<br>
                            <strong>Page:</strong> ${feedback.page_title}
                        </div>
                        <div class="col-md-6">
                            <strong>Date:</strong> ${new Date(feedback.timestamp).toLocaleString()}<br>
                            <strong>URL:</strong> <small>${feedback.current_url}</small>
                        </div>
                    </div>
                    <div class="mt-2">
                        <strong>Comments:</strong><br>
                        <div class="border rounded p-2 bg-white mt-1">${feedback.tester_comments}</div>
                    </div>
                </div>
            </div>
        `;
        
        document.getElementById('screenshotsContent').innerHTML = screenshotsHtml;
        document.getElementById('screenshotsModalLabel').textContent = `Screenshots - Feedback #${feedbackId}`;
        
        const modal = new bootstrap.Modal(document.getElementById('screenshotsModal'));
        modal.show();
        
    } catch (error) {
        console.error('Error loading screenshots:', error);
        showBootstrapAlert('Error', 'Failed to load screenshots', 'danger');
    }
}

// Function to show full-size screenshot
function showFullScreenshot(src, title) {
    // Remove any existing full-screenshot modals first
    const existingModals = document.querySelectorAll('.full-screenshot-modal');
    existingModals.forEach(m => {
        try {
            const existingInstance = bootstrap.Modal.getInstance(m);
            if (existingInstance) {
                existingInstance.dispose();
            }
            m.remove();
        } catch (e) {
            console.warn('Error removing existing modal:', e);
        }
    });
    
    // Remove any leftover modal backdrops
    const backdrops = document.querySelectorAll('.modal-backdrop');
    backdrops.forEach(backdrop => backdrop.remove());
    
    const modal = document.createElement('div');
    modal.className = 'modal fade full-screenshot-modal';
    modal.setAttribute('tabindex', '-1');
    modal.setAttribute('aria-hidden', 'true');
    modal.innerHTML = `
        <div class="modal-dialog modal-xl">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">${title}</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body text-center p-1">
                    <img src="${src}" class="img-fluid" alt="${title}" style="max-width: 100%; height: auto; max-height: 80vh; object-fit: contain;">
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                    <a href="${src}" download="${title.replace(/\s+/g, '_')}.jpg" class="btn btn-primary">
                        <i class="fas fa-download me-1"></i>Download
                    </a>
                </div>
            </div>
        </div>
    `;
    document.body.appendChild(modal);
    
    const bootstrapModal = new bootstrap.Modal(modal, {
        backdrop: true,
        keyboard: true,
        focus: true
    });
    
    // Function to clean up modal completely
    const cleanupModal = () => {
        try {
            bootstrapModal.dispose();
            if (modal.parentNode) {
                modal.parentNode.removeChild(modal);
            }
            // Remove any remaining backdrops
            setTimeout(() => {
                const remainingBackdrops = document.querySelectorAll('.modal-backdrop');
                remainingBackdrops.forEach(backdrop => backdrop.remove());
                // Restore body scroll
                document.body.classList.remove('modal-open');
                document.body.style.removeProperty('overflow');
                document.body.style.removeProperty('padding-right');
            }, 150);
        } catch (e) {
            console.warn('Error during modal cleanup:', e);
        }
    };
    
    // Multiple cleanup event listeners
    modal.addEventListener('hidden.bs.modal', cleanupModal);
    
    // Escape key cleanup
    const escapeHandler = (e) => {
        if (e.key === 'Escape') {
            cleanupModal();
            document.removeEventListener('keydown', escapeHandler);
        }
    };
    document.addEventListener('keydown', escapeHandler);
    
    // Show the modal
    bootstrapModal.show();
}

// Open reply modal
async function openReplyModal(feedbackId, userName, userId) {
    document.getElementById('replyFeedbackId').value = feedbackId;
    document.getElementById('replyUserId').value = userId;
    document.getElementById('replyRecipient').value = userName;
    document.getElementById('replyMessage').value = '';
    document.getElementById('markResolvedOnReply').checked = true;
    
    // Load existing reply if one exists
    try {
        const response = await fetch(`/api/alpha-feedback/${feedbackId}`);
        if (response.ok) {
            const feedback = await response.json();
            if (feedback.admin_reply) {
                document.getElementById('replyMessage').value = feedback.admin_reply;
                // Change modal title to indicate editing
                document.getElementById('replyModalLabel').textContent = 'View/Edit Reply to User';
            } else {
                document.getElementById('replyModalLabel').textContent = 'Reply to User';
            }
        }
    } catch (error) {
        console.error('Error loading existing reply:', error);
    }
    
    const modal = new bootstrap.Modal(document.getElementById('replyModal'));
    modal.show();
}

// Send reply to user
async function sendReply() {
    const feedbackId = document.getElementById('replyFeedbackId').value;
    const userId = document.getElementById('replyUserId').value;
    const message = document.getElementById('replyMessage').value.trim();
    const markResolved = document.getElementById('markResolvedOnReply').checked;
    
    if (!message) {
        showBootstrapAlert('Validation Error', 'Please enter a reply message', 'warning');
        return;
    }
    
    try {
        const response = await fetch('/api/alpha-feedback/reply', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                feedbackId: parseInt(feedbackId),
                userId: parseInt(userId),
                message: message,
                markResolved: markResolved
            })
        });
        
        const result = await response.json();
        
        if (response.ok && result.success) {
            // Close modal
            const modal = bootstrap.Modal.getInstance(document.getElementById('replyModal'));
            modal.hide();
            
            // Update the reply column for this feedback
            const row = document.querySelector(`tr[data-feedback-id="${feedbackId}"]`);
            if (row) {
                const replyCell = row.querySelector('td:nth-child(4)'); // Reply column is 4th
                if (replyCell) {
                    const userName = document.getElementById('replyRecipient').value;
                    replyCell.innerHTML = `<a href="#" class="btn btn-sm btn-outline-primary" onclick="openReplyModal(${feedbackId}, '${userName.replace(/'/g, "\\'")}', ${userId})" title="View/Edit Reply">
                        <i class="fas fa-reply" style="color: #0d6efd;"></i>
                    </a>`;
                }
                
                // If marked as resolved, update the row
                if (markResolved) {
                    row.classList.remove('table-warning');
                    row.dataset.resolved = 'true';
                    
                    // Update status badge
                    const statusCell = row.querySelector('.status-badge');
                    if (statusCell) {
                        statusCell.innerHTML = '<span class="badge bg-success">Resolved</span>';
                    }
                    
                    // Update resolve button
                    const resolveBtn = row.querySelector(`button[onclick*="markResolved(${feedbackId})"]`);
                    if (resolveBtn) {
                        resolveBtn.disabled = true;
                        resolveBtn.innerHTML = '<i class="fas fa-check text-success"></i>';
                        resolveBtn.title = 'Already Resolved';
                        resolveBtn.classList.remove('btn-success');
                        resolveBtn.classList.add('btn-outline-success');
                    }
                    
                    // Update counters
                    updateCounters();
                }
            }
            
            showBootstrapAlert('Success', 'Reply saved successfully', 'success');
        } else {
            showBootstrapAlert('Error', result.message || 'Failed to send reply', 'danger');
        }
    } catch (error) {
        console.error('Error sending reply:', error);
        showBootstrapAlert('Connection Error', 'Error sending reply. Please try again.', 'danger');
    }
}

</script>

<!-- Screenshots Modal -->
<div class="modal fade" id="screenshotsModal" tabindex="-1" aria-labelledby="screenshotsModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-xl">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="screenshotsModalLabel">Screenshots</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body" id="screenshotsContent">
                <!-- Screenshots loaded dynamically -->
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>

{% endblock %}