<layout name="admin" />

<div class="section">
    <div class="page-header-actions">
        <div>
            <h2>{{ title }}</h2>
            <p>{{ subtitle }}</p>
        </div>
    </div>

    <!-- Image Upload Section -->
    <div class="stat-card full-width">
        <h3>Upload Images</h3>
        <div data-module="image-manager"
             data-image-uploader
             data-upload-url="/api/images"
             data-max-file-size="10485760"
             data-allowed-types="image/jpeg,image/png,image/gif,image/webp"
             data-max-files="10">

            <div class="upload-area">
                <div class="upload-icon">
                    <svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1">
                        <path d="M14.5 4h-5L7 7H4a2 2 0 0 0-2 2v9a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2V9a2 2 0 0 0-2-2h-3l-2.5-3z"></path>
                        <circle cx="12" cy="13" r="3"></circle>
                    </svg>
                </div>
                <h4>Drag & Drop Images Here</h4>
                <p>Or click to select files from your computer</p>
                <button type="button" class="upload-btn">Choose Files</button>
                <input type="file" class="upload-input" multiple accept="image/*" hidden>

                <div class="upload-constraints">
                    <small>Max file size: 10MB | Supported: JPEG, PNG, GIF, WebP | Max 10 files at once</small>
                </div>
            </div>

            <!-- Upload Progress -->
            <div class="upload-progress" style="display: none;">
                <div class="progress-header">
                    <h4>Uploading Images...</h4>
                    <span class="progress-text">0 / 0</span>
                </div>
                <div class="progress-bar">
                    <div class="progress-fill"></div>
                </div>
                <div class="upload-files"></div>
            </div>
        </div>
    </div>

    <!-- Image Gallery Section - Now using LiveComponent -->
    <div class="stat-card full-width">
        <h3>Image Gallery (LiveComponent)</h3>
        <p style="color: var(--gray-600); margin-bottom: 20px;">
            Real-time image gallery with server-side filtering, sorting, and actions
        </p>

        <!-- LiveComponent replaces JavaScript-based gallery -->
        {{image_gallery}}
    </div>

    <!-- Legacy Image Slots Section (for backward compatibility) -->
    <div class="stat-card full-width">
        <h3>Image Slots (Legacy)</h3>
        <p style="color: var(--gray-600); margin-bottom: 20px;">
            Legacy image slots system - images can be dragged from the gallery above
        </p>

        <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); gap: 20px;">
            <for var="slot" in="slots">
                <div class="stat-card slot-item" data-slot-id="{{ slot.id }}">
                    <div style="display: flex; justify-content: space-between; align-items: center;">
                        <div>
                            <h4>{{ slot.slotName }}</h4>
                            <p style="color: var(--gray-600); margin: 0;">ID: {{ slot.id }}</p>
                        </div>
                        <div class="slot-image-container" style="width: 100px; height: 100px;">
                            <div style="border: 2px dashed var(--gray-300); display: flex; align-items: center; justify-content: center; height: 100%; border-radius: 4px; cursor: pointer;"
                                 ondrop="handleDrop(event, '{{ slot.id }}')"
                                 ondragover="handleDragOver(event)"
                                 ondragleave="handleDragLeave(event)">
                                <span style="color: var(--gray-500); font-size: 12px; text-align: center;">Drop image here</span>
                            </div>
                        </div>
                    </div>
                </div>
            </for>
        </div>
    </div>
</div>

