// GigLez - Capture Detail Modal

async function viewCaptureDetails(captureId) {
    console.log('viewCaptureDetails called with ID:', captureId);

    const modal = document.getElementById('detail-modal');
    const modalBody = document.getElementById('modal-body-content');

    console.log('Modal element:', modal);
    console.log('Modal body element:', modalBody);

    // Show loading state
    modal.classList.add('active');
    modalBody.innerHTML = '<div style="text-align: center; padding: 2rem;">Loading...</div>';

    console.log('Loading state set, about to fetch from:', `/api/v1/captures/${captureId}`);

    try {
        // Fetch capture details with cache-busting
        const cacheBuster = Date.now();
        const response = await fetch(`/api/v1/captures/${captureId}?_=${cacheBuster}`, {
            method: 'GET',
            headers: {
                'Cache-Control': 'no-cache, no-store, must-revalidate',
                'Pragma': 'no-cache',
                'Expires': '0'
            }
        });

        console.log('Response status:', response.status);
        console.log('Response ok:', response.ok);

        if (!response.ok) {
            throw new Error('Failed to fetch capture details');
        }

        const data = await response.json();
        console.log('Received data:', data);

        if (!data.success) {
            throw new Error(data.message);
        }

        console.log('About to render capture:', data.capture);

        // Render detail view
        const renderedHtml = renderCaptureDetail(data.capture);
        console.log('Rendered HTML length:', renderedHtml.length);

        modalBody.innerHTML = renderedHtml;
        console.log('Modal body innerHTML set');

    } catch (error) {
        console.error('Error in viewCaptureDetails:', error);
        modalBody.innerHTML = `
            <div style="text-align: center; padding: 2rem; color: var(--danger-color);">
                <p><strong>Error loading details:</strong></p>
                <p>${error.message}</p>
            </div>
        `;
    }
}

function renderCaptureDetail(capture) {
    const freqMHz = (capture.frequency / 1e6).toFixed(2);
    const date = new Date(capture.timestamp || Date.now()).toLocaleString();

    // Device identification section
    const deviceSection = capture.device_name ? renderDeviceSection(capture) : renderNoDeviceSection();

    // Matched devices section
    const matchedSection = capture.matched_devices && capture.matched_devices.length > 0
        ? renderMatchedDevices(capture.matched_devices)
        : '';

    return `
        <!-- Device Identification -->
        ${deviceSection}

        <!-- Signal Information -->
        <div class="detail-section">
            <h3>Signal Information</h3>
            <div class="detail-grid">
                <div class="detail-item">
                    <span class="detail-label">Frequency</span>
                    <span class="detail-value highlight">${freqMHz} MHz</span>
                </div>
                <div class="detail-item">
                    <span class="detail-label">Protocol</span>
                    <span class="detail-value">${capture.protocol || 'RAW'}</span>
                </div>
                <div class="detail-item">
                    <span class="detail-label">Modulation</span>
                    <span class="detail-value">${capture.preset || 'Unknown'}</span>
                </div>
                <div class="detail-item">
                    <span class="detail-label">Filename</span>
                    <span class="detail-value">${capture.filename}</span>
                </div>
            </div>
        </div>

        <!-- Location Information -->
        <div class="detail-section">
            <h3>Location Information</h3>
            <div class="detail-grid">
                <div class="detail-item">
                    <span class="detail-label">Latitude</span>
                    <span class="detail-value">${capture.latitude.toFixed(6)}</span>
                </div>
                <div class="detail-item">
                    <span class="detail-label">Longitude</span>
                    <span class="detail-value">${capture.longitude.toFixed(6)}</span>
                </div>
                <div class="detail-item">
                    <span class="detail-label">GPS Source</span>
                    <span class="detail-value">${capture.gps_source || 'unknown'}</span>
                </div>
                <div class="detail-item">
                    <span class="detail-label">Timestamp</span>
                    <span class="detail-value">${date}</span>
                </div>
            </div>
        </div>

        ${matchedSection}

        <!-- Metadata -->
        <div class="detail-section">
            <h3>Metadata</h3>
            <div class="detail-grid">
                <div class="detail-item">
                    <span class="detail-label">Capture ID</span>
                    <span class="detail-value">${capture.id}</span>
                </div>
                <div class="detail-item">
                    <span class="detail-label">Data Source</span>
                    <span class="detail-value">${capture.data_source || 'production'}</span>
                </div>
                ${capture.session_id ? `
                <div class="detail-item">
                    <span class="detail-label">Session ID</span>
                    <span class="detail-value">${capture.session_id}</span>
                </div>
                ` : ''}
            </div>
        </div>
    `;
}

