// Tube Link Fixer Extension - Popup Script with Enhanced UI

const API_BASE_URL = 'https://tube-link-fixer.vercel.app';

// DOM Elements
let connectionStatus, notYoutubeWarning, loginSection, accountSection, scanSection, resultsSection;
let loginBtn, scanBtn, rescanBtn;
let userAvatar, userName, userEmail, userPlan;
let videoThumbnail, videoTitle, videoChannel;
let progressSection, progressFill, progressText;
let totalLinksEl, validLinksEl, brokenLinksEl, resultsList;
let totalScans, linksChecked, issuesFound;
let refreshBtn, creditsDisplay, creditsProgressFill;
let userCredits = { used: 0, limit: 0, remaining: 0 };

// State
let isConnected = false;
let currentTab = null;
let scanResults = [];
let sessionStats = { scans: 0, links: 0, issues: 0 };

// Initialize popup
document.addEventListener('DOMContentLoaded', async () => {
    // Get DOM elements
    connectionStatus = document.getElementById('connectionStatus');
    notYoutubeWarning = document.getElementById('notYoutubeWarning');
    loginSection = document.getElementById('loginSection');
    accountSection = document.getElementById('accountSection');
    scanSection = document.getElementById('scanSection');
    resultsSection = document.getElementById('resultsSection');

    loginBtn = document.getElementById('loginBtn');
    scanBtn = document.getElementById('scanBtn');
    rescanBtn = document.getElementById('rescanBtn');

    userAvatar = document.getElementById('userAvatar');
    userName = document.getElementById('userName');
    userEmail = document.getElementById('userEmail');
    userPlan = document.getElementById('userPlan');

    videoThumbnail = document.getElementById('videoThumbnail');
    videoTitle = document.getElementById('videoTitle');
    videoChannel = document.getElementById('videoChannel');

    progressSection = document.getElementById('progressSection');
    progressFill = document.getElementById('progressFill');
    progressText = document.getElementById('progressText');

    totalLinksEl = document.getElementById('totalLinks');
    validLinksEl = document.getElementById('validLinks');
    brokenLinksEl = document.getElementById('brokenLinks');
    resultsList = document.getElementById('resultsList');

    totalScans = document.getElementById('totalScans');
    linksChecked = document.getElementById('linksChecked');
    issuesFound = document.getElementById('issuesFound');

    refreshBtn = document.getElementById('refreshBtn');
    creditsDisplay = document.getElementById('creditsDisplay');
    creditsProgressFill = document.getElementById('creditsProgressFill');

    // Load session stats
    const statsData = await chrome.storage.local.get(['sessionStats']);
    if (statsData.sessionStats) {
        sessionStats = statsData.sessionStats;
    }

    await checkCurrentTab();
    await loadStoredCredentials();
    setupEventListeners();
});

// Check if we're on a YouTube video page
async function checkCurrentTab() {
    const tabs = await chrome.tabs.query({ active: true, currentWindow: true });
    currentTab = tabs[0];

    if (!currentTab.url || !currentTab.url.includes('youtube.com/watch')) {
        showNotYoutubeWarning();
        return false;
    }
    return true;
}

// Show warning when not on YouTube
function showNotYoutubeWarning() {
    if (notYoutubeWarning) notYoutubeWarning.style.display = 'flex';
    if (loginSection) loginSection.style.display = 'none';
    if (accountSection) accountSection.style.display = 'none';
    if (scanSection) scanSection.style.display = 'none';
    if (resultsSection) resultsSection.style.display = 'none';
}

// Load stored credentials
async function loadStoredCredentials() {
    const data = await chrome.storage.sync.get(['userInfo', 'authToken']);

    if (data.authToken && data.userInfo) {
        isConnected = true;
        updateConnectionStatus(true);
        showAccountSection(data.userInfo);
        await loadVideoInfo();
        return;
    }

    showLoginSection();
}

// Setup event listeners
function setupEventListeners() {
    if (loginBtn) loginBtn.addEventListener('click', handleLogin);
    if (scanBtn) scanBtn.addEventListener('click', handleScan);
    if (rescanBtn) rescanBtn.addEventListener('click', handleScan);
    if (refreshBtn) refreshBtn.addEventListener('click', handleRefresh);

    chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
        if (message.type === 'Tube Link Fixer_AUTH_SUCCESS') {
            handleAuthSuccess(message.token, message.userInfo);
        }
    });
}

