<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Hall of Fame</title>
    <%- include('../partials/_favicon') %>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="/styles/main.css">
</head>

<body class="d-flex flex-column min-vh-100">

    <main class="flex-shrink-0">
        <%- include('../partials/_navbar') %>

        <div class="container mt-5">
            <div class="d-flex justify-content-between align-items-center mb-3">
                <h1>Hall of Fame</h1>
                <% if (user && user.isAdmin) { %>
                <a href="/hall-of-fame/new" class="btn btn-primary">Nieuwe Inzending Toevoegen</a>
                <% } %>
            </div>

            <% if (errorMessage) { %>
            <div class="alert alert-<%= alertType %>  alert-dismissible fade show" role="alert">
                <%= errorMessage %>
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            </div>
            <% } %>

            <ul id="hallOfFameList" class="list-group">
                <% hallOfFame.forEach(entry => { %>
                <li class="list-group-item d-flex justify-content-between align-items-center" data-id="<%= entry.id %>">
                    <span>
                        <strong><%= entry.prestatie %></strong> - <%= entry.activiteit %>
                        <br>
                        User: <a href="/profile/<%= entry.User.id %>"><%= entry.User.name %></a>
                    </span>
                    <% if (user && user.isAdmin) { %>
                    <span class="drag-handle">â˜°</span>
                    <% } %>
                </li>
                <% }) %>
            </ul>
        </div>
    </main>

    <%- include('../partials/_footer') %>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.bundle.min.js"></script>

    <% if (user && user.isAdmin) { %>
    <script src="https://cdn.jsdelivr.net/npm/sortablejs@1.14.0/Sortable.min.js"></script>
    <script>
        document.addEventListener('DOMContentLoaded', function () {
            const list = document.getElementById('hallOfFameList');
            const sortable = new Sortable(list, {
                handle: '.drag-handle',
                animation: 150,
                onEnd: async function (/**Event*/evt) {
                    const items = [...list.children].map((item, index) => ({
                        id: item.getAttribute('data-id'),
                        order: index + 1
                    }));

                    try {
                        const response = await fetch('/hall-of-fame/reorder', {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json',
                                'X-CSRF-Token': '<%= csrfToken %>'
                            },
                            body: JSON.stringify({ items })
                        });
                        const result = await response.json();
                        if (response.ok) {
                            showAlert('Order updated successfully', 'success');
                        } else {
                            throw new Error(result.message || 'Failed to reorder');
                        }
                    } catch (error) {
                        console.error('Error reordering items:', error);
                        showAlert('Failed to save the new order. Please try again.', 'danger');
                    }
                }
            });

            function showAlert(message, type) {
                const alertContainer = document.createElement('div');
                alertContainer.className = `alert alert-${type} alert-dismissible fade show`;
                alertContainer.role = 'alert';
                alertContainer.innerHTML = `
                    ${message}
                    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                `;
                document.querySelector('.container').prepend(alertContainer);
            }
        });
    </script>
    <% } %>
</body>

</html>