{% extends 'base.html' %}
{% load i18n %}
{% load static %}

{% block extra_css %}
<!-- Dropzone (CDN — page-specific, benefits from edge proximity) -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/dropzone@6.0.0-beta.2/dist/dropzone.css">
<style>
    .dropzone {
        border: 2px dashed #e5e7eb;
        border-radius: 0.5rem;
        background: white;
    }
    .dropzone:hover {
        border-color: #3b82f6;
    }
    .dropzone .dz-message {
        margin: 2em 0;
    }
    .image-grid {
        display: grid;
        grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
        gap: 1rem;
        padding: 1rem;
    }
    .image-item {
        position: relative;
        aspect-ratio: 1;
        overflow: hidden;
        border-radius: 0.5rem;
        background: #f3f4f6;
    }
    .image-item img {
        width: 100%;
        height: 100%;
        object-fit: cover;
        transition: transform 0.3s ease;
    }
    .image-overlay {
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background: rgba(0, 0, 0, 0.5);
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 0.75rem;
        opacity: 0;
        transition: opacity 0.3s ease;
    }
    .image-item:hover .image-overlay {
        opacity: 1;
    }
    .image-item:hover img {
        transform: scale(1.05);
    }
    .image-action {
        background: rgba(255, 255, 255, 0.2);
        border: none;
        color: white;
        width: 2.5rem;
        height: 2.5rem;
        border-radius: 9999px;
        cursor: pointer;
        display: flex;
        align-items: center;
        justify-content: center;
        transition: background-color 0.2s;
    }
    .image-action:hover {
        background: rgba(255, 255, 255, 0.3);
    }
    .image-action svg {
        width: 1.25rem;
        height: 1.25rem;
    }
    .description-modal {
        display: none;
        position: fixed;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background: rgba(0, 0, 0, 0.75);
        z-index: 50;
        align-items: center;
        justify-content: center;
        padding: 1rem;
    }
    .modal-content {
        background: white;
        padding: 1.5rem;
        border-radius: 0.5rem;
        width: 100%;
        max-width: 500px;
        position: relative;
    }
    .modal-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 1rem;
    }
    .modal-title {
        font-size: 1.25rem;
        font-weight: 600;
        color: #1f2937;
    }
    .modal-close {
        background: none;
        border: none;
        color: #6b7280;
        cursor: pointer;
        padding: 0.5rem;
    }
    .modal-close:hover {
        color: #1f2937;
    }
    .modal-body textarea {
        width: 100%;
        min-height: 120px;
        padding: 0.75rem;
        border: 1px solid #e5e7eb;
        border-radius: 0.375rem;
        margin-bottom: 1rem;
        resize: vertical;
    }
    .modal-footer {
        display: flex;
        justify-content: flex-end;
        gap: 0.75rem;
    }
    .modal-button {
        padding: 0.5rem 1rem;
        border-radius: 0.375rem;
        font-weight: 500;
        cursor: pointer;
        transition: background-color 0.2s;
    }
    .cancel-button {
        background: #f3f4f6;
        border: 1px solid #e5e7eb;
        color: #374151;
    }
    .cancel-button:hover {
        background: #e5e7eb;
    }
    .save-button {
        background: #2563eb;
        border: 1px solid #2563eb;
        color: white;
    }
    .save-button:hover {
        background: #1d4ed8;
    }
</style>
{% endblock %}