// Handle successful authentication
function handleAuthSuccess(token, userInfo) {
    chrome.storage.sync.set({ authToken: token, userInfo: userInfo }, () => {
        isConnected = true;
        updateConnectionStatus(true);
        showAccountSection(userInfo);
        loadVideoInfo();

        if (loginBtn) {
            loginBtn.disabled = false;
            loginBtn.innerHTML = `
        <svg class="btn-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
          <path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/>
        </svg>
        Login with Tube Link Fixer
      `;
        }
    });
}

// Handle login
async function handleLogin() {
    if (loginBtn) {
        loginBtn.disabled = true;
        loginBtn.innerHTML = `
      <div class="progress-spinner" style="width:18px;height:18px;border-width:2px;"></div>
      Opening login...
    `;
    }

    try {
        const authUrl = `${API_BASE_URL}/extension-auth`;
        chrome.windows.create({
            url: authUrl,
            type: 'popup',
            width: 500,
            height: 700,
            focused: true
        });

        setTimeout(() => {
            if (loginBtn && loginBtn.disabled) {
                loginBtn.disabled = false;
                loginBtn.innerHTML = `
          <svg class="btn-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
            <path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/>
          </svg>
          Login with Tube Link Fixer
        `;
            }
        }, 60000);

    } catch (error) {
        console.error('Login failed:', error);
        if (loginBtn) {
            loginBtn.disabled = false;
            loginBtn.innerHTML = `
        <svg class="btn-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
          <path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/>
        </svg>
        Login with Tube Link Fixer
      `;
        }
    }
}

// Handle logout
async function handleLogout() {
    await chrome.storage.sync.remove(['authToken', 'userInfo']);
    isConnected = false;
    updateConnectionStatus(false);
    showLoginSection();
}

// Update connection status badge
function updateConnectionStatus(connected) {
    if (!connectionStatus) return;

    if (connected) {
        connectionStatus.classList.add('connected');
        connectionStatus.querySelector('.status-text').textContent = 'Connected';
    } else {
        connectionStatus.classList.remove('connected');
        connectionStatus.querySelector('.status-text').textContent = 'Disconnected';
    }
}

// Show login section
function showLoginSection() {
    if (loginSection) loginSection.style.display = 'block';
    if (accountSection) accountSection.style.display = 'none';
    if (scanSection) scanSection.style.display = 'none';
    if (resultsSection) resultsSection.style.display = 'none';
}

// Show account section
async function showAccountSection(userInfo) {
    if (loginSection) loginSection.style.display = 'none';
    if (accountSection) accountSection.style.display = 'block';

    // Update user info
    const displayName = userInfo.displayName || userInfo.email?.split('@')[0] || 'User';
    if (userName) userName.textContent = `Welcome, ${displayName}!`;
    if (userEmail) userEmail.textContent = userInfo.email || '';
    if (userAvatar) userAvatar.textContent = (displayName)[0].toUpperCase();
    if (userPlan) {
        const planName = userInfo.plan || 'Free';
        userPlan.innerHTML = `
      <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
        <polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"/>
      </svg>
      ${planName} Plan
    `;
    }

    // Update stats
    updateStats();

    // Check if on YouTube
    if (currentTab && currentTab.url && currentTab.url.includes('youtube.com/watch')) {
        if (scanSection) scanSection.style.display = 'block';
    }

    // Load credits from server
    await loadCreditsFromServer(userInfo);
}

// Update session stats display
function updateStats() {
    if (totalScans) totalScans.textContent = sessionStats.scans;
    if (linksChecked) linksChecked.textContent = sessionStats.links;
    if (issuesFound) issuesFound.textContent = sessionStats.issues;
}

// Load credits from server
async function loadCreditsFromServer(userInfo) {
    if (!userInfo?.uid) return;

    try {
        const response = await fetch(`${API_BASE_URL}/api/extension/sync?userId=${userInfo.uid}`);
        if (response.ok) {
            const data = await response.json();
            userCredits = {
                used: data.creditsUsed || 0,
                limit: data.creditsLimit || 0,
                remaining: data.creditsRemaining || 0
            };
            updateCreditsDisplay();

            // Update plan display if plan info is returned
            if (data.plan) {
                updatePlanDisplay(data.plan);

                // Update stored userInfo with new plan
                const storedData = await chrome.storage.sync.get(['userInfo']);
                if (storedData.userInfo) {
                    storedData.userInfo.plan = data.plan;
                    await chrome.storage.sync.set({ userInfo: storedData.userInfo });
                }
            }
        }
    } catch (error) {
        console.error('Failed to load credits:', error);
    }
}