<!-- Image Modal -->
<div data-image-modal style="display: none;">
    <div class="modal-backdrop"></div>
    <div class="modal-content">
        <div class="modal-header">
            <h3 class="modal-title">Image Details</h3>
            <button type="button" class="modal-close">&times;</button>
        </div>

        <div class="modal-body">
            <div class="modal-image-container">
                <img class="modal-image" src="" alt="">
            </div>

            <div class="modal-details">
                <div class="detail-group">
                    <label>Filename:</label>
                    <span class="detail-filename"></span>
                </div>

                <div class="detail-group">
                    <label>Dimensions:</label>
                    <span class="detail-dimensions"></span>
                </div>

                <div class="detail-group">
                    <label>File Size:</label>
                    <span class="detail-file-size"></span>
                </div>

                <div class="detail-group">
                    <label>Type:</label>
                    <span class="detail-mime-type"></span>
                </div>

                <div class="detail-group">
                    <label>Upload Date:</label>
                    <span class="detail-created-at"></span>
                </div>

                <div class="detail-group">
                    <label>Alt Text:</label>
                    <input type="text" class="detail-alt-text" placeholder="Enter alt text for accessibility">
                </div>
            </div>
        </div>

        <div class="modal-footer">
            <button type="button" class="btn btn-secondary modal-close">Close</button>
            <button type="button" class="btn btn-primary save-alt-text">Save Alt Text</button>
            <button type="button" class="btn btn-danger delete-image">Delete Image</button>
        </div>
    </div>
</div>

<style>
/* Image Manager Specific Styles */
.page-header-actions {
    display: flex;
    justify-content: space-between;
    align-items: start;
    margin-bottom: 20px;
}

.page-header-actions h2 {
    margin: 0;
}

.page-header-actions p {
    margin: 4px 0 0 0;
    color: var(--gray-600);
}

/* Upload Styles */
.upload-area {
    border: 2px dashed var(--gray-300);
    border-radius: 8px;
    padding: 40px 20px;
    text-align: center;
    cursor: pointer;
    transition: all 0.2s ease;
    background: var(--gray-50);
}

.upload-area:hover {
    border-color: var(--primary);
    background: rgba(30, 64, 175, 0.05);
}

.upload-area.drag-over {
    border-color: var(--primary);
    background: rgba(30, 64, 175, 0.1);
    transform: scale(1.02);
}

.upload-icon {
    color: var(--gray-400);
    margin-bottom: 16px;
}

.upload-area h4 {
    margin: 0 0 8px 0;
    color: var(--gray-700);
    font-size: 18px;
}

.upload-area p {
    margin: 0 0 20px 0;
    color: var(--gray-500);
}

.upload-btn {
    background: var(--primary);
    color: white;
    border: none;
    padding: 12px 24px;
    border-radius: 6px;
    font-size: 14px;
    cursor: pointer;
    transition: background 0.2s;
}

.upload-btn:hover {
    background: #1d4ed8;
}

.upload-constraints {
    margin-top: 16px;
}

.upload-constraints small {
    color: var(--gray-500);
    font-size: 12px;
}

/* Progress Styles */
.upload-progress {
    margin-top: 20px;
    padding: 20px;
    background: var(--gray-50);
    border-radius: 8px;
}

.progress-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 12px;
}

.progress-header h4 {
    margin: 0;
    font-size: 16px;
}

.progress-text {
    font-size: 14px;
    color: var(--gray-600);
}

.progress-bar {
    height: 8px;
    background: var(--gray-200);
    border-radius: 4px;
    overflow: hidden;
    margin-bottom: 16px;
}

.progress-fill {
    height: 100%;
    background: var(--primary);
    width: 0%;
    transition: width 0.3s ease;
}

.upload-files {
    display: flex;
    flex-direction: column;
    gap: 8px;
}

.upload-file {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 8px 12px;
    background: white;
    border-radius: 4px;
    border: 1px solid var(--gray-200);
}

.upload-file.success {
    border-color: var(--success);
    background: rgba(5, 150, 105, 0.05);
}

.upload-file.error {
    border-color: var(--danger);
    background: rgba(220, 38, 38, 0.05);
}

/* Gallery Styles */
.image-gallery {
    width: 100%;
}

.gallery__controls {
    display: flex;
    gap: 16px;
    margin-bottom: 20px;
    align-items: center;
    flex-wrap: wrap;
}

.gallery__search-wrapper {
    position: relative;
    flex: 1;
    min-width: 250px;
}

