<head>
    <link rel="stylesheet" href="/stylesheets/nav.css">

</head>

<nav class="navbar navbar-expand-lg p-3" style="background-color: #64375E;">
    <div class="container-lg">
        <a class="navbar-brand mb-0 h1 text-white" href="/" id="logo-hover">
            <img width="170px" style="filter: invert(1);" src="/images/logo-portal-do-artista.png">
        </a>
        <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
            <span class="navbar-toggler-icon"></span>
        </button>
        <div class="collapse navbar-collapse" id="navbarSupportedContent">
            <ul class="navbar-nav me-auto mb-2 mb-lg-0">
                <li class="nav-item"><a href="/" class="nav-link active text-white">Início</a></li>
                <li class="nav-item" id="showNotice"><a href="#" class="nav-link active text-white">Favoritos</a></li>
                <li class="nav-item"><a href="/edital" class="nav-link active text-white">Editais</a></li>
                <li class="nav-item"><a href="/edital/create" class="nav-link active text-white">Criar Edital</a></li>
            </ul>
            <ul class="navbar-nav ml-auto">
                <li class="nav-item"><a href="/auth/login" class="btn btn-secondary me-2 text-white"
                        role="button">Entrar</a></li>
                <li class="nav-item"><a href="/auth/registro" class="btn btn-secondary me-2" role="button">Cadastrar</a>
            </ul>
        </div>
    </div>
</nav>

<script>
    function updateNavbar() {
        fetch('/api/acc/get-session-name', {
            headers: {
                'Authorization': `Bearer ${localStorage.getItem('token')}`
            }
        })
            .then(res => {
                if (!res.ok) {
                    throw new Error('Err');
                }
                return res.json();
            })
            .then(json => {
                const userName = json.name;
                const userNavbar = `
            <li class="nav-item dropdown">
                <a class="nav-link dropdown-toggle text-white" href="#" id="navbarDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false">
                    ${userName}
                </a>
                <ul class="dropdown-menu" aria-labelledby="navbarDropdown">
                    <li><a class="dropdown-item" href="/profile">Perfil</a></li>
                    <li><a class="dropdown-item" href="/logout">Sair</a></li>
                </ul>
            </li>
        `;
                document.querySelector('.navbar-nav.ml-auto').innerHTML = userNavbar;
            })
            .catch(e => {
                console.error(e);
            });
    }

    // Chama a função para atualizar a navbar quando a página carrega
    document.addEventListener('DOMContentLoaded', updateNavbar);


    function editalCard(edital) {
        const now = new Date();
        const subscriptionDeadline = new Date(edital.subscriptionDeadline);
        const daysLeft = Math.ceil((subscriptionDeadline - now) / (1000 * 60 * 60 * 24));

        let alertClass = "";
        let alertMessage = "";

        if (daysLeft < 0) {
            alertClass = "alert-danger";
            alertMessage = "Este edital já expirou!";
        } else if (daysLeft <= 7) { // se faltar 7 dias para expirar ele mostra
            alertClass = "alert-warning";
            alertMessage = `Faltam ${daysLeft} dias para expirar.`;
        } else {
            alertClass = "alert-success";
        }

        return `
        <div class="card mb-3 edital-card">
            <div class="card-body d-flex justify-content-between align-items-center">
                <div>
                    <h5 class="card-title">${edital.title}</h5>
                    <p class="card-text">${edital.description}</p>
                    <div class="alert ${alertClass}" role="alert">
                        ${alertMessage}
                    </div>
                </div>
                <div>
                    <button class="btn btn-danger ms-2" onclick="removeEdital('${edital.id}')">
                        <i class="fas fa-trash"></i>
                    </button>
                </div>
            </div>
        </div>
    `;
    }

    async function removeEdital(editalId) { // falta fazer isso
        const res = await fetch(`/edital/remove/${editalId}`, {
            method: 'DELETE',
            headers: {
                'Authorization': `Bearer ${localStorage.getItem('token')}`
            }
        });

        if (res.ok) {
            Swal.fire('Sucesso!', 'Edital removido dos favoritos.', 'success');
            document.getElementById('showNotice').click();
        } else {
            Swal.fire('Erro!', 'Não foi possível remover o edital.', 'error');
        }
    }

    document.getElementById('showNotice').addEventListener('click', async () => {
        const res = await fetch('/edital/editais-favoritos', {
            headers: {
                'Authorization': `Bearer ${localStorage.getItem('token')}`
            }
        });

        const editais = await res.json();

        const editaisHTML = editais.map(editalCard).join('');

        Swal.fire({
            title: `Você favoritou <code>${editais.length}</code> editais.`,
            html: `<div style="max-height: 400px; overflow-y: auto;">${editaisHTML}</div>`,
            showCloseButton: true,
            focusConfirm: false,
            confirmButtonText: 'Fechar',
        });
    });


</script>