{% extends "base.html" %}
{% block title %}Compte Outlook - {{ account.email }}{% endblock %}
{% block content %}
<div class="container-fluid">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <div>
            <h1 class="h3 mb-0">{{ account.email }}</h1>
            <small class="text-muted">Dernière connexion: {{ account.last_connected_at|datetime_fmt if account.last_connected_at else 'Jamais' }}</small>
        </div>
        <div>
            <button onclick="syncFolders()" class="btn btn-outline-primary btn-sm">
                <i class="bi bi-arrow-clockwise"></i> Synchroniser les dossiers
            </button>
        </div>
    </div>
    
    <div id="sync-status" class="alert alert-info d-none">
        <span class="spinner-border spinner-border-sm"></span> Synchronisation en cours...
    </div>
    
    <!-- Arbre des dossiers -->
    <div class="card">
        <div class="card-header">
            <i class="bi bi-folder"></i> Dossiers
        </div>
        <div class="card-body p-0">
            <div id="folders-container">
                <!-- Contenu généré par JavaScript -->
            </div>
        </div>
    </div>
</div>

<style>
.folder-tree {
    list-style: none;
    padding-left: 0;
}
.folder-tree ul {
    list-style: none;
    padding-left: 1.5rem;
}
.folder-item {
    padding: 0.5rem 1rem;
    border-bottom: 1px solid #eee;
    display: flex;
    align-items: center;
    justify-content: space-between;
}
.folder-item:hover {
    background-color: #f8f9fa;
}
.folder-name {
    display: flex;
    align-items: center;
    gap: 0.5rem;
}
.folder-toggle {
    cursor: pointer;
    width: 1.5rem;
    text-align: center;
}
.folder-icon {
    color: #ffc107;
}
.folder-count {
    font-size: 0.85rem;
    color: #6c757d;
}
.unread-badge {
    background-color: #dc3545;
    color: white;
    font-size: 0.75rem;
    padding: 0.2rem 0.5rem;
    border-radius: 0.25rem;
}
.children-container {
    display: none;
}
.children-container.show {
    display: block;
}
</style>

<script>
// Données des dossiers
const foldersTree = {{ folders_tree | tojson }};

// Rendu récursif de l'arbre
function renderFolderTree(folders, container) {
    folders.forEach(folder => {
        const li = document.createElement('li');
        li.className = 'folder-item';
        
        const hasChildren = folder.children && folder.children.length > 0;
        
        // Nom du dossier avec toggle
        const nameDiv = document.createElement('div');
        nameDiv.className = 'folder-name';
        
        // Toggle pour les enfants
        if (hasChildren) {
            const toggle = document.createElement('span');
            toggle.className = 'folder-toggle';
            toggle.innerHTML = '<i class="bi bi-chevron-right"></i>';
            toggle.onclick = (e) => {
                e.preventDefault();
                const childContainer = li.querySelector('.children-container');
                const icon = toggle.querySelector('i');
                if (childContainer.classList.contains('show')) {
                    childContainer.classList.remove('show');
                    icon.className = 'bi bi-chevron-right';
                } else {
                    childContainer.classList.add('show');
                    icon.className = 'bi bi-chevron-down';
                }
            };
            nameDiv.appendChild(toggle);
        } else {
            const spacer = document.createElement('span');
            spacer.className = 'folder-toggle';
            spacer.innerHTML = '&nbsp;';
            nameDiv.appendChild(spacer);
        }
        
        // Icône du dossier
        const icon = document.createElement('i');
        icon.className = 'bi bi-folder folder-icon';
        nameDiv.appendChild(icon);
        
        // Lien vers le dossier
        const link = document.createElement('a');
        link.href = `/outlook/{{ account.id }}/folder/${folder.id}`;
        link.textContent = folder.name;
        nameDiv.appendChild(link);
        
        // Badge non lus
        if (folder.unread_items > 0) {
            const badge = document.createElement('span');
            badge.className = 'unread-badge ms-2';
            badge.textContent = folder.unread_items;
            nameDiv.appendChild(badge);
        }
        
        li.appendChild(nameDiv);
        
        // Compteur d'emails
        const countDiv = document.createElement('div');
        countDiv.className = 'folder-count';
        countDiv.textContent = `${folder.total_items} emails`;
        li.appendChild(countDiv);
        
        // Conteneur pour les enfants
        if (hasChildren) {
            const childContainer = document.createElement('div');
            childContainer.className = 'children-container';
            
            const childList = document.createElement('ul');
            childList.className = 'folder-tree';
            renderFolderTree(folder.children, childList);
            childContainer.appendChild(childList);
            
            li.appendChild(childContainer);
        }
        
        container.appendChild(li);
    });
}

// Initialiser l'arbre
document.addEventListener('DOMContentLoaded', () => {
    const container = document.getElementById('folders-container');
    const rootList = document.createElement('ul');
    rootList.className = 'folder-tree';
    renderFolderTree(foldersTree, rootList);
    container.appendChild(rootList);
    
    // Ouvrir le premier niveau par défaut
    document.querySelectorAll('.children-container').forEach((el, i) => {
        if (i < 3) { // Ouvrir les 3 premiers
            el.classList.add('show');
            const toggle = el.parentElement.querySelector('.folder-toggle i');
            if (toggle) toggle.className = 'bi bi-chevron-down';
        }
    });
});

function syncFolders() {
    const statusDiv = document.getElementById('sync-status');
    statusDiv.classList.remove('d-none');
    
    fetch('/outlook/api/sync-folders/{{ account.id }}', {method: 'POST'})
        .then(response => response.json())
        .then(data => {
            statusDiv.classList.add('d-none');
            if (data.success) {
                location.reload();
            } else {
                alert('Erreur: ' + (data.error || 'Erreur inconnue'));
            }
        })
        .catch(error => {
            statusDiv.classList.add('d-none');
            alert('Erreur: ' + error.message);
        });
}
</script>
{% endblock %}
