const characters1 = "q  w  e  r  t  y  u   i o  p  l   k   j  h  g  f  d  s  a z x c v b n m. . ..";
const characters2 = "ef123456789";
const maxCharacterLength = 10000;
let lastClickedButton = null;
let lastButtonName = null;
const passwords = {}; // Store passwords for red buttons

function generateText() {
    let text1 = '';
    let text2 = '';
    for (let i = 0; i < maxCharacterLength; i++) {
        text1 += characters1.charAt(Math.floor(Math.random() * characters1.length));
        text2 += characters2.charAt(Math.floor(Math.random() * characters2.length));
    }
    document.getElementById('raw-characters').textContent = text1;
    document.getElementById('byte-characters').textContent = text2;
    const buttonName = this.textContent;
    document.getElementById('raw-data').textContent = buttonName;
    document.getElementById('Bytes-Data').textContent = buttonName;
}

function getPasswords(buttonName) {
    if (buttonName === lastButtonName && passwords[buttonName]) {
        displayPasswords(buttonName);
    } else {
        
        fetch('/password_view')
            .then(response => response.json())
            .then(data => {
                passwords[buttonName] = {
                    original_password: data.original_password,
                    encrypted_password: data.encrypted_password
                };
                displayPasswords(buttonName);
            })
            .catch(error => console.error('Error fetching passwords:', error));
    }
}

function displayPasswords(buttonName) {
    const passwordData = passwords[buttonName];
    document.getElementById('original-password').textContent = passwordData.original_password;
    document.getElementById('encrypted-password').textContent = passwordData.encrypted_password;
}

const buttons = document.querySelectorAll('.grid-item');
buttons.forEach(button => {
    button.addEventListener('click', function() {
        generateText.call(this); // Always generate random text first
        const buttonName = this.textContent;
        if (buttonName === lastButtonName) {
            return; // Same button clicked, do nothing
        }
        if (this.parentNode.classList.contains('red')) {
            getPasswords(buttonName);
            lastClickedButton = this;
            lastButtonName = buttonName;
        } else {
            lastClickedButton = null;
            lastButtonName = null;
        }
    });
});