.gallery__search {
    width: 100%;
    padding: 8px 32px 8px 12px;
    border: 1px solid var(--gray-300);
    border-radius: 6px;
    font-size: 14px;
}

.gallery__search-clear {
    position: absolute;
    right: 8px;
    top: 50%;
    transform: translateY(-50%);
    background: none;
    border: none;
    font-size: 18px;
    cursor: pointer;
    color: var(--gray-400);
}

.gallery__sort-wrapper {
    display: flex;
    align-items: center;
    gap: 8px;
}

.gallery__sort {
    padding: 8px 12px;
    border: 1px solid var(--gray-300);
    border-radius: 6px;
    font-size: 14px;
    background: white;
}

.gallery__grid {
    display: grid;
    grid-template-columns: repeat(var(--columns, 4), 1fr);
    gap: 16px;
    margin-bottom: 20px;
}

@media (max-width: 1024px) {
    .gallery__grid {
        grid-template-columns: repeat(3, 1fr);
    }
}

@media (max-width: 768px) {
    .gallery__grid {
        grid-template-columns: repeat(2, 1fr);
    }
}

@media (max-width: 480px) {
    .gallery__grid {
        grid-template-columns: 1fr;
    }
}

.gallery__item {
    background: white;
    border: 1px solid var(--gray-200);
    border-radius: 8px;
    overflow: hidden;
    transition: all 0.2s ease;
    cursor: pointer;
}

.gallery__item:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.gallery__item--selected {
    border-color: var(--primary);
    box-shadow: 0 0 0 2px rgba(30, 64, 175, 0.2);
}

.gallery__item-inner {
    height: 100%;
    display: flex;
    flex-direction: column;
}

.gallery__item-image {
    position: relative;
    aspect-ratio: 16 / 10;
    overflow: hidden;
}

.gallery__item-image img {
    width: 100%;
    height: 100%;
    object-fit: cover;
    transition: transform 0.2s ease;
}

.gallery__item:hover .gallery__item-image img {
    transform: scale(1.05);
}

.gallery__item-overlay {
    position: absolute;
    inset: 0;
    background: rgba(0, 0, 0, 0.5);
    display: flex;
    align-items: center;
    justify-content: center;
    opacity: 0;
    transition: opacity 0.2s ease;
}

.gallery__item:hover .gallery__item-overlay {
    opacity: 1;
}

.gallery__item-actions {
    display: flex;
    gap: 8px;
}

.action-btn {
    background: rgba(255, 255, 255, 0.9);
    border: none;
    width: 36px;
    height: 36px;
    border-radius: 50%;
    cursor: pointer;
    font-size: 16px;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: all 0.2s ease;
}

.action-btn:hover {
    background: white;
    transform: scale(1.1);
}

.gallery__item-info {
    padding: 12px;
    flex: 1;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
}

.gallery__item-name {
    font-weight: 500;
    margin-bottom: 8px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    font-size: 14px;
}

.gallery__item-meta {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
    font-size: 12px;
    color: var(--gray-500);
}

.meta-item {
    background: var(--gray-100);
    padding: 2px 6px;
    border-radius: 3px;
    font-size: 11px;
}

/* Pagination */
.gallery__pagination {
    text-align: center;
    margin-top: 20px;
}

.gallery__load-more {
    background: var(--primary);
    color: white;
    border: none;
    padding: 12px 24px;
    border-radius: 6px;
    font-size: 14px;
    cursor: pointer;
    transition: background 0.2s;
}

.gallery__load-more:hover {
    background: #1d4ed8;
}

.gallery__load-more:disabled {
    background: var(--gray-400);
    cursor: not-allowed;
}

/* Loading and Empty States */
.gallery-loading,
.gallery__loading {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 60px 20px;
    color: var(--gray-500);
}

.loading-spinner {
    width: 32px;
    height: 32px;
    border: 3px solid var(--gray-200);
    border-top: 3px solid var(--primary);
    border-radius: 50%;
    animation: spin 1s linear infinite;
    margin-bottom: 16px;
}

