<section class="analytics-dashboard">
    <?php if ($this->session->flashdata('toast_success')): ?>
        <script>
            document.addEventListener("DOMContentLoaded", function() {
                toast.success("<?= $this->session->flashdata('toast_success'); ?>");
            });
        </script>
    <?php endif; ?>

    <div class="title-wrapper">
        <h1 class="title">Add New Event</h1>
    </div>

    <div class="user-page mx-2">
        <!-- EVENT MODAL -->
        <div class="ringside events-modal" id="eventModal">

            <form method="post" action="<?php echo base_url('admin/save-event'); ?>" enctype="multipart/form-data">
                <!-- Event Info -->
                <div class="form-wrapper">
                    <div class="row g-3">
                        <div class="col-12 col-md-6">
                            <div class="form-group">
                                <label for="eventName">Event Name</label>
                                <input type="text" name="event_name" id="eventName" class="form-control"
                                    placeholder="Event Name" />
                            </div>
                        </div>
                        <div class="col-12 col-md-6">
                            <div class="form-group">
                                <label for="eventLocation"><i class="fas fa-map-marker-alt"></i> Event Location</label>
                                <input type="text" name="event_location" id="eventLocation" class="form-control" placeholder="Event Location" required />
                            </div>
                        </div>

                        <div class="col-12 col-md-6">
                            <div class="form-group">
                                <label for="startDate">Start Date</label>
                                <input type="date" name="start_date" id="startDate" class="form-control"
                                    required />
                            </div>
                        </div>

                        <div class="col-12 col-md-6">
                            <div class="form-group">
                                <label for="endDate">End Date</label>
                                <input type="date" name="end_date" id="endDate" class="form-control"
                                    required />
                            </div>
                        </div>

                    </div>

                    <div class="tiles-section">
                        <label>Main Tiles</label>
                        <div class="tiles-wrapper" id="mainTilesWrapper">
                            <!-- Tiles will be loaded dynamically -->
                            <div class="text-center w-100 py-3">
                                <div class="spinner-border text-primary" role="status">
                                    <span class="visually-hidden">Loading...</span>
                                </div>
                                <p class="mt-2 text-muted">Loading tiles...</p>
                            </div>



                        </div>

                        <label>Other Tiles</label>
                        <div class="tiles-wrapper" id="otherTilesWrapper">
                            <!-- Tiles will be loaded dynamically -->
                            <div class="text-center w-100 py-3">
                                <div class="spinner-border text-primary" role="status">
                                    <span class="visually-hidden">Loading...</span>
                                </div>
                                <p class="mt-2 text-muted">Loading tiles...</p>
                            </div>
                        </div>
                    </div>
                    <div class="modal fade" id="customTileModal" tabindex="-1">
                        <div class="modal-dialog modal-sm modal-dialog-centered">
                            <div class="modal-content">
                                <div class="modal-header">
                                    <h5 class="modal-title">Create Custom Tile</h5>
                                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                                </div>
                                <div class="modal-body">
                                    <input type="text" id="customTileName" class="form-control"
                                        placeholder="Tile name">
                                </div>
                                <div class="modal-footer">
                                    <button class="btn btn-primary" data-bs-dismiss="modal" style="background: burlywood !important; color: white !important;">Cancel</button>
                                    <button class=" btn btn-primary" id="saveCustomTileBtn">Create</button>
                                </div>
                            </div>
                        </div>
                    </div>


                    <!-- Dynamic sections will be injected here -->
                    <div id="dynamic-sections-container"></div>

                    <!-- Enable Admin Messages Checkbox -->
                    <div class="checkbox-area custom-checkbox">
                        <input class="checkbox-input" type="checkbox" id="enableAdminMessages"
                            name="enable_admin_messages" value="1" />
                        <label class="checkbox-text m-0" for="enableAdminMessages">Enable Admin Messages</label>
                    </div>

                    <!-- Buttons -->
                    <div class="modal-buttons">
                        <a href="<?php echo base_url('admin/dashboard/contentManagement'); ?>"
                            class="btn-cancel close-modal">Cancel</a>
                        <button type="submit" class="btn btn-upload" id="saveEvent">Upload Event</button>
                    </div>

                </div>
            </form>
        </div>
    </div>
</section>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>


