let currentPercent = 0;
let hashInterval;
let progressAnimation; // Add this to track the animation interval
const progressBarLength = 18;

// Function to generate a random hash
function generateRandomHash(length = 4) {
    const chars = "01234567890";
    let hash = "";
    for (let i = 0; i < length; i++) {
        hash += chars[Math.floor(Math.random() * chars.length)];
    }
    return hash;
}

// Function to generate a random symbol
function generateRandomSymbol() {
    const symbols = "!@#$%^&*()_+-=[]{}|;:,.<>?";
    return symbols[Math.floor(Math.random() * symbols.length)];
}

// Function to update the loading hash with a random symbol effect on "Hacking ..."
function updateLoadingHash() {
    const loadingHash = document.getElementById("loading-hash");
    if (!loadingHash) return;
    
    const originalText = "Hacking ...";
    let textArray = originalText.split("");

    // Clear any existing interval first
    if (hashInterval) {
        clearInterval(hashInterval);
    }

    hashInterval = setInterval(() => {
        const randomIndex = Math.floor(Math.random() * textArray.length);
        const originalChar = textArray[randomIndex];

        textArray[randomIndex] = generateRandomSymbol();
        const modifiedText = textArray.join("");

        loadingHash.textContent = `${modifiedText} X:${generateRandomHash()} , Y:${generateRandomHash()}`;

        setTimeout(() => {
            textArray[randomIndex] = originalChar;
            loadingHash.textContent = `${textArray.join("")} X:${generateRandomHash()} , Y:${generateRandomHash()}`;
        }, 50);
    }, 100);
}

// Function to stop the loading hash
function stopLoadingHash() {
    if (hashInterval) {
        clearInterval(hashInterval);
        hashInterval = null;
    }
    const loadingHash = document.getElementById("loading-hash");
    if (loadingHash) {
        loadingHash.textContent = "Hacking complete!";
    }
}

// Reusable function to create an animated progress bar
function createProgressBar(containerId, targetPercent, duration) {
    const progressBar = document.getElementById(containerId);
    if (!progressBar) {
        console.log('Progress bar container not found:', containerId);
        return;
    }

    // Clear any existing animation first
    if (progressAnimation) {
        clearInterval(progressAnimation);
    }

    const interval = 50;
    const steps = duration / interval;
    const startPercent = currentPercent;
    const increment = (targetPercent - startPercent) / steps;

    progressAnimation = setInterval(() => {
        if (currentPercent >= targetPercent) {
            clearInterval(progressAnimation);
            progressAnimation = null;
            
            if (currentPercent >= 100) {
                progressBar.innerHTML = "☠️☠️☠️☠️☠️☠️☠️☠️";
                progressBar.classList.add("skull-flash");
                stopLoadingHash();
                
                // Play audio safely
                try {
                    const audio = new Audio(chrome.runtime.getURL("progressbar/finish-him-off.mp3"));
                    audio.play().catch(e => console.log('Audio play failed:', e));
                } catch (error) {
                    console.log('Audio error:', error);
                }
            }
            return;
        }

        currentPercent += increment;
        if (currentPercent > targetPercent) {
            currentPercent = targetPercent;
        }

        progressBar.textContent = "";
        const filledBlocks = Math.floor((currentPercent / 100) * progressBarLength);
        
        for (let n = 0; n < progressBarLength; n++) {
            if (n < filledBlocks) {
                progressBar.textContent += "▓";
            } else {
                progressBar.textContent += "░";
            }
        }
        
        // Add percentage text
        progressBar.textContent += ` ${Math.round(currentPercent)}%`;
        
    }, interval);
}

// Function to reset progress (important!)
function resetProgress() {
    currentPercent = 0;
    if (progressAnimation) {
        clearInterval(progressAnimation);
        progressAnimation = null;
    }
    const progressBar = document.getElementById("ascii-progress-bar-1");
    if (progressBar) {
        progressBar.textContent = "";
        progressBar.classList.remove("skull-flash");
    }
}