// Tube Link Fixer Extension - Results Page Script

let scanData = null;
let currentFilter = 'all';

// DOM Elements
let videoThumbnail, videoTitle, scanTime;
let totalCount, validCount, brokenCount, warningCount;
let resultsList, emptyState;

// Initialize
document.addEventListener('DOMContentLoaded', async () => {
    // Get DOM elements
    videoThumbnail = document.getElementById('videoThumbnail');
    videoTitle = document.getElementById('videoTitle');
    scanTime = document.getElementById('scanTime');

    totalCount = document.getElementById('totalCount');
    validCount = document.getElementById('validCount');
    brokenCount = document.getElementById('brokenCount');
    warningCount = document.getElementById('warningCount');

    resultsList = document.getElementById('resultsList');
    emptyState = document.getElementById('emptyState');

    // Load scan data
    await loadScanData();

    // Setup event listeners
    setupEventListeners();
});

// Load scan data from storage
async function loadScanData() {
    const data = await chrome.storage.local.get(['lastScanResults']);

    if (data.lastScanResults) {
        scanData = data.lastScanResults;
        displayResults();
    } else {
        // No data, go back to popup
        window.location.href = 'popup.html';
    }
}

// Setup event listeners
function setupEventListeners() {
    // Back button
    document.getElementById('backBtn').addEventListener('click', () => {
        window.location.href = 'popup.html';
    });

    // Rescan button
    document.getElementById('rescanBtn').addEventListener('click', async () => {
        // Clear current results and go back to popup for rescan
        await chrome.storage.local.remove(['lastScanResults']);
        window.location.href = 'popup.html';
    });

    // Filter tabs
    document.querySelectorAll('.filter-tab').forEach(tab => {
        tab.addEventListener('click', () => {
            document.querySelectorAll('.filter-tab').forEach(t => t.classList.remove('active'));
            tab.classList.add('active');
            currentFilter = tab.dataset.filter;
            renderResultsList();
        });
    });

    // Summary card clicks
    document.querySelectorAll('.summary-card[data-filter]').forEach(card => {
        card.addEventListener('click', () => {
            const filter = card.dataset.filter;
            document.querySelectorAll('.filter-tab').forEach(t => {
                t.classList.toggle('active', t.dataset.filter === filter);
            });
            currentFilter = filter;
            renderResultsList();
        });
    });
}

// Display results
function displayResults() {
    if (!scanData) return;

    // Video info
    if (videoThumbnail && scanData.video?.thumbnail) {
        videoThumbnail.style.backgroundImage = `url(${scanData.video.thumbnail})`;
    }
    if (videoTitle && scanData.video?.title) {
        videoTitle.textContent = scanData.video.title;
    }
    if (scanTime && scanData.timestamp) {
        scanTime.textContent = formatTimeAgo(scanData.timestamp);
    }

    // Count results by status
    const results = scanData.results || [];
    const counts = {
        total: results.length,
        valid: results.filter(r => r.status === 'valid').length,
        broken: results.filter(r => r.status === 'broken').length,
        warning: results.filter(r => r.status === 'warning' || r.status === 'redirect').length
    };

    // Update counts
    if (totalCount) totalCount.textContent = counts.total;
    if (validCount) validCount.textContent = counts.valid;
    if (brokenCount) brokenCount.textContent = counts.broken;
    if (warningCount) warningCount.textContent = counts.warning;

    // Render links list
    renderResultsList();
}

// Render filtered results list
function renderResultsList() {
    if (!resultsList || !scanData?.results) return;

    let results = scanData.results;

    // Apply filter
    if (currentFilter !== 'all') {
        if (currentFilter === 'warning') {
            results = results.filter(r => r.status === 'warning' || r.status === 'redirect');
        } else {
            results = results.filter(r => r.status === currentFilter);
        }
    }

    // Sort: broken first, then warnings, then valid
    results.sort((a, b) => {
        const order = { broken: 0, warning: 1, redirect: 1, valid: 2 };
        return (order[a.status] ?? 2) - (order[b.status] ?? 2);
    });

    // Show empty state if no results
    if (results.length === 0) {
        resultsList.style.display = 'none';
        emptyState.style.display = 'flex';
        return;
    }

    resultsList.style.display = 'flex';
    emptyState.style.display = 'none';

    // Build HTML
    resultsList.innerHTML = results.map(result => {
        const statusClass = result.status === 'redirect' ? 'warning' : result.status;
        const statusText = getStatusText(result);
        const domain = getDomain(result.url);
        const icon = getStatusIcon(statusClass);

        return `
      <div class="result-item" data-url="${escapeHtml(result.url)}">
        <div class="result-icon ${statusClass}">
          ${icon}
        </div>
        <div class="result-content">
          <div class="result-url">${escapeHtml(result.url)}</div>
          <div class="result-domain">${escapeHtml(domain)}</div>
        </div>
        <span class="result-status ${statusClass}">${statusText}</span>
        <button class="result-action" title="Open link" onclick="window.open('${escapeHtml(result.url)}', '_blank')">
          <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
            <path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"/>
            <polyline points="15 3 21 3 21 9"/>
            <line x1="10" y1="14" x2="21" y2="3"/>
          </svg>
        </button>
      </div>
    `;
    }).join('');
}

// Get status text
function getStatusText(result) {
    if (result.status === 'valid') return 'OK';
    if (result.status === 'broken') {
        if (result.code === 'TIMEOUT') return 'Timeout';
        if (result.code === 'ERROR') return 'Error';
        return result.code || 'Broken';
    }
    if (result.status === 'warning' || result.status === 'redirect') return 'Warning';
    return 'Unknown';
}

// Get status icon SVG
function getStatusIcon(status) {
    if (status === 'valid') {
        return `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
      <polyline points="20 6 9 17 4 12"/>
    </svg>`;
    } else if (status === 'broken') {
        return `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
      <circle cx="12" cy="12" r="10"/>
      <line x1="15" y1="9" x2="9" y2="15"/>
      <line x1="9" y1="9" x2="15" y2="15"/>
    </svg>`;
    } else {
        return `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
      <circle cx="12" cy="12" r="10"/>
      <line x1="12" y1="8" x2="12" y2="12"/>
      <line x1="12" y1="16" x2="12.01" y2="16"/>
    </svg>`;
    }
}

// Get domain from URL
function getDomain(url) {
    try {
        return new URL(url).hostname;
    } catch {
        return url;
    }
}

// Format time ago
function formatTimeAgo(timestamp) {
    const seconds = Math.floor((Date.now() - timestamp) / 1000);

    if (seconds < 60) return 'Just now';
    if (seconds < 3600) return `${Math.floor(seconds / 60)} min ago`;
    if (seconds < 86400) return `${Math.floor(seconds / 3600)} hours ago`;
    return new Date(timestamp).toLocaleDateString();
}

// Escape HTML
function escapeHtml(text) {
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
}
