const CREDENTIAL_MASK = '••••••••••••';

function toggleCredential(button) {
    const row = button.closest('tr');
    const codeEl = row.querySelector('.credential-value');
    const icon = button.querySelector('i');

    if (!codeEl) return;

    const isHidden = codeEl.textContent === CREDENTIAL_MASK;

    if (isHidden) {
        codeEl.textContent = codeEl.getAttribute('data-value');
        icon.classList.remove('bi-eye');
        icon.classList.add('bi-eye-slash');
    } else {
        codeEl.textContent = CREDENTIAL_MASK;
        icon.classList.remove('bi-eye-slash');
        icon.classList.add('bi-eye');
    }

    updateShowAllButton();
}

function toggleAllCredentials() {
    const credentials = document.querySelectorAll('.credential-value');
    const anyHidden = Array.from(credentials).some(el => el.textContent === CREDENTIAL_MASK);

    credentials.forEach(function (codeEl) {
        const row = codeEl.closest('tr');
        const button = row.querySelector('.credential-toggle');
        const icon = button ? button.querySelector('i') : null;

        if (anyHidden) {
            codeEl.textContent = codeEl.getAttribute('data-value');
            if (icon) {
                icon.classList.remove('bi-eye');
                icon.classList.add('bi-eye-slash');
            }
        } else {
            codeEl.textContent = CREDENTIAL_MASK;
            if (icon) {
                icon.classList.remove('bi-eye-slash');
                icon.classList.add('bi-eye');
            }
        }
    });

    updateShowAllButton();
}

function updateShowAllButton() {
    const credentials = document.querySelectorAll('.credential-value');
    const anyHidden = Array.from(credentials).some(el => el.textContent === CREDENTIAL_MASK);
    const toggleBtn = document.getElementById('toggle-credentials-btn');
    const toggleText = document.getElementById('toggle-credentials-text');
    const toggleIcon = toggleBtn ? toggleBtn.querySelector('i') : null;

    if (toggleText && toggleBtn) {
        const showText = toggleBtn.getAttribute('data-show-text') || 'Show All';
        const hideText = toggleBtn.getAttribute('data-hide-text') || 'Hide All';
        toggleText.textContent = anyHidden ? showText : hideText;
    }
    if (toggleIcon) {
        toggleIcon.classList.toggle('bi-eye', anyHidden);
        toggleIcon.classList.toggle('bi-eye-slash', !anyHidden);
    }
}