function renderDeviceSection(capture) {
    const confidencePercent = (capture.match_confidence * 100).toFixed(0);
    const confidenceClass = capture.match_confidence >= 0.8 ? '' :
                           capture.match_confidence >= 0.6 ? 'medium' : 'low';

    return `
        <div class="detail-section">
            <h3>Device Identification</h3>
            <div class="detail-grid">
                <div class="detail-item">
                    <span class="detail-label">Device Name</span>
                    <span class="detail-value highlight">${capture.device_name}</span>
                </div>
                <div class="detail-item">
                    <span class="detail-label">Category</span>
                    <span class="detail-value">${capture.device_category}</span>
                </div>
                <div class="detail-item">
                    <span class="detail-label">Match Method</span>
                    <span class="detail-value">${capture.match_method || 'unknown'}</span>
                </div>
                <div class="detail-item">
                    <span class="detail-label">Confidence</span>
                    <span class="detail-value">${confidencePercent}%</span>
                    <div class="confidence-bar">
                        <div class="confidence-fill ${confidenceClass}" style="width: ${confidencePercent}%"></div>
                    </div>
                </div>
            </div>
            ${capture.device_description ? `
            <div style="margin-top: 1rem; padding: 1rem; background: var(--light-bg); border-radius: 0.375rem;">
                <strong>Description:</strong> ${capture.device_description}
            </div>
            ` : ''}
        </div>
    `;
}

function renderNoDeviceSection() {
    return `
        <div class="detail-section">
            <h3>Device Identification</h3>
            <div style="padding: 2rem; text-align: center; background: var(--light-bg); border-radius: 0.375rem;">
                <p style="color: var(--text-secondary);">No device match found for this capture.</p>
                <p style="color: var(--text-secondary); font-size: 0.875rem; margin-top: 0.5rem;">
                    This could be an unknown or custom protocol.
                </p>
            </div>
        </div>
    `;
}

function renderMatchedDevices(matches) {
    if (!matches || matches.length === 0) return '';

    const matchesHtml = matches.map(match => {
        const confidencePercent = (match.confidence * 100).toFixed(0);
        return `
            <div class="matched-device-item">
                <div class="matched-device-header">
                    <span class="matched-device-name">${match.device_name}</span>
                    <span class="matched-device-confidence">${confidencePercent}%</span>
                </div>
                <span class="matched-device-category">${match.category}</span>
                <p class="matched-device-description">${match.description}</p>
                <p class="matched-device-method">Matched via: ${match.method}</p>
            </div>
        `;
    }).join('');

    return `
        <div class="detail-section">
            <h3>Alternative Matches</h3>
            <div class="matched-devices-list">
                ${matchesHtml}
            </div>
        </div>
    `;
}

function closeDetailModal() {
    const modal = document.getElementById('detail-modal');
    const modalBody = document.getElementById('modal-body-content');

    // Clear modal content to prevent stale data
    if (modalBody) {
        modalBody.innerHTML = '';
    }

    modal.classList.remove('active');
}

// Initialize modal event listeners
document.addEventListener('DOMContentLoaded', () => {
    const modal = document.getElementById('detail-modal');
    const closeBtn = document.getElementById('modal-close-btn');

    // Close button click
    if (closeBtn) {
        closeBtn.addEventListener('click', (e) => {
            e.preventDefault();
            e.stopPropagation();
            closeDetailModal();
        });
    }

    // Click outside modal
    if (modal) {
        modal.addEventListener('click', (e) => {
            if (e.target === modal) {
                closeDetailModal();
            }
        });
    }

    // Escape key
    document.addEventListener('keydown', (e) => {
        if (e.key === 'Escape' && modal && modal.classList.contains('active')) {
            closeDetailModal();
        }
    });

    console.log('Detail modal initialized');
});

// Export for use in other modules
window.viewCaptureDetails = viewCaptureDetails;
window.closeDetailModal = closeDetailModal;