// Update plan display in UI
function updatePlanDisplay(planName) {
    if (userPlan) {
        userPlan.innerHTML = `
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                <polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"/>
            </svg>
            ${planName} Plan
        `;
    }
}

// Update credits display in UI
function updateCreditsDisplay() {
    if (creditsDisplay) {
        if (userCredits.limit >= 999999) {
            creditsDisplay.textContent = 'Unlimited';
        } else {
            creditsDisplay.textContent = `${userCredits.used} / ${userCredits.limit}`;
        }
    }

    if (creditsProgressFill) {
        const percentage = userCredits.limit >= 999999 ? 0 : Math.min((userCredits.used / userCredits.limit) * 100, 100);
        creditsProgressFill.style.width = `${percentage}%`;

        // Update color based on usage
        creditsProgressFill.classList.remove('warning', 'danger');
        if (percentage >= 90) {
            creditsProgressFill.classList.add('danger');
        } else if (percentage >= 70) {
            creditsProgressFill.classList.add('warning');
        }
    }
}

// Handle refresh button click
async function handleRefresh() {
    if (refreshBtn) {
        refreshBtn.classList.add('refreshing');
        refreshBtn.disabled = true;
    }

    try {
        const data = await chrome.storage.sync.get(['userInfo']);
        if (data.userInfo) {
            await loadCreditsFromServer(data.userInfo);
        }
    } catch (error) {
        console.error('Refresh failed:', error);
    } finally {
        if (refreshBtn) {
            refreshBtn.classList.remove('refreshing');
            refreshBtn.disabled = false;
        }
    }
}

// Save session stats
async function saveStats() {
    await chrome.storage.local.set({ sessionStats });
    updateStats();
}

// Load video info from current tab
async function loadVideoInfo() {
    if (!currentTab || !currentTab.url || !currentTab.url.includes('youtube.com/watch')) return;

    if (scanSection) scanSection.style.display = 'block';

    try {
        const url = new URL(currentTab.url);
        const videoId = url.searchParams.get('v');

        if (videoId && videoThumbnail) {
            videoThumbnail.style.backgroundImage = `url(https://i.ytimg.com/vi/${videoId}/mqdefault.jpg)`;
        }

        if (videoTitle) {
            let title = currentTab.title.replace(' - YouTube', '');
            if (title.length > 60) title = title.substring(0, 60) + '...';
            videoTitle.textContent = title;
        }

        // Check if we have existing results for this video
        const existingData = await chrome.storage.local.get(['lastScanResults']);
        if (existingData.lastScanResults && existingData.lastScanResults.video?.id === videoId) {
            // Show "View Results" option
            if (videoChannel) {
                const timeAgo = formatTimeAgo(existingData.lastScanResults.timestamp);
                videoChannel.innerHTML = `
                    <span style="color: #10b981;">✓ Scanned ${timeAgo}</span>
                    <button id="viewResultsBtn" style="
                        margin-left: 8px;
                        padding: 4px 8px;
                        background: #2563eb;
                        color: white;
                        border: none;
                        border-radius: 6px;
                        font-size: 11px;
                        cursor: pointer;
                    ">View Results</button>
                `;

                // Add click handler for view results button
                setTimeout(() => {
                    const viewBtn = document.getElementById('viewResultsBtn');
                    if (viewBtn) {
                        viewBtn.addEventListener('click', () => {
                            window.location.href = 'results.html';
                        });
                    }
                }, 0);
            }
        } else {
            if (videoChannel) videoChannel.textContent = 'Click scan to check description links';
        }

    } catch (error) {
        console.error('Error loading video info:', error);
    }
}

