<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">Edit Event</h1>
    </div>

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

            <form method="post" action="<?php echo base_url('admin/update-event'); ?>" enctype="multipart/form-data">
                <input type="hidden" name="event_id" value="<?php echo $event_id; ?>">

                <!-- 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"
                                    value="<?php echo htmlspecialchars($event['event_name'] ?? ''); ?>" required />
                            </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"
                                    value="<?php echo htmlspecialchars($event['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"
                                    value="<?php echo isset($event['start_date']) ? date('Y-m-d', $event['start_date'] / 1000) : ''; ?>"
                                    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"
                                    value="<?php echo isset($event['end_date']) ? date('Y-m-d', $event['end_date'] / 1000) : ''; ?>"
                                    required />
                            </div>
                        </div>

                    </div>

                    <div class="tiles-section">
                        <label>Main Tiles</label>
                        <div class="tiles-wrapper" id="mainTilesWrapper">
                            <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">
                            <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>

                    <!-- Custom Tile Modal -->
                    <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" <?php echo (!empty($event['enable_admin_messages'])) ? 'checked' : ''; ?> />
                        <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/content'); ?>" class="btn-cancel close-modal">Cancel</a>
                        <button type="submit" class="btn btn-upload" id="updateEvent">Update 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>
    // Existing event data from PHP
    const existingEventData = <?php echo json_encode($event); ?>;
    console.log('Existing Event Data:', existingEventData);

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

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

    // Build dynamic tile configuration from API + custom tiles
    let tileConfigs = {};
    let tilesData = [];
    let customTileIds = [];
    let customTileModal;

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

    // Fetch main tiles + merge custom tiles
    async function fetchAllTiles() {
        try {
            const response = await fetch('<?php echo base_url('admin/api/tiles'); ?>');
            const data = await response.json();

            if (!data.success || !data.tiles) {
                throw new Error('Invalid response format');
            }

            tilesData = [...data.tiles];

            // Extract custom tile IDs from categories
            const eventCategories = existingEventData.categories || [];
            const mainTileIds = data.tiles.map(t => t.tile_id);
            customTileIds = eventCategories.filter(id => !mainTileIds.includes(id));

            // Fetch each custom tile
            if (customTileIds.length > 0) {
                console.log('Fetching custom tiles:', customTileIds);

                const customTilePromises = customTileIds.map(id => fetchCustomTile(id));
                const customTiles = await Promise.all(customTilePromises);

                customTiles.forEach(tile => {
                    if (tile) {
                        tilesData.push(tile);
                    }
                });
            }

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

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

        } catch (error) {
            console.error('Error fetching tiles:', error);

            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.'
            });
        }
    }

    // Fetch custom tile by ID
    async function fetchCustomTile(tileId) {
        try {
            const response = await fetch(`<?php echo base_url('admin/api/tile/'); ?>${tileId}`);
            const data = await response.json();

            if (data.success && data.data) {
                return {
                    tile_id: data.data.tile_id,
                    tile_name: data.data.tile_name,
                    tile_url: data.data.tile_url,
                    type: data.data.type || 'other',
                    slug: data.data.slug
                };
            }
            return null;
        } catch (error) {
            console.error('Error fetching custom tile:', error);
            return null;
        }
    }

    // Create tile HTML
    function createTileHTML(tile) {
        const eventCategories = existingEventData.categories || [];
        const isChecked = eventCategories.includes(tile.tile_id);

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

        return `
            <div class="tile-container">
                <label class="tile-item ${isChecked ? 'selected' : ''}" data-tile="${tile.slug}">
                    <input type="hidden" name="tiles[${tile.tile_id}]" value='${tileValue}'>
                    <input type="checkbox" name="selected_tiles[${tile.tile_id}]" value='${tileValue}'
                        class="tile-check" ${isChecked ? 'checked' : ''}>
                    <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>
        `;
    }

    // Render tiles
    function renderTiles(tiles) {
        const mainWrapper = document.getElementById('mainTilesWrapper');
        const otherWrapper = document.getElementById('otherTilesWrapper');

        if (!mainWrapper || !otherWrapper) return;

        mainWrapper.innerHTML = '';
        otherWrapper.innerHTML = '';

        tiles.forEach(tile => {
            const tileHTML = createTileHTML(tile);
            const tempDiv = document.createElement('div');
            tempDiv.innerHTML = tileHTML;
            const tileElement = tempDiv.firstElementChild;

            if (tile.type === 'main') {
                mainWrapper.appendChild(tileElement);
            } else {
                otherWrapper.appendChild(tileElement);
            }
        });

        setupTileHandlers();
        appendAddTileButton();
    }

    // Append "Add Tile" button
    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;
            }

            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 - FIXED VERSION
    document.addEventListener('DOMContentLoaded', () => {
        const saveBtn = document.getElementById('saveCustomTileBtn');
        if (saveBtn) {
            saveBtn.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);
                document.activeElement.blur();

                // Add tile dynamically to OTHER tiles wrapper (not main)
                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);

                // Setup handlers for both tiles and the new subsection button
                setupTileHandlers();
                setupAddSubsectionHandlers();

                tileNameInput.value = '';
                customTileModal.hide();
            });
        }
    });

    // Serialize selected tiles
    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 section = document.getElementById(slug);

            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;
    }

    // Component generator functions
    const FormComponents = {
        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>
                    <div class="subsections-container" data-section="${sectionId}"></div>
                </div>
            `;
        }
    };

    function initializeSections() {
        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;
            const html = FormComponents.generateTileForm(sectionId, config.title);
            container.insertAdjacentHTML('beforeend', html);
        });

        // Load existing subsections for checked tiles
        Object.keys(tileConfigs).forEach(sectionId => {
            const config = tileConfigs[sectionId];
            const section = document.getElementById(sectionId);

            if (section) {
                const tileCheckbox = document.querySelector(`.tile-item[data-tile="${sectionId}"] .tile-check`);

                if (tileCheckbox && tileCheckbox.checked) {
                    section.style.display = 'block';

                    const existingTile = existingEventData[config.slug];

                    if (existingTile && typeof existingTile === 'object' && Object.keys(existingTile).length > 0) {
                        // CRITICAL FIX: Pass Firebase doc IDs as subsectionKey
                        Object.keys(existingTile).forEach(firestoreDocId => {
                            const subsection = existingTile[firestoreDocId];
                            addSubsection(section, sectionId, subsection, firestoreDocId);
                        });
                    } else {
                        addSubsection(section, sectionId);
                    }

                    initializedSections.add(sectionId);
                }
            }
        });

        // Setup Add Subsection handlers - MOVED HERE (called only once)
        setupAddSubsectionHandlers();
    }

    // Global object to store File objects for each subsection
    const subsectionFiles = {};

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

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

        const name = existingData?.name || '';
        const pdfs = existingData?.pdfs || [];

        const docId = subsectionKey || '';

        // Generate PDF list HTML
        let pdfListHTML = '';
        if (pdfs.length > 0) {
            pdfs.forEach((pdf, idx) => {
                const fileName = pdf.split('/').pop().split('?')[0];
                const decodedFileName = decodeURIComponent(fileName);

                pdfListHTML += `
                    <div class="alert alert-success py-1 px-2 mb-1 d-flex align-items-center justify-content-between existing-pdf-item">
                        <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;">${decodedFileName}</span>
                        </div>
                        <div class="d-flex gap-1">
                            <button type="button" 
                                    class="btn btn-sm btn-pdf-action btn-view-pdf" 
                                    data-pdf-url="${pdf}"
                                    title="View PDF">
                                👁
                            </button>
                            <button type="button" 
                                    class="btn btn-sm btn-pdf-action btn-delete-pdf" 
                                    title="Delete PDF">
                                &times;
                            </button>
                        </div>
                        <input type="hidden" name="${fieldName}[subsections][${subsectionIndex}][existing_pdfs][]" value="${btoa(pdf)}">
                    </div>
                `;
            });
        }

        const subsectionHTML = `
        <div class="subsection mb-2 p-2" data-subsection-id="${subsectionIndex}" data-firestore-doc-id="${docId}">
            ${docId ? `<input type="hidden" name="${fieldName}[subsections][${subsectionIndex}][key]" value="${docId}">` : ''}
            <input type="hidden" name="${fieldName}[subsections][${subsectionIndex}][subsection_index]" value="${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" 
                               value="${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}">
                            ${pdfListHTML || ''}
                        </div>
                    </div>
                </div>
            </div>
        </div>
    `;

        container.insertAdjacentHTML('beforeend', subsectionHTML);

        setupSubsectionPdfHandlers(section);
        setupDeleteSubsectionHandlers(section);
        setupExistingPdfHandlers(section);
    }

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

        deleteButtons.forEach(btn => {
            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
    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}`;

                if (!subsectionFiles[storageKey]) {
                    subsectionFiles[storageKey] = [];
                }

                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');

        const files = subsectionFiles[storageKey];

        const newFileItems = pdfList.querySelectorAll('.alert-success:not(.existing-pdf-item)');
        newFileItems.forEach(item => item.remove());

        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>
                <div class="d-flex gap-1">
                    <button type="button" 
                            class="btn btn-sm btn-pdf-action btn-view-new-pdf" 
                            data-file-index="${index}"
                            data-storage-key="${storageKey}"
                            title="View PDF">
                        👁
                    </button>
                    <button type="button" 
                            class="btn btn-sm btn-pdf-action btn-delete-new-pdf" 
                            data-file-index="${index}"
                            data-storage-key="${storageKey}"
                            title="Delete PDF">
                        &times;
                    </button>
                </div>
            `;
                pdfList.appendChild(fileItem);
            });

            // Setup view and delete handlers for newly added PDFs
            setupNewPdfHandlers(subsection);
        } else {
            btn.textContent = 'Choose PDF Files';
            btn.classList.replace('btn-success', 'btn-warning');
        }
    }

    // Setup handlers for newly uploaded PDF files (view & delete)
    function setupNewPdfHandlers(subsection) {
        // View button handlers
        const viewButtons = subsection.querySelectorAll('.btn-view-new-pdf');
        viewButtons.forEach(btn => {
            btn.addEventListener('click', function(e) {
                e.stopPropagation();
                const storageKey = this.getAttribute('data-storage-key');
                const fileIndex = parseInt(this.getAttribute('data-file-index'));
                const file = subsectionFiles[storageKey][fileIndex];

                if (file) {
                    // Create a temporary URL for the file and open it
                    const fileURL = URL.createObjectURL(file);
                    window.open(fileURL, '_blank');

                    // Clean up the URL after a delay
                    setTimeout(() => URL.revokeObjectURL(fileURL), 1000);
                }
            });
        });

        // Delete button handlers
        const deleteButtons = subsection.querySelectorAll('.btn-delete-new-pdf');
        deleteButtons.forEach(btn => {
            btn.addEventListener('click', function(e) {
                e.stopPropagation();
                const storageKey = this.getAttribute('data-storage-key');
                const fileIndex = parseInt(this.getAttribute('data-file-index'));

                Swal.fire({
                    title: 'Delete PDF?',
                    text: 'Are you sure you want to remove this PDF?',
                    icon: 'warning',
                    showCancelButton: true,
                    confirmButtonColor: '#d33',
                    cancelButtonColor: '#3085d6',
                    confirmButtonText: 'Yes, delete it!'
                }).then((result) => {
                    if (result.isConfirmed) {
                        // Remove from storage array
                        subsectionFiles[storageKey].splice(fileIndex, 1);

                        // Get the input and update it
                        const input = subsection.querySelector('.pdf-input-sub');

                        // Re-render the list
                        renderPdfList(storageKey, subsection);
                        updateNativeInput(input, storageKey);

                        Swal.fire({
                            title: 'Deleted!',
                            text: 'PDF has been removed.',
                            icon: 'success',
                            timer: 1500,
                            showConfirmButton: false
                        });
                    }
                });
            });
        });
    }

    // 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);
    };

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

    // Add this new function to handle PDF deletion from existing subsections
    function setupExistingPdfHandlers(section) {
        const viewButtons = section.querySelectorAll('.btn-view-pdf');
        viewButtons.forEach(btn => {
            const newBtn = btn.cloneNode(true);
            btn.parentNode.replaceChild(newBtn, btn);

            newBtn.addEventListener('click', function(e) {
                e.stopPropagation();
                const pdfUrl = this.getAttribute('data-pdf-url');
                if (pdfUrl) {
                    window.open(pdfUrl, '_blank');
                }
            });
        });

        const deleteButtons = section.querySelectorAll('.existing-pdf-item .btn-delete-pdf');
        deleteButtons.forEach(btn => {
            const newBtn = btn.cloneNode(true);
            btn.parentNode.replaceChild(newBtn, btn);

            newBtn.addEventListener('click', function(e) {
                e.stopPropagation();
                const pdfWrapper = this.closest('.existing-pdf-item');

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

    // Setup Add Subsection button handlers - IMPROVED VERSION
    function setupAddSubsectionHandlers() {
        const addButtons = document.querySelectorAll('.btn-add-subsection');

        addButtons.forEach(btn => {
            // Skip if already initialized
            if (btn.dataset.initialized === 'true') {
                return;
            }

            // Mark as initialized
            btn.dataset.initialized = 'true';

            // Use cloning to remove old event listeners if any
            const newBtn = btn.cloneNode(true);
            newBtn.dataset.initialized = 'true';
            btn.parentNode.replaceChild(newBtn, btn);

            newBtn.addEventListener('click', function() {
                const sectionId = this.getAttribute('data-section');
                const section = document.getElementById(sectionId);
                addSubsection(section, sectionId);
            });
        });
    }

    // 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 isChecked = checkbox.checked;

        if (isChecked) {
            currentTile.classList.add("selected");
            img.src = img.dataset.active;

            if (section) {
                section.style.display = "block";

                if (!initializedSections.has(sectionId)) {
                    const config = tileConfigs[sectionId];
                    const existingTile = existingEventData[config?.slug];

                    if (existingTile && typeof existingTile === 'object' && Object.keys(existingTile).length > 0) {
                        Object.keys(existingTile).forEach(subKey => {
                            const subsection = existingTile[subKey];
                            addSubsection(section, sectionId, subsection, subKey);
                        });
                    } else {
                        addSubsection(section, sectionId);
                    }

                    initializedSections.add(sectionId);
                }

                // Always scroll into view when tile is checked
                setTimeout(() => {
                    section.scrollIntoView({
                        behavior: 'smooth',
                        block: 'nearest'
                    });
                }, 100);
            }
        } else {
            currentTile.classList.remove("selected");
            img.src = img.dataset.default;

            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) {
        form.querySelectorAll('.is-invalid').forEach(el => el.classList.remove('is-invalid'));

        let isValid = true;
        let firstErrorField = null;

        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;
        }

        if (startDate.value && endDate.value) {
            const startDateObj = new Date(startDate.value);
            const endDateObj = new Date(endDate.value);

            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;
            }
        }

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

            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;
                }
            });
        });

        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('submit', function(e) {
            e.preventDefault();

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

            Swal.fire({
                title: 'Updating Event',
                text: 'Please wait...',
                allowOutsideClick: false,
                allowEscapeKey: false,
                didOpen: () => Swal.showLoading()
            });

            const formData = new FormData(form);

            // Serialize selected tiles
            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 () => {
        await fetchAllTiles();
        initializeSections();
        setupFormSubmit();
    });
</script>

<style>
    .btn-pdf-action {
        background-color: transparent;
        border: none;
        font-size: 18px;
        padding: 0 4px;
        cursor: pointer;
        transition: transform 0.2s;
    }

    .btn-pdf-action:hover {
        transform: scale(1.2);
    }



    .btn-delete-pdf:hover,
    .btn-delete-new-pdf:hover {
        color: #dc3545;
    }

    .btn-view-pdf:hover,
    .btn-view-new-pdf:hover {
        color: #007bff;
    }

    .tile-item img {
        width: 50px !important;
        height: 50px !important;
        object-fit: contain;
        /* preserves aspect ratio without stretching */
        display: block;
    }

    .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;
    }

    .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 {
        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;
    }

    .tile-check {
        position: absolute;
        opacity: 0;
        pointer-events: none;
    }

    .pdf-item-wrapper {
        transition: all 0.3s ease;
    }

    .pdf-item-wrapper:hover {
        transform: translateY(-2px);
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    }
</style>