document.addEventListener('DOMContentLoaded', function() {
    const languageToggle = document.getElementById('language-toggle');
    const langLabel = document.getElementById('lang-label');
    const pageHeading = document.getElementById('page-heading');
    const portugueseContent = document.getElementById('portuguese-content');
    const englishContent = document.getElementById('english-content');
    const navCommitment = document.getElementById('nav-commitment');
    const navDocuments = document.getElementById('nav-documents');
    const htmlElement = document.documentElement;
    
    let documentsData = [];

    // Load documents from JSON
    fetch('./documents.json')
        .then(response => response.json())
        .then(data => {
            documentsData = data.documents;
            renderDocuments('pt-PT');
            setLanguage(localStorage.getItem('preferred-language') || 'pt-PT');
        })
        .catch(error => console.error('Error loading documents:', error));

    languageToggle.addEventListener('click', function() {
        const currentLang = htmlElement.lang;
        const newLang = currentLang === 'pt-PT' ? 'en' : 'pt-PT';
        setLanguage(newLang);
    });

    function renderDocuments(lang) {
        const container = lang === 'pt-PT' 
            ? document.getElementById('documents-container')
            : document.getElementById('documents-container-en');
        
        const filtered = documentsData;
        
        // Group by category
        const grouped = {};
        filtered.forEach(doc => {
            if (!grouped[doc.category]) {
                grouped[doc.category] = [];
            }
            grouped[doc.category].push(doc);
        });

        container.innerHTML = '';

        Object.keys(grouped).forEach(category => {
            const categoryTitle = getCategoryTitle(category, lang);
            const categoryDiv = document.createElement('div');
            categoryDiv.className = 'document-category';
            
            const categoryHeading = document.createElement('h2');
            categoryHeading.textContent = categoryTitle;
            categoryDiv.appendChild(categoryHeading);

            grouped[category].forEach(doc => {
                const docCard = document.createElement('div');
                docCard.className = 'document-card';
                
                const cardHeader = document.createElement('div');
                cardHeader.className = 'card-header';
                
                const docTitle = document.createElement('h3');
                docTitle.textContent = doc.title;
                cardHeader.appendChild(docTitle);

                const langBadge = document.createElement('div');
                langBadge.className = 'language-badge';
                const langText = getLanguageName(doc.language);
                langBadge.innerHTML = `
                    <span class="material-icons">language</span>
                    <span>${langText}</span>
                `;
                cardHeader.appendChild(langBadge);
                
                docCard.appendChild(cardHeader);

                const docDesc = document.createElement('p');
                docDesc.textContent = doc.description;
                docCard.appendChild(docDesc);

                const downloadLink = document.createElement('a');
                downloadLink.href = doc.filename;
                downloadLink.className = 'btn btn-primary';
                downloadLink.download = '';
                downloadLink.innerHTML = `
                    <span class="material-icons">download</span>
                    ${lang === 'pt-PT' ? 'Download' : 'Download'}
                `;
                
                const linkWrapper = document.createElement('p');
                linkWrapper.style.marginTop = '16px';
                linkWrapper.appendChild(downloadLink);
                docCard.appendChild(linkWrapper);

                categoryDiv.appendChild(docCard);
            });

            container.appendChild(categoryDiv);
        });
    }

    function getLanguageName(langCode) {
        const names = {
            'pt-PT': 'Português',
            'en': 'English'
        };
        return names[langCode] || langCode;
    }

    function getCategoryTitle(category, lang) {
        const titles = {
            legal: {
                'pt-PT': 'Documentos Legais',
                'en': 'Legal Documents'
            },
            report: {
                'pt-PT': 'Relatórios',
                'en': 'Reports'
            },
            policy: {
                'pt-PT': 'Políticas',
                'en': 'Policies'
            }
        };
        return titles[category][lang] || category;
    }

    function setLanguage(lang) {
        if (lang === 'en') {
            htmlElement.lang = 'en';
            portugueseContent.classList.add('hidden');
            englishContent.classList.remove('hidden');
            pageHeading.lang = 'en';
            pageHeading.textContent = 'Accessibility Documents';
            langLabel.textContent = 'Português';
            if (navCommitment) navCommitment.textContent = 'Commitment';
            if (navDocuments) navDocuments.textContent = 'Documents';
            renderDocuments('en');
        } else {
            htmlElement.lang = 'pt-PT';
            englishContent.classList.add('hidden');
            portugueseContent.classList.remove('hidden');
            pageHeading.lang = 'pt-PT';
            pageHeading.textContent = 'Documentos de Acessibilidade';
            langLabel.textContent = 'English';
            if (navCommitment) navCommitment.textContent = 'Compromisso';
            if (navDocuments) navDocuments.textContent = 'Documentos';
            renderDocuments('pt-PT');
        }
        localStorage.setItem('preferred-language', lang);
    }
});