@keyframes spin {
    0% { transform: rotate(0deg); }
    100% { transform: rotate(360deg); }
}

.gallery__empty {
    text-align: center;
    padding: 60px 20px;
    color: var(--gray-500);
}

.empty-state__icon {
    margin-bottom: 16px;
    color: var(--gray-300);
}

.gallery__empty h3 {
    margin: 0 0 8px 0;
    color: var(--gray-700);
}

.gallery__empty p {
    margin: 0;
    color: var(--gray-500);
}

/* Modal Styles */
[data-image-modal] {
    position: fixed;
    inset: 0;
    z-index: 1000;
}

.modal-backdrop {
    position: absolute;
    inset: 0;
    background: rgba(0, 0, 0, 0.5);
    backdrop-filter: blur(4px);
}

.modal-content {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    background: white;
    border-radius: 12px;
    max-width: 800px;
    max-height: 90vh;
    width: 90vw;
    overflow: hidden;
    display: flex;
    flex-direction: column;
}

.modal-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20px 24px;
    border-bottom: 1px solid var(--gray-200);
}

.modal-title {
    margin: 0;
    font-size: 18px;
    font-weight: 600;
}

.modal-close {
    background: none;
    border: none;
    font-size: 24px;
    cursor: pointer;
    color: var(--gray-400);
    padding: 0;
    line-height: 1;
}

.modal-close:hover {
    color: var(--gray-600);
}

.modal-body {
    padding: 24px;
    overflow-y: auto;
    flex: 1;
    display: grid;
    grid-template-columns: 1fr 250px;
    gap: 24px;
}

.modal-image-container {
    display: flex;
    align-items: center;
    justify-content: center;
    min-height: 200px;
}

