{% extends "base.html" %}

{% block page_title %}Day Events{% endblock %}
{% block eyebrow %}Event Management{% endblock %}

{% block head %}
<style>
/* Header alignment */
.day-header-top {
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex-wrap: wrap;
    gap: 15px;
}
.day-header-top .add-day-btn {
    background: linear-gradient(135deg, #2c7da0 0%, #1a5f7a 100%);
    color: white;
    border: none;
    padding: 10px 20px;
    border-radius: 10px;
    font-weight: 600;
    font-size: 14px;
    cursor: pointer;
    transition: all 0.2s ease;
    box-shadow: 0 4px 12px rgba(44, 125, 160, 0.3);
}

.day-header-top .add-day-btn:hover {
    background: linear-gradient(135deg, #1a5f7a 0%, #0f3a47 100%);
    transform: translateY(-1px);
}

/* Day container */
.day-container {
    margin-top: 24px;
    display: flex;
    flex-direction: column;
    gap: 16px;
}

/* Day card */
.day-box {
    background: #ffffff;
    border-radius: 14px;
    border: 1px solid #e2e8f0;
    overflow: hidden;
    box-shadow: 0 2px 8px rgba(0,0,0,0.06);
}

.day-box-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 14px 18px;
    background: linear-gradient(135deg, #0f2b3d 0%, #1b5e7a 100%);
}

.day-box-header h3 {
    margin: 0;
    color: #ffffff !important;
    font-weight: 700;
    font-size: 16px;
}

.day-box-actions {
    display: flex;
    gap: 8px;
    align-items: center;
}

.btn-add-event {
    background: #ffffff;
    color: #0f2b3d !important;
    border: none;
    padding: 7px 14px;
    border-radius: 8px;
    cursor: pointer;
    font-weight: 700;
    font-size: 13px;
    transition: all 0.2s ease;
}

.btn-add-event:hover {
    background: #e0f2fe;
    color: #0f2b3d !important;
}

/* Event list */
.day-box-body {
    padding: 14px 18px;
}

.event-list {
    list-style: none;
    padding: 0;
    margin: 0;
    display: flex;
    flex-direction: column;
    gap: 8px;
}

.event-item {
    display: flex;
    align-items: center;
    justify-content: space-between;
    background: #f0f7ff;
    border: 1px solid #bfdbfe;
    border-left: 4px solid #2c7da0;
    padding: 10px 14px;
    border-radius: 8px;
    transition: all 0.2s ease;
}

.event-item:hover {
    background: #dbeafe;
}

.event-item-name {
    color: #1e3a5f !important;
    font-weight: 600;
    font-size: 14px;
    flex: 1;
}

.event-item-actions {
    display: flex;
    gap: 6px;
    flex-shrink: 0;
}

.btn-edit-event {
    background: #dbeafe;
    border: 1px solid #bfdbfe;
    color: #0f2b3d;
    cursor: pointer;
    font-size: 12px;
    font-weight: 700;
    padding: 4px 10px;
    border-radius: 6px;
    transition: all 0.2s;
}

.btn-edit-event:hover {
    background: #bfdbfe;
    border-color: #7dd3fc;
}

.btn-delete-event {
    background: #fee2e2;
    border: none;
    color: #ef4444;
    cursor: pointer;
    font-size: 13px;
    font-weight: 700;
    padding: 4px 8px;
    border-radius: 6px;
    transition: all 0.2s;
    flex-shrink: 0;
    line-height: 1;
}

.btn-delete-event:hover {
    background: #fca5a5;
    color: #991b1b;
}

.no-events-msg {
    color: #94a3b8 !important;
    font-size: 13px;
    font-style: italic;
    padding: 8px 0;
}

/* Empty state */
.empty-state-day {
    text-align: center;
    padding: 40px 20px;
    color: #94a3b8;
}

.empty-state-day p {
    font-size: 15px;
    margin-bottom: 16px;
}

/* ===== MODAL STYLES ===== */
.de-modal {
    display: none;
    position: fixed;
    inset: 0;
    background: rgba(15, 23, 42, 0.65);
    backdrop-filter: blur(6px);
    z-index: 1000;
    align-items: center;
    justify-content: center;
    padding: 16px;
}

.de-modal.active {
    display: flex;
}

.de-modal-content {
    background: #ffffff;
    border-radius: 16px;
    width: 100%;
    max-width: 400px;
    box-shadow: 0 25px 60px rgba(0,0,0,0.25);
    overflow: hidden;
    animation: deModalIn 0.2s ease;
}

@keyframes deModalIn {
    from { opacity: 0; transform: translateY(-16px) scale(0.97); }
    to   { opacity: 1; transform: translateY(0) scale(1); }
}

.de-modal-header {
    background: linear-gradient(135deg, #0f2b3d 0%, #1b5e7a 100%);
    padding: 16px 20px;
    display: flex;
    align-items: center;
    justify-content: space-between;
}

.de-modal-header h3 {
    margin: 0;
    color: #ffffff !important;
    font-size: 16px;
    font-weight: 700;
    display: flex;
    align-items: center;
    gap: 6px;
}

.de-modal-close {
    background: #ffffff;
    border: 1.5px solid #cbd5e1;
    color: #0f2b3d !important;
    width: 34px;
    height: 34px;
    border-radius: 8px;
    cursor: pointer;
    font-size: 20px;
    font-weight: 900;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: all 0.2s ease;
    padding: 0;
    line-height: 1;
}

.de-modal-close:hover {
    background: #0f2b3d;
    color: red !important;
    border-color: #0f2b3d;
}

.de-modal-body {
    padding: 22px 20px 24px;
}

.de-field {
    display: flex;
    flex-direction: column;
    gap: 6px;
    margin-bottom: 18px;
}

.de-field label {
    font-size: 12px;
    font-weight: 700;
    text-transform: uppercase;
    letter-spacing: 0.7px;
    color: #475569 !important;
}

.de-field input {
    padding: 11px 14px;
    border: 1.5px solid #e2e8f0;
    border-radius: 10px;
    font-size: 14px;
    color: #0f172a !important;
    background: #f8fafc;
    transition: all 0.2s;
    width: 100%;
    box-sizing: border-box;
}

.de-field input:focus {
    outline: none;
    border-color: #2c7da0;
    background: #ffffff;
    box-shadow: 0 0 0 3px rgba(44, 125, 160, 0.15);
}

.de-field input::placeholder {
    color: #b0bec5;
}

.de-modal-buttons {
    display: flex;
    gap: 10px;
}

.de-btn-primary {
    flex: 1;
    padding: 12px 20px;
    background: #2c7da0;
    color: green !important;
    border: none;
    border-radius: 10px;
    font-size: 14px;
    font-weight: 700;
    cursor: pointer;
    transition: all 0.2s ease;
    box-shadow: 0 2px 4px rgba(44, 125, 160, 0.2);
}

.de-btn-primary:hover {
    background: #1a5f7a;
    box-shadow: 0 4px 8px rgba(44, 125, 160, 0.3);
    transform: translateY(-1px);
}

.de-btn-cancel {
    flex: 1;
    padding: 12px 20px;
    background: #ffffff;
    color: #0f2b3d !important;
    border: 1.5px solid #cbd5e1;
    border-radius: 10px;
    font-size: 14px;
    font-weight: 600;
    cursor: pointer;
    transition: all 0.2s ease;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.de-btn-cancel:hover {
    background: #f1f5f9;
    border-color: #94a3b8;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

/* Confirm delete modal */
.de-confirm-text {
    color: #475569 !important;
    font-size: 14px;
    margin-bottom: 20px;
    line-height: 1.6;
}

.de-confirm-text strong {
    color: #0f172a !important;
}

.de-btn-danger {
    flex: 1;
    padding: 12px 20px;
    background: blue;
    color: red !important;
    border: none;
    border-radius: 10px;
    font-size: 14px;
    font-weight: 700;
    cursor: pointer;
    transition: all 0.2s ease;
    box-shadow: 0 2px 4px rgba(220, 38, 38, 0.2);
}

.de-btn-danger:hover {
    background: blue;
    box-shadow: 0 4px 8px rgba(220, 38, 38, 0.3);
    transform: translateY(-1px);
}

/* Responsive */
@media (max-width: 768px) {
    .day-header-top {
        flex-direction: column;
        align-items: flex-start;
    }
    .day-header-top .add-day-btn {
        width: 100%;
    }
    .day-box-header {
        flex-wrap: wrap;
        gap: 8px;
    }
}
</style>
{% endblock %}

{% block content %}
    <section class="panel-stack">
        <article class="glass-card panel-card">
            <div class="panel-header">
                <div class="day-header-top">
                    <div>
                        <p class="eyebrow">Schedule</p>
                        <h3>Manage Day Events</h3>
                    </div>
                    <button onclick="openAddDayModal()" type="button" class="add-day-btn">+ Add Day</button>
                </div>
            </div>

            <div class="panel-body">
                <div id="dayContainer" class="day-container">
                    <div class="empty-state-day">
                        <p>Loading events...</p>
                    </div>
                </div>
            </div>
        </article>
    </section>

    <!-- ADD DAY MODAL -->
    <div id="addDayModal" class="de-modal">
        <div class="de-modal-content">
            <div class="de-modal-header">
                <h3>📅 Add New Day</h3>
                <button class="de-modal-close" onclick="closeAddDayModal()">&times;</button>
            </div>
            <div class="de-modal-body">
                <div class="de-field">
                    <label>Day Name <span style="color:#e53e3e;">*</span></label>
                    <input type="text" id="dayNameInput" placeholder="e.g. Day 1, Day 2" autocomplete="off">
                </div>
                <p style="font-size: 12px; color: #94a3b8; margin-bottom: 16px;">💡 Tip: Add your first event to create the day in the schedule.</p>
                <div class="de-modal-buttons">
                    <button class="de-btn-cancel" onclick="closeAddDayModal()">Cancel</button>
                    <button class="de-btn-primary" onclick="submitAddDay()">Continue</button>
                </div>
            </div>
        </div>
    </div>

    <!-- ADD EVENT MODAL -->
    <div id="addEventModal" class="de-modal">
        <div class="de-modal-content">
            <div class="de-modal-header">
                <h3>➕ Add Event</h3>
                <button class="de-modal-close" onclick="closeAddEventModal()">&times;</button>
            </div>
            <div class="de-modal-body">
                <div class="de-field">
                    <label>Day</label>
                    <input type="text" id="eventDayDisplay" readonly style="background:#f1f5f9; cursor:not-allowed;">
                </div>
                <div class="de-field">
                    <label>Event Name <span style="color:#e53e3e;">*</span></label>
                    <input type="text" id="eventNameInput" placeholder="e.g. Opening Ceremony" autocomplete="off">
                </div>
                <div class="de-modal-buttons">
                    <button class="de-btn-cancel" onclick="closeAddEventModal()">Cancel</button>
                    <button class="de-btn-primary" onclick="submitAddEvent()">Add Event</button>
                </div>
            </div>
        </div>
    </div>

    <!-- EDIT EVENT MODAL -->
    <div id="editEventModal" class="de-modal">
        <div class="de-modal-content">
            <div class="de-modal-header">
                <h3>✏️ Edit Event</h3>
                <button class="de-modal-close" onclick="closeEditEventModal()">&times;</button>
            </div>
            <div class="de-modal-body">
                <div class="de-field">
                    <label>Event Name <span style="color:#e53e3e;">*</span></label>
                    <input type="text" id="editEventNameInput" placeholder="e.g. Opening Ceremony" autocomplete="off">
                </div>
                <div class="de-modal-buttons">
                    <button class="de-btn-cancel" onclick="closeEditEventModal()">Cancel</button>
                    <button class="de-btn-primary" onclick="submitEditEvent()">Save Changes</button>
                </div>
            </div>
        </div>
    </div>

    <!-- CONFIRM DELETE MODAL -->
    <div id="confirmDeleteModal" class="de-modal">
        <div class="de-modal-content">
            <div class="de-modal-header">
                <h3>🗑️ Confirm Delete</h3>
                <button class="de-modal-close" onclick="closeConfirmModal()">&times;</button>
            </div>
            <div class="de-modal-body">
                <p class="de-confirm-text" id="confirmDeleteText">Are you sure?</p>
                <div class="de-modal-buttons">
                    <button class="de-btn-cancel" onclick="closeConfirmModal()">Cancel</button>
                    <button class="de-btn-danger" onclick="executeDelete()">Delete</button>
                </div>
            </div>
        </div>
    </div>
{% endblock %}

{% block scripts %}
<script>
    let currentDay = '';
    let pendingDeleteType = '';
    let pendingDeleteId = null;
    let editingEventId = null;

    // ===== LOAD DAYS =====
    async function loadDays() {
        try {
            const res = await fetch('/admin/api/day-events/grouped');
            const data = await res.json();
            const container = document.getElementById('dayContainer');

            if (!data || Object.keys(data).length === 0) {
                container.innerHTML = `
                    <div class="empty-state-day">
                        <p>No days added yet.</p>
                        <button class="add-day-btn" onclick="openAddDayModal()">+ Add First Day</button>
                    </div>`;
                return;
            }

            let html = '';
            for (const day in data) {
                const events = data[day];
                let eventsHtml = '';

                if (events.length === 0) {
                    eventsHtml = `<p class="no-events-msg">No events yet — click "+ Add Event" to add one.</p>`;
                } else {
                    eventsHtml = `<ul class="event-list">`;
                    events.forEach(evt => {
                        const eventName = evt.event_name && evt.event_name.trim() ? evt.event_name : '(No name)';
                        eventsHtml += `
                            <li class="event-item">
                                <span class="event-item-name">📌 ${escapeHtml(eventName)}</span>
                                <div class="event-item-actions">
                                    <button class="btn-edit-event" onclick="openEditEventModal(${evt.id}, '${escapeAttr(eventName)}')">Edit</button>
                                    <button class="btn-delete-event" onclick="confirmDeleteEvent(${evt.id}, '${escapeAttr(eventName)}')">Delete</button>
                                </div>
                            </li>`;
                    });
                    eventsHtml += `</ul>`;
                }

                html += `
                    <div class="day-box">
                        <div class="day-box-header">
                            <h3>📅 ${escapeHtml(day)}</h3>
                            <div class="day-box-actions">
                                <button class="btn-add-event" onclick="openAddEventModal('${escapeAttr(day)}')">+ Add Event</button>
                            </div>
                        </div>
                        <div class="day-box-body">
                            ${eventsHtml}
                        </div>
                    </div>`;
            }

            container.innerHTML = html;
        } catch (error) {
            console.error('Error loading days:', error);
            document.getElementById('dayContainer').innerHTML = `
                <div class="empty-state-day">
                    <p style="color:#ef4444;">Failed to load events. Please refresh.</p>
                </div>`;
        }
    }

    // ===== ADD DAY MODAL =====
    function openAddDayModal() {
        document.getElementById('dayNameInput').value = '';
        document.getElementById('addDayModal').classList.add('active');
        setTimeout(() => document.getElementById('dayNameInput').focus(), 100);
    }

    function closeAddDayModal() {
        document.getElementById('addDayModal').classList.remove('active');
    }

    async function submitAddDay() {
        const day = document.getElementById('dayNameInput').value.trim();
        if (!day) {
            alert('Please enter a day name');
            document.getElementById('dayNameInput').focus();
            return;
        }

        try {
            const res = await fetch('/admin/api/add-day', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ day })
            });
            const data = await res.json();
            if (data.success) {
                closeAddDayModal();
                // Open add event modal directly
                openAddEventModal(day);
            } else {
                alert('Error: ' + (data.error || 'Failed to add day'));
            }
        } catch (err) {
            alert('Failed to add day. Please try again.');
        }
    }

    // ===== ADD EVENT MODAL =====
    function openAddEventModal(day) {
        currentDay = day;
        document.getElementById('eventDayDisplay').value = day;
        document.getElementById('eventNameInput').value = '';
        document.getElementById('addEventModal').classList.add('active');
        setTimeout(() => document.getElementById('eventNameInput').focus(), 100);
    }

    function closeAddEventModal() {
        document.getElementById('addEventModal').classList.remove('active');
    }

    async function submitAddEvent() {
        const event_name = document.getElementById('eventNameInput').value.trim();
        if (!event_name) {
            alert('Please enter an event name');
            document.getElementById('eventNameInput').focus();
            return;
        }

        try {
            const res = await fetch('/admin/api/add-event', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ day: currentDay, event_name })
            });
            const data = await res.json();
            if (data.success) {
                closeAddEventModal();
                await loadDays();
            } else {
                alert('Error: ' + (data.error || 'Failed to add event'));
            }
        } catch (err) {
            alert('Failed to add event. Please try again.');
        }
    }

    // ===== EDIT EVENT MODAL =====
    function openEditEventModal(eventId, eventName) {
        editingEventId = eventId;
        document.getElementById('editEventNameInput').value = eventName;
        document.getElementById('editEventModal').classList.add('active');
        setTimeout(() => document.getElementById('editEventNameInput').focus(), 100);
    }

    function closeEditEventModal() {
        document.getElementById('editEventModal').classList.remove('active');
        editingEventId = null;
    }

    async function submitEditEvent() {
        const event_name = document.getElementById('editEventNameInput').value.trim();
        if (!event_name) {
            alert('Please enter an event name');
            document.getElementById('editEventNameInput').focus();
            return;
        }

        try {
            const res = await fetch(`/admin/api/update-event/${editingEventId}`, {
                method: 'PUT',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ event_name })
            });
            const data = await res.json();
            if (data.success) {
                closeEditEventModal();
                await loadDays();
            } else {
                alert('Error: ' + (data.error || 'Failed to update event'));
            }
        } catch (err) {
            alert('Failed to update event. Please try again.');
        }
    }

    // ===== DELETE CONFIRM MODAL =====
    function confirmDeleteEvent(eventId, eventName) {
        pendingDeleteType = 'event';
        pendingDeleteId = eventId;
        document.getElementById('confirmDeleteText').innerHTML =
            `Are you sure you want to delete the event <strong>"${escapeHtml(eventName)}"</strong>? This cannot be undone.`;
        document.getElementById('confirmDeleteModal').classList.add('active');
    }

    function closeConfirmModal() {
        document.getElementById('confirmDeleteModal').classList.remove('active');
        pendingDeleteType = '';
        pendingDeleteId = null;
    }

    async function executeDelete() {
        if (pendingDeleteType === 'event' && pendingDeleteId) {
            try {
                const res = await fetch(`/admin/api/delete-event/${pendingDeleteId}`, {
                    method: 'DELETE'
                });
                const data = await res.json();
                if (data.success) {
                    closeConfirmModal();
                    await loadDays();
                } else {
                    alert('Error: ' + (data.error || 'Failed to delete event'));
                }
            } catch (err) {
                alert('Failed to delete event. Please try again.');
            }
        }
    }

    // ===== HELPERS =====
    function escapeHtml(str) {
        const div = document.createElement('div');
        div.textContent = str;
        return div.innerHTML;
    }

    function escapeAttr(str) {
        return str.replace(/'/g, "\\'").replace(/"/g, '&quot;');
    }

    // Close modals on backdrop click
    document.querySelectorAll('.de-modal').forEach(modal => {
        modal.addEventListener('click', function(e) {
            if (e.target === this) {
                this.classList.remove('active');
            }
        });
    });

    // Enter key support
    document.getElementById('dayNameInput').addEventListener('keypress', e => {
        if (e.key === 'Enter') submitAddDay();
    });
    document.getElementById('eventNameInput').addEventListener('keypress', e => {
        if (e.key === 'Enter') submitAddEvent();
    });
    document.getElementById('editEventNameInput').addEventListener('keypress', e => {
        if (e.key === 'Enter') submitEditEvent();
    });

    // Escape key
    document.addEventListener('keydown', e => {
        if (e.key === 'Escape') {
            document.querySelectorAll('.de-modal.active').forEach(m => m.classList.remove('active'));
        }
    });

    // Load on page load
    window.onload = loadDays;
</script>
{% endblock %}