{% block content %}
<div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
    <!-- Back Button -->
    <div class="mb-6">
        <a href="{% url 'collection-list' %}"
           class="inline-flex items-center p-2 text-gray-600 hover:text-gray-800 hover:bg-gray-50 rounded-md"
           title="{% trans 'Back to Collections' %}">
            <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                      d="M10 19l-7-7m0 0l7-7m-7 7h18"/>
            </svg>
            <span class="ml-1 text-sm">{% trans "Back to Collections" %}</span>
        </a>
    </div>

    <!-- Collection Header -->
    <div class="flex flex-col space-y-4 sm:space-y-0 sm:flex-row sm:justify-between sm:items-start mb-6">
        <!-- Title and Description -->
        <div class="flex-1">
            {% if collection.description %}
                <div class="mb-4">
                    <h3 class="text-lg font-medium text-gray-900 mb-2">{% trans "Description" %}</h3>
                    <p class="text-gray-600">{{ collection.description }}</p>
                </div>
            {% endif %}

            {% if collection.tags.exists %}
            <div class="flex flex-wrap gap-2 mt-2">
                {% for tag in collection.tags.all %}
                {% with number=forloop.counter %}
                <a href="{% url 'tag-detail' tag.slug %}"
                   class="inline-flex items-center px-3 py-1 rounded-full text-xs font-medium transition duration-150 {% if number|divisibleby:10 %}tag-10{% elif number|divisibleby:9 %}tag-9{% elif number|divisibleby:8 %}tag-8{% elif number|divisibleby:7 %}tag-7{% elif number|divisibleby:6 %}tag-6{% elif number|divisibleby:5 %}tag-5{% elif number|divisibleby:4 %}tag-4{% elif number|divisibleby:3 %}tag-3{% elif number|divisibleby:2 %}tag-2{% else %}tag-1{% endif %}">
                    {{ tag.name }}
                </a>
                {% endwith %}
                {% endfor %}
            </div>
            {% endif %}

        </div>

        <!-- Action Buttons -->
        <div class="flex flex-wrap gap-2 sm:space-x-2">
            <button type="button"
                    onclick="document.getElementById('uploadModal').classList.remove('hidden')"
                    class="inline-flex items-center px-3 py-2 sm:px-4 sm:py-2 border border-transparent text-sm font-medium rounded-md shadow-sm text-white bg-blue-600 hover:bg-blue-700">
                <svg class="w-5 h-5 sm:mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                          d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-8l-4-4m0 0L8 8m4-4v12"/>
                </svg>
                <span class="hidden sm:inline">{% trans "Upload Images" %}</span>
            </button>

            <a href="{% url 'collection-update' collection.pk %}"
               class="inline-flex items-center px-3 py-2 sm:px-4 sm:py-2 border border-gray-300 text-sm font-medium rounded-md shadow-sm text-gray-700 bg-white hover:bg-gray-50">
                <svg class="w-5 h-5 sm:mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                          d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"/>
                </svg>
                <span class="hidden sm:inline">{% trans "Edit Collection" %}</span>
            </a>

            <button type="button"
                    onclick="deleteCollection('{{ collection.pk }}')"
                    class="inline-flex items-center px-3 py-2 sm:px-4 sm:py-2 border border-transparent text-sm font-medium rounded-md shadow-sm text-white bg-red-600 hover:bg-red-700">
                <svg class="w-5 h-5 sm:mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                          d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"/>
                </svg>
                <span class="hidden sm:inline">{% trans "Delete Collection" %}</span>
            </button>

            <button type="button"
                    onclick="window.location.href='{% url 'collection-slideshow' collection.pk %}'"
                    class="inline-flex items-center px-3 py-2 sm:px-4 sm:py-2 border border-transparent text-sm font-medium rounded-md shadow-sm text-white bg-green-600 hover:bg-green-700">
                <svg class="w-5 h-5 sm:mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                          d="M15 10l4.553-2.276A1 1 0 0121 8.618v6.764a1 1 0 01-1.447.894L15 14M5 18h8a2 2 0 002-2V8a2 2 0 00-2-2H5a2 2 0 00-2 2v8a2 2 0 002 2z"/>
                </svg>
                <span class="hidden sm:inline">{% trans "Slideshow" %}</span>
            </button>
        </div>
    </div>

    <!-- Images Grid -->
    <div class="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 gap-4" id="imagesGrid">
        {% for image in collection.images.all %}
            <div class="image-item">
                <img src="{{ image.get_thumbnail_url }}" alt="{{ image.title }}" loading="lazy">
                <div class="image-overlay">
                    <a href="{{ image.get_url }}"
                           target="_blank"
                           class="p-2 text-white hover:text-blue-200"
                           title="{% trans 'View Full Size' %}">
                            <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                                      d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"/>
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                                      d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"/>
                            </svg>
                    </a>
                    <button class="image-action" onclick="editDescription('{{ image.id }}', '{{ image.description|default:'' }}')" title="{% trans 'Edit Description' %}">
                        <svg fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"/>
                        </svg>
                    </button>
                    <button class="image-action" onclick="deleteImage('{{ image.id }}')" title="{% trans 'Delete Image' %}">
                        <svg fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"/>
                        </svg>
                    </button>
                </div>
            </div>
        {% empty %}
            <div class="col-span-full flex flex-col items-center justify-center py-12 bg-white rounded-lg border-2 border-dashed border-gray-300">
                <svg class="w-12 h-12 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                          d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z"/>
                </svg>
                <h3 class="mt-2 text-sm font-medium text-gray-900">{% trans "No images" %}</h3>
                <p class="mt-1 text-sm text-gray-500">{% trans "Upload some images to get started." %}</p>
            </div>
        {% endfor %}
    </div>