.modal-image {
    max-width: 100%;
    max-height: 400px;
    border-radius: 8px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.modal-details {
    display: flex;
    flex-direction: column;
    gap: 16px;
}

.detail-group {
    display: flex;
    flex-direction: column;
    gap: 4px;
}

.detail-group label {
    font-weight: 500;
    color: var(--gray-700);
    font-size: 14px;
}

.detail-group span,
.detail-group input {
    color: var(--gray-600);
    font-size: 14px;
}

.detail-alt-text {
    padding: 8px 12px;
    border: 1px solid var(--gray-300);
    border-radius: 6px;
    font-size: 14px;
    width: 100%;
}

.modal-footer {
    padding: 20px 24px;
    border-top: 1px solid var(--gray-200);
    display: flex;
    gap: 12px;
    justify-content: flex-end;
}

.btn {
    padding: 8px 16px;
    border: none;
    border-radius: 6px;
    font-size: 14px;
    cursor: pointer;
    transition: all 0.2s;
}

.btn-primary {
    background: var(--primary);
    color: white;
}

.btn-primary:hover {
    background: #1d4ed8;
}

.btn-secondary {
    background: var(--gray-200);
    color: var(--gray-700);
}

.btn-secondary:hover {
    background: var(--gray-300);
}

.btn-danger {
    background: var(--danger);
    color: white;
}

.btn-danger:hover {
    background: #dc2626;
}

/* Error States */
.gallery__error {
    margin: 16px 0;
    padding: 12px 16px;
    background: rgba(220, 38, 38, 0.1);
    border: 1px solid var(--danger);
    border-radius: 6px;
}

.error-message {
    display: flex;
    align-items: center;
    gap: 8px;
    color: var(--danger);
    font-size: 14px;
}

.error-close {
    background: none;
    border: none;
    color: var(--danger);
    cursor: pointer;
    margin-left: auto;
    font-size: 16px;
}

/* Legacy Slots Integration */
.slot-item.selecting {
    border-color: var(--primary) !important;
    background-color: rgba(30, 64, 175, 0.1) !important;
}

@media (max-width: 768px) {
    .modal-body {
        grid-template-columns: 1fr;
        gap: 16px;
    }

    .modal-content {
        width: 95vw;
        max-height: 95vh;
    }

    .gallery__controls {
        flex-direction: column;
        align-items: stretch;
    }

    .gallery__search-wrapper {
        min-width: unset;
    }
}
</style>

<script type="module">
// Legacy slot functions for backward compatibility
let draggedImageUlid = null;
let selectedSlotId = null;

function handleDragStart(event, imageUlid) {
    draggedImageUlid = imageUlid;
    event.dataTransfer.effectAllowed = 'copy';
}

function handleDragOver(event) {
    event.preventDefault();
    event.currentTarget.style.backgroundColor = 'var(--gray-100)';
}

function handleDragLeave(event) {
    event.currentTarget.style.backgroundColor = '';
}

async function handleDrop(event, slotId) {
    event.preventDefault();
    event.currentTarget.style.backgroundColor = '';

    if (draggedImageUlid) {
        await assignImageToSlot(slotId, draggedImageUlid);
    }
}

async function assignImageToSlot(slotId, imageUlid) {
    try {
        const response = await fetch(`/api/image-slots/${slotId}/image`, {
            method: 'PUT',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({ image_ulid: imageUlid })
        });

        if (response.ok) {
            location.reload();
        } else {
            alert('Failed to assign image');
        }
    } catch (error) {
        console.error('Error:', error);
        alert('Error assigning image');
    }
}

function selectImage(imageUlid) {
    const clickedSlot = document.querySelector('.slot-item.selecting');
    if (clickedSlot) {
        const slotId = clickedSlot.dataset.slotId;
        assignImageToSlot(slotId, imageUlid);
        clickedSlot.classList.remove('selecting');
    }
}

// Make functions global for template access
window.handleDragStart = handleDragStart;
window.handleDragOver = handleDragOver;
window.handleDragLeave = handleDragLeave;
window.handleDrop = handleDrop;
window.selectImage = selectImage;

// Legacy slot click handlers - initialize when DOM is ready
document.addEventListener('DOMContentLoaded', function() {
    document.querySelectorAll('.slot-item').forEach(slot => {
        const container = slot.querySelector('.slot-image-container');
        if (container && !container.querySelector('img')) {
            container.addEventListener('click', function() {
                document.querySelectorAll('.slot-item').forEach(s => s.classList.remove('selecting'));
                slot.classList.add('selecting');
                slot.style.borderColor = 'var(--primary)';
                slot.style.backgroundColor = 'rgba(30, 64, 175, 0.1)';
            });
        }
    });
});

// Debug: Enable JavaScript logging and check module loading
console.log('🚀 Debug: Admin Image Manager Template loaded');

// Enable JavaScript debugging
if (window.Logger) {
    window.Logger.setEnabled(true);
    window.Logger.setLevel('info');
    console.log('🔧 Debug: Logger enabled');
}

// Check if the image-manager module is loaded
setTimeout(() => {
    console.log('🔍 Debug: Checking module loading...');
    if (window.activeModules) {
        console.log('📦 Available modules:', Array.from(window.activeModules.keys()));
        const imageManager = window.activeModules.get('image-manager');
        if (imageManager) {
            console.log('✅ Image Manager module found:', imageManager);
        } else {
            console.log('❌ Image Manager module NOT found');

            // Check if there are any errors for the module
            const modules = Array.from(window.activeModules.entries());
            console.log('🔧 All modules with details:', modules);
        }
    } else {
        console.log('❌ No activeModules found in window');
    }

    // Check for data-image-gallery elements
    const galleryElements = document.querySelectorAll('[data-image-gallery]');
    console.log('🖼️ Gallery elements found:', galleryElements.length, galleryElements);

    // Check for data-module elements
    const moduleElements = document.querySelectorAll('[data-module]');
    console.log('🔧 Module elements found:', moduleElements.length, moduleElements);

    // Try to check moduleHealth if available
    if (window.moduleHealth) {
        const health = window.moduleHealth();
        console.log('🏥 Module health:', health);
        console.log('🏥 Individual modules:', health.modules);
    }
}, 2000);
</script>