<script>
    // Track which sections have been initialized
    const initializedSections = new Set();

    // Track subsection counter for each tile
    const subsectionCounters = {};

    // Build dynamic tile configuration from API
    let tileConfigs = {};
    let tilesData = []; // Store complete tile data

    // Fetch tiles from API
    async function fetchTiles() {
        try {
            const response = await fetch('<?php echo base_url('admin/api/tiles'); ?>');
            const data = await response.json();

            if (data.success && data.tiles) {
                tilesData = data.tiles;

                // Build tile configs
                data.tiles.forEach(tile => {
                    tileConfigs[tile.slug] = {
                        id: tile.tile_id,
                        title: tile.tile_name,
                        type: tile.type,
                        url: tile.tile_url
                    };
                });

                console.log('Tile Configs:', tileConfigs);

                // Render tiles after fetching
                renderTiles(data.tiles);
            } else {
                throw new Error('Invalid response format');
            }
        } catch (error) {
            console.error('Error fetching tiles:', error);

            // Show error in tile wrappers
            document.getElementById('mainTilesWrapper').innerHTML = `
                <div class="alert alert-danger w-100" role="alert">
                    <strong>Error:</strong> Failed to load tiles. Please refresh the page.
                </div>
            `;
            document.getElementById('otherTilesWrapper').innerHTML = `
                <div class="alert alert-danger w-100" role="alert">
                    <strong>Error:</strong> Failed to load tiles. Please refresh the page.
                </div>
            `;

            Swal.fire({
                icon: 'error',
                title: 'Error',
                text: 'Failed to load tiles. Please refresh the page.'
            });
        }
    }

    // Render tiles dynamically
    function renderTiles(tiles) {
        const mainTiles = tiles
            .filter(tile => tile.type === 'main')
            .sort((a, b) => {
                // Force "result" tile to the first position
                if (a.slug === 'results') return -1;
                if (b.slug === 'results') return 1;
                return 0;
            });
        const otherTiles = tiles.filter(tile => tile.type === 'other');

        // Render main tiles
        const mainTilesWrapper = document.getElementById('mainTilesWrapper');
        if (mainTilesWrapper) {
            if (mainTiles.length > 0) {
                mainTilesWrapper.innerHTML = mainTiles.map(tile => createTileHTML(tile)).join('');
            } else {
                mainTilesWrapper.innerHTML = '<p class="text-muted">No main tiles available</p>';
            }
        }

        // Render other tiles
        const otherTilesWrapper = document.getElementById('otherTilesWrapper');
        if (otherTilesWrapper) {
            if (otherTiles.length > 0) {
                otherTilesWrapper.innerHTML = otherTiles.map(tile => createTileHTML(tile)).join('');
            } else {
                otherTilesWrapper.innerHTML = '';
            }
        }

        // Setup tile handlers after rendering
        setupTileHandlers();
        appendAddTileButton();

    }
    let customTileModal;

    document.addEventListener("DOMContentLoaded", () => {
        const modalEl = document.getElementById('customTileModal');
        if (modalEl) {
            customTileModal = new bootstrap.Modal(modalEl);
        }
    });

    function generateSlug(text) {
        return text
            .toLowerCase()
            .trim()
            .replace(/[\s\W-]+/g, '-')
            .replace(/^-+|-+$/g, '');
    }

    function appendAddTileButton() {
        const wrapper = document.getElementById('mainTilesWrapper');

        wrapper.insertAdjacentHTML('beforeend', `
                    <div class="tile-container">
                        <div class="tile-item add-tile-btn" id="addCustomTileBtn" style="font-size: 32px; display:flex; justify-content:center; align-items:center; width:60px; height:60px; border:2px dashed #aaa; border-radius:10px; cursor:pointer;">
                            +
                        </div>
                        <span class="tile-name">Add Tile</span>
                    </div>
                `);


        document.getElementById('addCustomTileBtn').addEventListener('click', () => {
            const modalEl = document.getElementById('customTileModal');

            if (!modalEl) {
                console.error('customTileModal element not found');
                return;
            }

            // Lazy init (runs once)
            if (!customTileModal) {
                if (!window.bootstrap || !bootstrap.Modal) {
                    console.error('Bootstrap Modal not available');
                    return;
                }
                customTileModal = new bootstrap.Modal(modalEl);
            }

            document.getElementById('customTileName').value = '';
            customTileModal.show();
        });
    }
    // Save Custom Tile
    document.getElementById('saveCustomTileBtn').addEventListener('click', (e) => {
        e.preventDefault();

        const tileNameInput = document.getElementById('customTileName');
        const tileName = tileNameInput.value.trim();
        if (!tileName) {
            alert('Please enter a tile name');
            return;
        }

        const slug = generateSlug(tileName); // ← clean slug
        document.activeElement.blur();

        // Add tile dynamically to OTHER tiles wrapper
        const wrapper = document.getElementById('otherTilesWrapper');
        wrapper.insertAdjacentHTML('beforeend', `
                <div class="tile-container">
                    <label class="tile-item" data-tile="${slug}">
                        <input type="hidden" name="tiles_custom[${slug}]" value="${tileName}">
                        <input type="checkbox" class="tile-check">

                        <img 
                            src="<?php echo base_url('public/admin_assets/images/RingsideLogo-1.png'); ?>"
                            data-active="<?php echo base_url('public/admin_assets/images/RingsideLogo-1.png'); ?>"
                            data-default="<?php echo base_url('public/admin_assets/images/RingsideLogo-1.png'); ?>"
                            alt="${tileName}"
                        >
                    </label>
                    <span class="tile-name">${tileName}</span>
                </div>
            `);



        // Add the section for this tile dynamically
        const container = document.getElementById('dynamic-sections-container');
        subsectionCounters[slug] = 0;
        const sectionHTML = FormComponents.generateTileForm(slug, tileName);
        container.insertAdjacentHTML('beforeend', sectionHTML);

        setupTileHandlers();

        tileNameInput.value = '';
        customTileModal.hide();
    });
    // On form submit, override tiles serialization
    function serializeSelectedTiles() {
        const selectedTiles = document.querySelectorAll('.tile-item .tile-check:checked');
        const tilesData = {};

        selectedTiles.forEach(input => {
            const container = input.closest('.tile-item');
            const slug = container.getAttribute('data-tile');
            const sectionId = slug;
            const section = document.getElementById(sectionId);

            tilesData[slug] = {
                subsections: {}
            };

            if (section) {
                const subsections = section.querySelectorAll('.subsection');
                subsections.forEach(sub => {
                    const subIndex = sub.getAttribute('data-subsection-id');
                    const nameInput = sub.querySelector('input[type="text"]');
                    tilesData[slug].subsections[subIndex] = {
                        name: nameInput.value.trim()
                    };
                });
            }
        });

        return tilesData;
    }
    // Create tile HTML
    function createTileHTML(tile) {
        const tileValue = JSON.stringify({
            slug: tile.slug,
            name: tile.tile_name
        }).replace(/"/g, '&quot;');

        return `
            <div class="tile-container">
                <label class="tile-item" data-tile="${tile.slug}">
                    <!-- Hidden input to always send tile info -->
                    <input type="hidden" name="tiles[${tile.tile_id}]"
                        value='${tileValue}'>

                    <!-- Checkbox for visual selection -->
                    <input type="checkbox" name="selected_tiles[${tile.tile_id}]"
                        value='${tileValue}'
                        class="tile-check">
                    <img src="${tile.tile_url}" 
                         data-active="${tile.tile_url}"
                         data-default="${tile.tile_url}" 
                         alt="${tile.tile_name}">
                </label>
                <span class="tile-name">${tile.tile_name}</span>
            </div>
        `;
    }

    // Component generator functions
    const FormComponents = {
        // Generate form section with Add Subsection button
        generateTileForm: function(sectionId, title) {
            const fieldName = sectionId.replace(/-/g, '_');
            return `
                <div class="section mb-1 tile-section" id="${sectionId}" style="display:none;">
                    <div class="d-flex justify-content-between align-items-center mb-1">
                        <h3 class="mb-0">${title}</h3>
                        <button type="button" class="btn btn-primary btn-add-subsection" data-section="${sectionId}">
                            <i class="fas fa-plus"></i> Add Section
                        </button>
                    </div>
                    
                    <!-- Container where dynamic sub-sections will appear -->
                    <div class="subsections-container" data-section="${sectionId}"></div>
                </div>
            `;
        }
    };

    // Initialize all sections on page load
    function initializeSections() {
        const startInput = document.getElementById('startDate');
        const endInput = document.getElementById('endDate');

        const now = new Date();
        const year = now.getFullYear();
        const month = String(now.getMonth() + 1).padStart(2, '0');
        const day = String(now.getDate()).padStart(2, '0');
        const hours = String(now.getHours()).padStart(2, '0');
        const minutes = String(now.getMinutes()).padStart(2, '0');
        const minDateTime = `${year}-${month}-${day}T${hours}:${minutes}`;

        startInput.setAttribute('min', minDateTime);
        endInput.setAttribute('min', minDateTime);

        startInput.addEventListener('change', function() {
            endInput.setAttribute('min', this.value);
        });

        const container = document.getElementById('dynamic-sections-container');

        if (!container) {
            console.error('Container #dynamic-sections-container not found!');
            return;
        }

        // Generate form for each tile
        Object.keys(tileConfigs).forEach(sectionId => {
            const config = tileConfigs[sectionId];
            subsectionCounters[sectionId] = 0; // Initialize counter
            const html = FormComponents.generateTileForm(sectionId, config.title);
            container.insertAdjacentHTML('beforeend', html);
        });

    }

    // Setup Add Subsection button handlers
    document.addEventListener('click', function(e) {
        const btn = e.target.closest('.btn-add-subsection');
        if (!btn) return;

        const sectionId = btn.getAttribute('data-section');
        const section = document.getElementById(sectionId);
        if (!section) return;

        addSubsection(section, sectionId);
    });


    // Add a single subsection
    function addSubsection(section, sectionId) {
        const container = section.querySelector('.subsections-container');
        const fieldName = sectionId.replace(/-/g, '_');

        // Increment counter
        subsectionCounters[sectionId] = (subsectionCounters[sectionId] || 0) + 1;
        const subsectionIndex = subsectionCounters[sectionId];

        const subsectionHTML = `
            <div class="subsection mb-2 p-2 " data-subsection-id="${subsectionIndex}">
                <div class="d-flex justify-content-between align-items-center mb-2">
                    <h5 class="mb-0">Section </h5>
                    <button type="button" class="btn btn-danger btn-sm btn-delete-subsection">
                        <i class="fas fa-trash"></i> Delete
                    </button>
                </div>
                <div class="row g-2">
                    <div class="col-12 col-md-6">
                        <div class="form-group">
                            <label for="${fieldName}_subname_${subsectionIndex}">Name</label>
                            <input type="text" name="${fieldName}[subsections][${subsectionIndex}][name]" 
                                   id="${fieldName}_subname_${subsectionIndex}" 
                                   class="form-control" 
                                   placeholder="Name" 
                                   required />
                        </div>
                    </div>
                    <div class="col-12 col-md-6">
                        <div class="form-group">
                            <label for="${fieldName}_subpdf_${subsectionIndex}">
                                Upload PDF <small>(you can choose multiple files)</small>
                            </label>
                            <button type="button" class="btn btn-warning w-100 btn-upload-pdf-sub" data-subsection="${subsectionIndex}">
                                Choose PDF Files
                            </button>
                            <input type="file" name="${fieldName}[subsections][${subsectionIndex}][pdf][]" 
                                   id="${fieldName}_subpdf_${subsectionIndex}" 
                                   class="d-none pdf-input-sub" 
                                   accept=".pdf" 
                                   multiple>
                            <div class="pdf-list mt-2" id="${fieldName}_pdflist_${subsectionIndex}"></div>
                        </div>
                    </div>
                </div>
            </div>
        `;

        container.insertAdjacentHTML('beforeend', subsectionHTML);

        // Setup PDF upload handler for this subsection
        setupSubsectionPdfHandlers(section);

        // Setup delete button handler
        setupDeleteSubsectionHandlers(section);
    }

    // Setup delete button handlers
    function setupDeleteSubsectionHandlers(section) {
        const deleteButtons = section.querySelectorAll('.btn-delete-subsection');

        deleteButtons.forEach(btn => {
            // Remove old listeners by cloning
            const newBtn = btn.cloneNode(true);
            btn.parentNode.replaceChild(newBtn, btn);

            newBtn.addEventListener('click', function() {
                const subsection = this.closest('.subsection');

                Swal.fire({
                    title: 'Delete Section?',
                    text: 'Are you sure you want to delete this section?',
                    icon: 'warning',
                    showCancelButton: true,
                    confirmButtonColor: '#d33',
                    cancelButtonColor: '#3085d6',
                    confirmButtonText: 'Yes, delete it!'
                }).then((result) => {
                    if (result.isConfirmed) {
                        subsection.remove();
                        Swal.fire({
                            title: 'Deleted!',
                            text: 'Section has been deleted.',
                            icon: 'success',
                            timer: 1500,
                            showConfirmButton: false
                        });
                    }
                });
            });
        });
    }

    // Setup PDF upload handlers for subsections
    // Global object to store File objects for each subsection
    const subsectionFiles = {};

    function setupSubsectionPdfHandlers(section) {
        const pdfButtons = section.querySelectorAll('.btn-upload-pdf-sub');

        pdfButtons.forEach(btn => {
            const newBtn = btn.cloneNode(true);
            btn.parentNode.replaceChild(newBtn, btn);

            newBtn.addEventListener('click', function(e) {
                e.preventDefault();
                const fileInput = this.nextElementSibling;
                fileInput.click();
            });
        });

        const pdfInputs = section.querySelectorAll('.pdf-input-sub');

        pdfInputs.forEach(input => {
            const newInput = input.cloneNode(true);
            input.parentNode.replaceChild(newInput, input);

            newInput.addEventListener('change', function() {
                const subsection = this.closest('.subsection');
                const subsectionIndex = subsection.getAttribute('data-subsection-id');
                const sectionId = subsection.closest('.tile-section').id;
                const storageKey = `${sectionId}_${subsectionIndex}`;

                // Initialize storage for this specific subsection if it doesn't exist
                if (!subsectionFiles[storageKey]) {
                    subsectionFiles[storageKey] = [];
                }

                // Add new files to our global array (preventing duplicates by name/size if desired)
                Array.from(this.files).forEach(file => {
                    const isDuplicate = subsectionFiles[storageKey].some(f => f.name === file.name && f.size === file.size);
                    if (!isDuplicate) {
                        subsectionFiles[storageKey].push(file);
                    }
                });

                renderPdfList(storageKey, subsection);
                updateNativeInput(newInput, storageKey);
            });
        });
    }

    // Function to render the UI list with delete buttons
    function renderPdfList(storageKey, subsection) {
        const sectionId = subsection.closest('.tile-section').id;
        const fieldName = sectionId.replace(/-/g, '_');
        const subsectionIndex = subsection.getAttribute('data-subsection-id');
        const pdfList = document.getElementById(`${fieldName}_pdflist_${subsectionIndex}`);
        const btn = subsection.querySelector('.btn-upload-pdf-sub');

        pdfList.innerHTML = '';
        const files = subsectionFiles[storageKey];

        if (files.length > 0) {
            btn.textContent = `✓ ${files.length} PDF(s) Selected`;
            btn.classList.replace('btn-warning', 'btn-success');

            files.forEach((file, index) => {
                const fileItem = document.createElement('div');
                fileItem.className = 'alert alert-success py-1 px-2 mb-1 d-flex align-items-center justify-content-between';
                fileItem.style.fontSize = '0.85rem';
                fileItem.innerHTML = `
                    <div class="d-flex align-items-center" style="min-width: 0;">
                        <span class="me-2">📄</span>
                        <span class="text-truncate" style="max-width: 180px; display: inline-block;">${file.name}</span>
                    </div>
                    <button type="button" 
                            class="btn btn-sm btn-danger py-0 px-2" 
                            style="line-height: 1.2; font-weight: bold; font-size: 16px; border-radius: 4px;"
                            onclick="removeFile('${storageKey}', ${index}, this)">
                        &times;
                    </button>
                `;
                pdfList.appendChild(fileItem);
            });
        } else {
            btn.textContent = 'Choose PDF Files';
            btn.classList.replace('btn-success', 'btn-warning');
        }
    }

    // Function to remove a file from the list
    window.removeFile = function(storageKey, index, element) {
        subsectionFiles[storageKey].splice(index, 1);

        const subsection = element.closest('.subsection');
        const input = subsection.querySelector('.pdf-input-sub');

        renderPdfList(storageKey, subsection);
        updateNativeInput(input, storageKey);
    };

    // Crucial: Update the hidden file input so the Form submit actually sees the files
    function updateNativeInput(input, storageKey) {
        const dataTransfer = new DataTransfer();
        subsectionFiles[storageKey].forEach(file => {
            dataTransfer.items.add(file);
        });
        input.files = dataTransfer.files;
    }

    // Toggle tile visibility
    function toggleTileVisibility(currentTile) {
        const checkbox = currentTile.querySelector(".tile-check");
        const img = currentTile.querySelector("img");
        const sectionId = currentTile.getAttribute('data-tile');
        const section = document.getElementById(sectionId);

        const activeSrc = img.dataset.active || img.src;
        const defaultSrc = img.dataset.default || img.src;

        if (checkbox.checked) {
            currentTile.classList.add("selected");
            img.src = activeSrc;
            if (section) section.style.display = "block";
        } else {
            currentTile.classList.remove("selected");
            img.src = defaultSrc;
            if (section) section.style.display = "none";
        }
    }


    // Handle tile clicks
    function setupTileHandlers() {
        const tiles = document.querySelectorAll(".tile-item:not(.add-tile-btn)");

        tiles.forEach(tile => {
            // Skip if this tile already has a handler
            if (tile.dataset.handlerAttached === 'true') {
                return;
            }

            // Mark this tile as having a handler
            tile.dataset.handlerAttached = 'true';

            const checkbox = tile.querySelector(".tile-check");
            const hiddenInput = tile.querySelector('input[type="hidden"]');

            tile.addEventListener("click", (e) => {
                e.preventDefault();

                if (e.target === hiddenInput) return;

                if (e.target !== checkbox) {
                    checkbox.checked = !checkbox.checked;
                }

                toggleTileVisibility(tile);
            });
        });
    }


    // Form validation before submit
    function validateForm(form) {
        // Clear previous error styling
        form.querySelectorAll('.is-invalid').forEach(el => el.classList.remove('is-invalid'));
        form.querySelectorAll('.btn-danger').forEach(btn => {
            if (btn.classList.contains('btn-upload-pdf-sub')) {
                btn.classList.add('btn-warning');
                btn.classList.remove('btn-danger');
            }
        });

        let isValid = true;
        let firstErrorField = null;

        // Validate basic event info
        const eventName = form.querySelector('#eventName');
        const startDate = form.querySelector('input[name="start_date"]');
        const endDate = form.querySelector('input[name="end_date"]');
        const eventLocation = form.querySelector('input[name=event_location]')

        if (!eventName.value.trim()) {
            eventName.classList.add('is-invalid');
            isValid = false;
            if (!firstErrorField) firstErrorField = eventName;
        }

        if (!startDate.value) {
            startDate.classList.add('is-invalid');
            isValid = false;
            if (!firstErrorField) firstErrorField = startDate;
        }

        if (!endDate.value) {
            endDate.classList.add('is-invalid');
            isValid = false;
            if (!firstErrorField) firstErrorField = endDate;
        }

        if (!eventLocation.value.trim()) {
            eventLocation.classList.add('is-invalid');
            isValid = false;
            if (!firstErrorField) firstErrorField = eventLocation;
        }

        // Validate visible tile sections
        // Validate visible tile sections
        const visibleSections = form.querySelectorAll('.tile-section[style*="display: block"]');
        visibleSections.forEach(section => {
            const subsections = section.querySelectorAll('.subsection');

            // Only validate subsections if they exist
            subsections.forEach(subsection => {
                const nameInput = subsection.querySelector('input[type="text"]');

                if (!nameInput.value.trim()) {
                    nameInput.classList.add('is-invalid');
                    isValid = false;
                    if (!firstErrorField) firstErrorField = nameInput;
                }
            });
        });


        // Date validation
        const startDateValue = startDate.value;
        const endDateValue = endDate.value;
        const now = new Date();

        if (startDateValue) {
            const startDateObj = new Date(startDateValue);

            if (startDateObj <= now) {
                startDate.classList.add('is-invalid');
                Swal.fire({
                    icon: 'error',
                    title: 'Invalid Start Time',
                    text: 'Start date and time must be in the future'
                });
                isValid = false;
                if (!firstErrorField) firstErrorField = startDate;
            }
        }

        if (startDateValue && endDateValue) {
            const startDateObj = new Date(startDateValue);
            const endDateObj = new Date(endDateValue);

            if (endDateObj <= startDateObj) {
                endDate.classList.add('is-invalid');
                Swal.fire({
                    icon: 'error',
                    title: 'Invalid End Time',
                    text: 'End date and time must be later than the start date and time'
                });
                isValid = false;
                if (!firstErrorField) firstErrorField = endDate;
            }
        }

        // Scroll to first error
        if (!isValid && firstErrorField) {
            firstErrorField.scrollIntoView({
                behavior: 'smooth',
                block: 'center'
            });
            if (firstErrorField.focus) firstErrorField.focus();
        }

        return isValid;
    }

    function setupFormSubmit() {
        const form = document.querySelector('form');
        if (!form) return;

        form.addEventListener('keydown', function(e) {
            // Prevent submit on Enter key
            if (e.key === 'Enter') {
                // Allow Enter in textarea if you ever add one
                if (e.target.tagName.toLowerCase() !== 'textarea') {
                    e.preventDefault();
                    return false;
                }
            }
        });

        form.addEventListener('submit', function(e) {
            e.preventDefault();

            if (!validateForm(form)) {
                Swal.fire({
                    icon: 'error',
                    title: 'Missing information',
                    text: 'Please fill all required fields',
                });
                return;
            }

            // Show loading modal
            Swal.fire({
                title: 'Uploading Event',
                text: 'Please wait...',
                allowOutsideClick: false,
                allowEscapeKey: false,
                didOpen: () => Swal.showLoading()
            });

            const formData = new FormData(form);

            // ← NEW: serialize only selected tiles (custom or main)
            const selectedTiles = serializeSelectedTiles();
            formData.append('selected_tiles', JSON.stringify(selectedTiles));

            fetch(form.action, {
                    method: 'POST',
                    body: formData,
                })
                .then(res => res.json())
                .then(data => {
                    Swal.close();
                    if (data.success) {
                        Swal.fire({
                            icon: 'success',
                            title: 'Success',
                            text: data.message,
                            timer: 1500,
                            showConfirmButton: false
                        }).then(() => window.location.href = data.redirect);
                    } else {
                        Swal.fire({
                            icon: 'error',
                            title: 'Error',
                            html: data.message || 'Something went wrong'
                        });
                    }
                })
                .catch(() => {
                    Swal.close();
                    Swal.fire({
                        icon: 'error',
                        title: 'Server Error',
                        text: 'Please try again later'
                    });
                });
        });
    }


    // DOM Ready
    document.addEventListener("DOMContentLoaded", async () => {
        // Fetch tiles first
        await fetchTiles();

        // Then initialize everything else
        initializeSections();
        setupFormSubmit();
    });
</script>

<style>
    .tile-item img {
        width: 50px !important;
        height: 50px !important;
        object-fit: contain;
        /* Keeps aspect ratio without distortion */
    }

    .spinner-border {
        width: 2rem;
        height: 2rem;
        border-width: 0.2em;
    }

    .alert-success .btn-outline-danger:hover {
        background-color: #dc3545;
        color: white;
    }

    .text-truncate {
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
    }

    .subsection {
        background-color: transparent !important;
        box-shadow: none !important;
        border: none !important;
    }

    /* Add validation styling */
    .is-invalid {
        border-color: #dc3545 !important;
        box-shadow: 0 0 0 0.2rem rgba(220, 53, 69, 0.25) !important;
    }

    .btn-danger.btn-upload-pdf-sub {
        background-color: #dc3545 !important;
        border-color: #dc3545 !important;
    }

    .subsection {
        background-color: #f8f9fa;
    }

    .btn-add-subsection {
        white-space: nowrap;
        padding: 8px 10px;
        margin-top: 10px;
        margin-bottom: 10px;
    }

    .tiles-wrapper {
        display: flex;
        flex-wrap: wrap;
        gap: 20px;
        margin-bottom: 20px;
    }

    .tile-container {
        background-color: unset;
        display: flex;
        flex-direction: column;
        align-items: center;
        gap: 5px;
    }

    .tile-item {
        cursor: pointer;
        position: relative;
        display: block;
    }

    .tile-item img {
        display: block;
    }

    .tile-name {
        font-size: 11px;
        font-weight: 500;
        text-align: center;
        color: #333;
        max-width: 80px;
        line-height: 1.2;
    }

    .tile-container:has(.tile-item.selected) .tile-name {
        color: #007bff;
        font-weight: 600;
    }

    /* Hide the checkbox */
    .tile-check {
        position: absolute;
        opacity: 0;
        pointer-events: none;
    }
</style>