</div>

<!-- Upload Modal -->
<div id="uploadModal" class="hidden fixed inset-0 bg-gray-500 bg-opacity-75 flex items-center justify-center z-50">
    <div class="bg-white rounded-lg shadow-xl max-w-3xl w-full mx-4">
        <div class="px-4 py-5 sm:p-6">
            <div class="flex justify-between items-center mb-4">
                <h3 class="text-lg font-medium text-gray-900">{% trans "Upload Images" %}</h3>
                <button type="button"
                        onclick="document.getElementById('uploadModal').classList.add('hidden')"
                        class="text-gray-400 hover:text-gray-500">
                    <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/>
                    </svg>
                </button>
            </div>
            <form id="uploadForm" class="dropzone"></form>
            <div class="mt-4 flex justify-end">
                <button type="button"
                        onclick="document.getElementById('uploadModal').classList.add('hidden')"
                        class="px-4 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-md shadow-sm hover:bg-gray-50">
                    {% trans "Done" %}
                </button>
            </div>
        </div>
    </div>
</div>

<!-- Description Modal -->
<div class="description-modal" id="descriptionModal">
    <div class="modal-content">
        <div class="modal-header">
            <h3 class="modal-title">{% trans "Edit Description" %}</h3>
            <button class="modal-close" onclick="closeDescriptionModal()">
                <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/>
                </svg>
            </button>
        </div>
        <div class="modal-body">
            <textarea id="imageDescription" placeholder="{% trans 'Enter image description...' %}"></textarea>
        </div>
        <div class="modal-footer">
            <button class="modal-button cancel-button" onclick="closeDescriptionModal()">{% trans "Cancel" %}</button>
            <button class="modal-button save-button" onclick="saveImageDescription()">{% trans "Save" %}</button>
        </div>
    </div>
</div>

{% endblock %}

{% block extra_js %}
<!-- Dropzone (CDN — page-specific, benefits from edge proximity) -->
<script src="https://cdn.jsdelivr.net/npm/dropzone@6.0.0-beta.2/dist/dropzone.min.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function() {
    const colors = ['blue', 'green', 'yellow', 'red', 'indigo', 'purple', 'pink'];
    document.querySelectorAll('.tag-item').forEach(tag => {
        const randomColor = colors[Math.floor(Math.random() * colors.length)];
        tag.className = `tag-item inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-${randomColor}-50 text-${randomColor}-700 hover:bg-${randomColor}-100`;
    });
});

Dropzone.autoDiscover = false;