// Format time ago helper
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)}m ago`;
    if (seconds < 86400) return `${Math.floor(seconds / 3600)}h ago`;
    return new Date(timestamp).toLocaleDateString();
}

// Handle scan button click
async function handleScan() {
    // Check if credits are available before scanning
    if (userCredits.limit > 0 && userCredits.used >= userCredits.limit) {
        // No credits remaining - show error
        if (progressSection) progressSection.style.display = 'block';
        if (progressFill) progressFill.style.width = '100%';
        if (progressFill) progressFill.classList.add('danger');
        if (progressText) {
            progressText.innerHTML = `
                <span style="color: #ef4444; font-weight: 600;">⚠️ No Credits Remaining</span><br>
                <span style="font-size: 11px; color: #6b7280;">You've used all ${userCredits.limit} credits this month. Please upgrade your plan or wait for credits to reset.</span>
            `;
        }
        // Re-enable buttons after delay
        setTimeout(() => {
            if (progressSection) progressSection.style.display = 'none';
            if (progressFill) progressFill.classList.remove('danger');
        }, 5000);
        return;
    }

    // Check if user has no credits assigned at all (limit is 0)
    if (userCredits.limit === 0) {
        if (progressSection) progressSection.style.display = 'block';
        if (progressFill) progressFill.style.width = '100%';
        if (progressFill) progressFill.classList.add('danger');
        if (progressText) {
            progressText.innerHTML = `
                <span style="color: #ef4444; font-weight: 600;">⚠️ No Credits Available</span><br>
                <span style="font-size: 11px; color: #6b7280;">Your plan doesn't include extension credits. Please upgrade or contact support.</span>
            `;
        }
        setTimeout(() => {
            if (progressSection) progressSection.style.display = 'none';
            if (progressFill) progressFill.classList.remove('danger');
        }, 5000);
        return;
    }

    if (scanBtn) scanBtn.disabled = true;
    if (rescanBtn) rescanBtn.disabled = true;
    if (resultsSection) resultsSection.style.display = 'none';
    if (progressSection) progressSection.style.display = 'block';
    if (progressFill) progressFill.style.width = '0%';
    if (progressText) progressText.textContent = 'Extracting links from description...';

    try {
        const response = await chrome.tabs.sendMessage(currentTab.id, { action: 'extractLinks' });

        if (!response || !response.links || response.links.length === 0) {
            if (progressText) progressText.textContent = 'No links found in description';
            setTimeout(() => {
                if (progressSection) progressSection.style.display = 'none';
                if (scanBtn) scanBtn.disabled = false;
            }, 2000);
            return;
        }

        const links = response.links;
        if (progressText) progressText.textContent = `Found ${links.length} links. Checking...`;
        if (progressFill) progressFill.style.width = '10%';

        scanResults = [];
        for (let i = 0; i < links.length; i++) {
            const link = links[i];
            const progress = 10 + ((i + 1) / links.length * 90);
            if (progressFill) progressFill.style.width = `${progress}%`;
            if (progressText) progressText.textContent = `Checking link ${i + 1} of ${links.length}...`;

            const result = await checkLink(link);
            scanResults.push(result);
        }

        // Update session stats
        sessionStats.scans++;
        sessionStats.links += links.length;
        sessionStats.issues += scanResults.filter(r => r.status === 'broken').length;
        await saveStats();

        // Get video info for results page
        const url = new URL(currentTab.url);
        const videoId = url.searchParams.get('v');
        const videoInfo = {
            id: videoId,
            title: currentTab.title.replace(' - YouTube', ''),
            thumbnail: videoId ? `https://i.ytimg.com/vi/${videoId}/mqdefault.jpg` : null,
            url: currentTab.url
        };

        // Save scan results to storage for the results page
        const scanData = {
            video: videoInfo,
            results: scanResults,
            timestamp: Date.now(),
            totalLinks: scanResults.length,
            validCount: scanResults.filter(r => r.status === 'valid').length,
            brokenCount: scanResults.filter(r => r.status === 'broken').length,
            warningCount: scanResults.filter(r => r.status === 'warning' || r.status === 'redirect').length
        };

        await chrome.storage.local.set({ lastScanResults: scanData });

        // Sync results to server (deduct credits)
        try {
            const userData = await chrome.storage.sync.get(['userInfo']);
            if (userData.userInfo?.uid) {
                // Generate unique request ID to prevent replay attacks
                const requestId = `${userData.userInfo.uid}_${Date.now()}_${Math.random().toString(36).substring(7)}`;

                const syncResponse = await fetch(`${API_BASE_URL}/api/extension/sync`, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({
                        userId: userData.userInfo.uid,
                        videoId: videoId,
                        videoTitle: videoInfo.title,
                        videoUrl: videoInfo.url,
                        results: scanResults,
                        scanTimestamp: Date.now(),
                        requestId: requestId
                    })
                });

                if (syncResponse.ok) {
                    const syncData = await syncResponse.json();
                    userCredits = {
                        used: syncData.creditsUsed || 0,
                        limit: syncData.creditsLimit || 0,
                        remaining: syncData.creditsRemaining || 0
                    };
                    console.log('Scan synced, credits:', userCredits);
                } else {
                    // Handle security-related errors
                    const errorData = await syncResponse.json().catch(() => ({}));
                    console.error('Sync failed:', errorData.code || syncResponse.status);

                    if (errorData.code === 'CREDIT_LIMIT_REACHED' || errorData.code === 'NO_CREDITS') {
                        userCredits = {
                            used: errorData.creditsUsed || userCredits.limit,
                            limit: errorData.creditsLimit || 0,
                            remaining: 0
                        };
                    }
                }
            }
        } catch (syncError) {
            console.error('Failed to sync results:', syncError);
        }

        // Redirect to results page
        if (progressText) progressText.textContent = 'Scan complete! Loading results...';
        setTimeout(() => {
            window.location.href = 'results.html';
        }, 500);

    } catch (error) {
        console.error('Scan error:', error);
        if (progressText) progressText.textContent = 'Error: Could not scan. Try refreshing the page.';
        setTimeout(() => {
            if (progressSection) progressSection.style.display = 'none';
        }, 3000);
    } finally {
        if (scanBtn) scanBtn.disabled = false;
        if (rescanBtn) rescanBtn.disabled = false;
    }
}

