<!-- bedrock_server_manager//web/templates/configure_allowlist.html -->
{% extends "base.html" %}

{# --- Page Title Block --- #}
{% block title %}{{ super() }} - Configure Allowlist: {{ server_name }}{% endblock %}

{# --- Head Scripts Block --- #}
{% block head_scripts %}
<script src="{{ request.url_for('static', path='js/utils.js') }}" defer></script>
<script src="{{ request.url_for('static', path='js/allowlist.js') }}" defer></script>
{% endblock %}

{# --- Main Content Block --- #}
{% block content %}
<h2>Configure Allowlist</h2>
<p style="margin-bottom: 15px;" data-server-name="{{ server_name | e }}">
    Server: <strong>{{ server_name }}</strong>
    {% if new_install %}
    <br><span class="step-indicator">(Step 2 of 4 for New Installation)</span>
    {% endif %}
</p>

    {# --- Status Message Area --- #}
<div id="status-message-area" class="message-box" style="opacity: 0; transition: opacity 0.5s ease-out;"></div>

    {# --- Section for Adding New Players (Unchanged) --- #}
<section class="allowlist-add-section form-section">
    <h3>Add Players</h3>
    <p>Enter player names (Gamertags), one per line, to add them to the allowlist.</p>
    <div class="form-group">
        <label for="player-names-add" class="form-label">Player Names to Add:</label>
        <textarea id="player-names-add" name="player_names_add" class="form-input" rows="5" placeholder="PlayerOne\nAnotherPlayer\nGamertag123"></textarea>
    </div>
    <div class="form-group form-group-toggle-container">
        <div class="form-label-group">
            <span class="form-label">Ignore Player Limit:</span>
            <small class="form-help-text">Allow the player(s) being added to join even if the server is full?</small>
        </div>
        <div class="toggle-switch-container">
            <input type="checkbox" id="ignore-limit-add" name="ignore_limit_add-cb" class="toggle-input" value="true">
            <label for="ignore-limit-add" class="toggle-switch"></label>
        </div>
        <input type="hidden" name="ignore_limit_add" class="toggle-hidden-false" value="false">
    </div>
    <div class="form-actions">
        <button type="button" onclick="addAllowlistPlayers(this, '{{ server_name | e }}')" class="action-button start-button">
            Add These Players
        </button>
    </div>
</section>

    {# --- Section to Display Current Allowlist --- #}
<section class="current-allowlist-section list-section">
    <h2>Current Allowlist</h2>
    <ul id="current-allowlist-display" class="item-list">
    </ul>
    <template id="no-players-template">
        <li class="list-item-empty">No players currently in allowlist.</li>
    </template>
    <template id="player-item-template">
        <li class="list-item">
            <div class="item-details">
                <span class="item-name">PlayerName</span>
                <span class="item-tag ignores-limit-tag" style="display: none;">Ignores Player Limit</span>
            </div>
            <button type="button" class="action-button danger-button remove-button">Remove</button>
        </li>
    </template>
</section>

<div class="form-actions navigation-link">
    {% if new_install %}
    <a href="{{ request.url_for('configure_permissions_page', server_name=server_name) ~ ('?new_install=true' if new_install else '') if request else '#' }}" class="action-link">
        Skip & Go to Permissions »
    </a>
    <a href="{{ request.url_for('configure_properties_page', server_name=server_name) ~ ('?new_install=true' if new_install else '') if request else '#' }}" class="action-link">
        « Back to Server Properties
    </a>
    {% else %}
    <a href="{{ request.url_for('index') if request else '/' }}" class="action-link">
        « Back to Dashboard
    </a>
    {% endif %}
</div>
{% endblock %}

{% block body_scripts %}
<script>
    document.addEventListener('DOMContentLoaded', () => {
        const serverName = document.querySelector('[data-server-name]').dataset.serverName;
        const allowlistDisplay = document.getElementById('current-allowlist-display');
        const playerItemTemplate = document.getElementById('player-item-template');
        const noPlayersTemplate = document.getElementById('no-players-template');

        window.fetchAndUpdateAllowlistDisplay = async () => {
            console.log('Fetching and updating allowlist display...');
            allowlistDisplay.innerHTML = `<div class="loader-container-small"><div class="spinner"></div><p>Loading...</p></div>`;

            try {
                const data = await window.sendServerActionRequest(serverName, 'allowlist/get', 'GET', null, null);
                allowlistDisplay.innerHTML = '';

                if (data && data.status === 'success' && Array.isArray(data.players)) { // Changed existing_players to players
                    const players = data.players; // Changed existing_players to players
                    if (players.length > 0) {
                        players.forEach(player => {
                            const playerClone = playerItemTemplate.content.cloneNode(true);
                            const nameSpan = playerClone.querySelector('.item-name');
                            const tagSpan = playerClone.querySelector('.ignores-limit-tag');
                            const removeButton = playerClone.querySelector('.remove-button');

                            nameSpan.textContent = player.name;
                            if (String(player.ignoresPlayerLimit).toLowerCase() === 'true') {
                                tagSpan.style.display = 'inline-block';
                            }

                            if (window.removeAllowlistPlayer) {
                                removeButton.onclick = () => removeAllowlistPlayer(removeButton, serverName, player.name);
                            } else {
                                removeButton.style.display = 'none';
                            }
                            allowlistDisplay.appendChild(playerClone);
                        });
                    } else {
                        const noPlayersClone = noPlayersTemplate.content.cloneNode(true);
                        allowlistDisplay.appendChild(noPlayersClone);
                    }
                } else {
                    const errorMsg = (data && data.message) ? data.message : 'Failed to load allowlist data.';
                    console.error('Failed to load allowlist:', errorMsg);
                    if (typeof showStatusMessage === 'function' && !(data && data.status === 'error')) {
                        showStatusMessage(`Error loading allowlist: ${errorMsg}`, 'error');
                    }
                }
            } catch (error) {
                console.error('Client-side error in fetchAndUpdateAllowlistDisplay:', error);
                allowlistDisplay.innerHTML = '';
                if (typeof showStatusMessage === 'function') {
                    showStatusMessage(`Client-side error loading allowlist: ${error.message}`, 'error');
                }
            }
        };

        const toggleInput = document.getElementById('ignore-limit-add');
        if (toggleInput) {
            const hiddenFalseInput = document.querySelector('input[name="ignore_limit_add"]');
            const syncHiddenFalse = () => {
                if (hiddenFalseInput) hiddenFalseInput.disabled = toggleInput.checked;
            };
            toggleInput.addEventListener('change', syncHiddenFalse);
            syncHiddenFalse();
        }
        fetchAndUpdateAllowlistDisplay();
    });
</script>
{% endblock %}