const dropzone = new Dropzone("#uploadForm", {
    url: `/api/collections/{{ collection.pk }}/upload_images`,
    headers: {
        'X-CSRFToken': getCookie('csrftoken')
    },
    paramName: "file",
    acceptedFiles: 'image/*',
    parallelUploads: 5,
    maxFilesize: 10,
    uploadMultiple: false,  // Process one file at a time
    autoProcessQueue: true,
    dictDefaultMessage: `
        <div class="text-center">
            <svg class="mx-auto h-12 w-12 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                      d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-8l-4-4m0 0L8 8m4-4v12"/>
            </svg>
            <p class="mt-1 text-sm text-gray-600">
                {% trans "Drag and drop images here, or click to select files" %}
            </p>
        </div>
    `,
    init: function() {
        let totalFiles = 0;
        let completedFiles = 0;

        this.on("addedfile", function(file) {
            totalFiles++;
        });

        this.on("success", function(file, response) {
            completedFiles++;
            file.previewElement.classList.add('dz-success');
        });

        this.on("error", function(file, errorMessage) {
            console.error(`Upload error for ${file.name}:`, errorMessage);
            completedFiles++;
            file.previewElement.classList.add('dz-error');
            alert(typeof errorMessage === 'string' ? errorMessage : errorMessage.error || 'Upload failed');
        });

        this.on("queuecomplete", function() {
            if (completedFiles === totalFiles) {
                setTimeout(() => {
                    location.reload();
                }, 1000);
            }
        });

        // Reset counters when queue is cleared
        this.on("reset", function() {
            totalFiles = 0;
            completedFiles = 0;
        });
    }
});

function deleteImage(imageId) {
    if (confirm('{% trans "Are you sure you want to delete this image?" %}')) {
        fetch(`/api/images/${imageId}`, {
            method: 'DELETE',
            headers: {
                'X-CSRFToken': getCookie('csrftoken')
            }
        })
        .then(response => {
            if (!response.ok) {
                throw new Error('Network response was not ok');
            }
            document.getElementById(`image-${imageId}`).remove();
        })
        .catch(error => {
            console.error('Error:', error);
            alert('Failed to delete image');
        });
    }
}

function deleteCollection(collectionId) {
    if (confirm('{% trans "Are you sure you want to delete this collection? All images will be permanently deleted." %}')) {
        fetch(`/api/collections/${collectionId}`, {
            method: 'DELETE',
            headers: {
                'X-CSRFToken': getCookie('csrftoken')
            }
        })
        .then(response => {
            if (!response.ok) {
                throw new Error('Network response was not ok');
            }
            window.location.href = '{% url "collection-list" %}';
        })
        .catch(error => {
            console.error('Error:', error);
            alert('Failed to delete collection');
        });
    }
}

let currentImageId = null;

function editDescription(imageId, description) {
    currentImageId = imageId;
    const modal = document.getElementById('descriptionModal');
    const textarea = document.getElementById('imageDescription');
    textarea.value = description;
    modal.style.display = 'flex';
}

function closeDescriptionModal() {
    const modal = document.getElementById('descriptionModal');
    modal.style.display = 'none';
    currentImageId = null;
}

async function saveImageDescription() {
    if (!currentImageId) return;

    const description = document.getElementById('imageDescription').value;

    try {
        const response = await fetch(`/api/images/${currentImageId}/update-description`, {
            method: 'PATCH',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRFToken': document.querySelector('[name=csrfmiddlewaretoken]').value
            },
            body: JSON.stringify({ description: description })
        });

        if (response.ok) {
            const data = await response.json();
            closeDescriptionModal();
        } else {
            alert('Failed to update description. Please try again.');
        }
    } catch (error) {
        console.error('Error updating description:', error);
        alert('Failed to update description. Please try again.');
    }
}

// Close modal when clicking outside
document.getElementById('descriptionModal').addEventListener('click', function(e) {
    if (e.target === this) {
        closeDescriptionModal();
    }
});

// Prevent modal close when clicking modal content
document.querySelector('.modal-content').addEventListener('click', function(e) {
    e.stopPropagation();
});
</script>
{% endblock %}