// Check a single link
async function checkLink(url) {
    return new Promise((resolve) => {
        chrome.runtime.sendMessage({ action: 'checkLink', url }, (response) => {
            resolve(response || { url, status: 'unknown', code: null });
        });
    });
}

// Display scan results
function displayResults(results) {
    if (progressSection) progressSection.style.display = 'none';
    if (resultsSection) resultsSection.style.display = 'block';

    const total = results.length;
    const valid = results.filter(r => r.status === 'valid').length;
    const broken = results.filter(r => r.status === 'broken').length;

    if (totalLinksEl) totalLinksEl.textContent = total;
    if (validLinksEl) validLinksEl.textContent = valid;
    if (brokenLinksEl) brokenLinksEl.textContent = broken;

    if (resultsList) {
        resultsList.innerHTML = '';

        const sortedResults = [...results].sort((a, b) => {
            const order = { broken: 0, redirect: 1, valid: 2 };
            return (order[a.status] || 2) - (order[b.status] || 2);
        });

        if (sortedResults.length === 0) {
            resultsList.innerHTML = '<div class="result-item"><span class="result-url">No links found</span></div>';
            return;
        }

        sortedResults.forEach(result => {
            const item = document.createElement('div');
            item.className = 'result-item';

            const iconSvg = getStatusIcon(result.status);
            const statusClass = result.status;
            const statusText = getStatusText(result.status, result.code);

            item.innerHTML = `
        ${iconSvg}
        <span class="result-url" title="${result.url}">${truncateUrl(result.url, 35)}</span>
        <span class="result-status ${statusClass}">${statusText}</span>
      `;

            resultsList.appendChild(item);
        });
    }
}

// Get SVG icon for status
function getStatusIcon(status) {
    if (status === 'valid') {
        return `<svg class="result-icon valid" 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 class="result-icon broken" 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 class="result-icon redirect" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
      <polyline points="9 18 15 12 9 6"/>
    </svg>`;
    }
}

// Get status text
function getStatusText(status, code) {
    if (status === 'valid') return 'OK';
    if (status === 'broken') return code ? `${code}` : 'Error';
    if (status === 'redirect') return 'Redirect';
    return 'Unknown';
}

// Truncate URL for display
function truncateUrl(url, maxLength) {
    try {
        const parsed = new URL(url);
        let display = parsed.hostname + parsed.pathname;
        if (display.length > maxLength) {
            display = display.substring(0, maxLength - 3) + '...';
        }
        return display;
    } catch {
        return url.length > maxLength ? url.substring(0, maxLength - 3) + '...' : url;
    }
}
