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

{% block extra_css %}
<style>
  [x-cloak] { display: none !important; }

  /* ============================================================
     Apple-inspired design system — Collection detail
     ============================================================ */
  :root {
    --apple-bg: #f5f5f7;
    --apple-text: #1d1d1f;
    --apple-gray: #6e6e73;
    --apple-blue: #0071e3;
    --apple-blue-hover: #0077ed;
    --apple-red: #ff3b30;
    --apple-green: #1e7b34;
    --apple-separator: rgba(0, 0, 0, 0.06);
    --apple-ease: cubic-bezier(0.28, 0.11, 0.32, 1);
    --apple-radius-lg: 28px;
    --apple-radius-md: 22px;
    --apple-shadow-card: 0 4px 24px rgba(0, 0, 0, 0.05);
    --apple-shadow-lift: 0 18px 44px rgba(0, 0, 0, 0.10);
  }

  body {
    background-color: var(--apple-bg) !important;
    font-family: -apple-system, BlinkMacSystemFont, "SF Pro Display", "SF Pro Text",
      "Helvetica Neue", "Segoe UI", Roboto, Arial, sans-serif;
    color: var(--apple-text);
    -webkit-font-smoothing: antialiased;
    text-rendering: optimizeLegibility;
  }

  .apple-wrap { max-width: 76rem; margin: 0 auto; padding: 0 1rem; }

  /* ---------- Back link ---------- */
  .back-link {
    display: inline-flex; align-items: center; gap: 0.35rem;
    margin-top: 1.2rem; padding: 0.45rem 0.9rem 0.45rem 0.55rem;
    border-radius: 980px; color: var(--apple-blue);
    font-size: 0.88rem; font-weight: 600; text-decoration: none;
    transition: background 0.25s ease;
  }
  .back-link:hover { background: rgba(0, 113, 227, 0.08); }
  .back-link svg { width: 1rem; height: 1rem; }

  /* ---------- Header ---------- */
  .detail-header {
    display: flex; flex-wrap: wrap; align-items: flex-end; justify-content: space-between;
    gap: 1.1rem; padding: 1.2rem 0.25rem 1.5rem;
  }
  .detail-title-group { min-width: 0; flex: 1 1 18rem; }
  .detail-title {
    font-size: clamp(1.7rem, 4vw, 2.4rem); font-weight: 700; letter-spacing: -0.028em;
    margin: 0 0 0.35rem; word-break: break-word;
  }
  .detail-meta { display: flex; flex-wrap: wrap; align-items: center; gap: 0.45rem; font-size: 0.88rem; color: var(--apple-gray); }
  .detail-meta .sep { color: #c7c7cc; }
  .detail-desc { margin: 0.7rem 0 0; font-size: 0.95rem; color: var(--apple-gray); line-height: 1.55; max-width: 46rem; }
  .tag-chips { display: flex; flex-wrap: wrap; gap: 0.4rem; margin-top: 0.8rem; }
  .tag-chip {
    display: inline-flex; align-items: center; padding: 0.28rem 0.75rem;
    border-radius: 980px; font-size: 0.76rem; font-weight: 600; text-decoration: none;
    background: rgba(0, 113, 227, 0.10); color: var(--apple-blue);
    transition: background 0.25s ease;
  }
  .tag-chip:hover { background: rgba(0, 113, 227, 0.18); }

  /* ---------- Buttons ---------- */
  .apple-btn {
    display: inline-flex; align-items: center; justify-content: center; gap: 0.45rem;
    min-height: 44px; padding: 0.6rem 1.35rem; border-radius: 980px;
    font-weight: 600; font-size: 0.93rem; border: none; cursor: pointer; text-decoration: none;
    transition: background 0.3s var(--apple-ease), transform 0.3s var(--apple-ease), box-shadow 0.3s var(--apple-ease);
  }
  .apple-btn:active { transform: scale(0.97); }
  .apple-btn-primary { background: var(--apple-blue); color: #fff; box-shadow: 0 6px 18px rgba(0, 113, 227, 0.28); }
  .apple-btn-primary:hover { background: var(--apple-blue-hover); color: #fff; }
  .apple-btn-secondary { background: #fff; color: var(--apple-text); border: 1px solid rgba(0, 0, 0, 0.10); }
  .apple-btn-secondary:hover { background: #ececef; }
  .apple-btn-danger { background: var(--apple-red); color: #fff; box-shadow: 0 6px 18px rgba(255, 59, 48, 0.25); }
  .apple-btn-danger:hover { background: #d63027; }
  .apple-btn svg { width: 1.05rem; height: 1.05rem; }

  /* ---------- Image grid ---------- */
  .image-grid {
    display: grid; gap: 0.9rem;
    grid-template-columns: repeat(2, 1fr);
  }
  @media (min-width: 640px) {
    .image-grid { grid-template-columns: repeat(3, 1fr); gap: 1.1rem; }
  }
  @media (min-width: 1024px) {
    .image-grid { grid-template-columns: repeat(4, 1fr); }
  }
  @media (min-width: 1536px) {
    .image-grid { grid-template-columns: repeat(5, 1fr); }
  }

  .image-tile {
    position: relative; aspect-ratio: 1; overflow: hidden;
    background: #fff; border-radius: var(--apple-radius-md);
    border: 1px solid rgba(0, 0, 0, 0.04); box-shadow: var(--apple-shadow-card);
    cursor: zoom-in;
    transition: transform 0.4s var(--apple-ease), box-shadow 0.4s var(--apple-ease);
  }
  .image-tile:hover { transform: translateY(-3px); box-shadow: var(--apple-shadow-lift); }
  .image-tile img {
    width: 100%; height: 100%; object-fit: cover;
    transition: transform 0.6s var(--apple-ease);
  }
  .image-tile:hover img { transform: scale(1.05); }
  .image-tile::after {
    content: ''; position: absolute; inset: 0;
    background: linear-gradient(to top, rgba(0,0,0,0.35), transparent 40%);
    opacity: 0; transition: opacity 0.35s ease; pointer-events: none;
  }
  .image-tile:hover::after { opacity: 1; }

  .tile-actions {
    position: absolute; right: 0.55rem; bottom: 0.55rem; left: 0.55rem; z-index: 2;
    display: flex; justify-content: flex-end; gap: 0.35rem;
    opacity: 1;
    transition: opacity 0.3s ease;
  }
  .tile-btn {
    display: inline-flex; align-items: center; justify-content: center;
    width: 34px; height: 34px; border-radius: 50%;
    background: rgba(255, 255, 255, 0.94); backdrop-filter: blur(8px);
    color: #3a3a3c; border: none; cursor: pointer; text-decoration: none;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.15);
    transition: background 0.25s ease, color 0.25s ease, transform 0.25s ease;
  }
  .tile-btn:active { transform: scale(0.92); }
  .tile-btn.blue:hover { background: var(--apple-blue); color: #fff; }
  .tile-btn.red:hover { background: var(--apple-red); color: #fff; }
  .tile-btn svg { width: 1rem; height: 1rem; }

  @media (min-width: 640px) {
    .tile-actions { opacity: 0; }
    .image-tile:hover .tile-actions, .image-tile:focus-within .tile-actions { opacity: 1; }
  }

  /* ---------- Empty state ---------- */
  .empty-state {
    grid-column: 1 / -1;
    display: flex; flex-direction: column; align-items: center; justify-content: center;
    padding: 4rem 1.5rem; text-align: center;
    background: #fff; border-radius: var(--apple-radius-lg);
    border: 1px dashed rgba(0, 0, 0, 0.14);
  }
  .empty-state svg { width: 3.4rem; height: 3.4rem; color: #c7c7cc; }
  .empty-title { font-size: 1.15rem; font-weight: 700; margin: 1rem 0 0.25rem; }
  .empty-sub { font-size: 0.9rem; color: var(--apple-gray); margin: 0 0 1.4rem; }

  /* ---------- Lightbox ---------- */
  .lightbox {
    position: fixed; inset: 0; z-index: 90;
    display: none; align-items: center; justify-content: center;
    background: rgba(0, 0, 0, 0.92); backdrop-filter: blur(14px);
    -webkit-tap-highlight-color: transparent;
  }
  .lightbox.open { display: flex; animation: lb-fade 0.3s var(--apple-ease); }
  @keyframes lb-fade { from { opacity: 0; } to { opacity: 1; } }
  .lb-img-wrap {
    display: flex; align-items: center; justify-content: center;
    width: 100%; height: 100%; padding: 2.2rem 0.8rem 4.6rem;
  }
  .lb-img-wrap img {
    max-width: 100%; max-height: 100%; object-fit: contain;
    border-radius: 10px; box-shadow: 0 24px 80px rgba(0, 0, 0, 0.5);
    animation: lb-zoom 0.35s var(--apple-ease);
  }
  @keyframes lb-zoom { from { transform: scale(0.96); opacity: 0.4; } to { transform: scale(1); opacity: 1; } }
  .lb-topbar {
    position: absolute; top: 0; left: 0; right: 0;
    display: flex; align-items: center; justify-content: space-between;
    padding: 0.8rem 1rem; z-index: 2;
    background: linear-gradient(to bottom, rgba(0,0,0,0.5), transparent);
  }
  .lb-counter { color: rgba(255,255,255,0.85); font-size: 0.85rem; font-weight: 600; }
  .lb-close {
    display: inline-flex; align-items: center; justify-content: center;
    width: 40px; height: 40px; border-radius: 50%;
    background: rgba(255,255,255,0.14); border: none; color: #fff; cursor: pointer;
    transition: background 0.25s ease, transform 0.25s ease;
  }
  .lb-close:hover { background: rgba(255,255,255,0.28); transform: rotate(90deg); }
  .lb-close svg { width: 1.2rem; height: 1.2rem; }
  .lb-nav {
    position: absolute; top: 50%; transform: translateY(-50%);
    display: inline-flex; align-items: center; justify-content: center;
    width: 46px; height: 46px; border-radius: 50%;
    background: rgba(255,255,255,0.12); border: none; color: #fff; cursor: pointer;
    transition: background 0.25s ease, transform 0.25s ease;
    z-index: 2;
  }
  .lb-nav:hover { background: rgba(255,255,255,0.24); }
  .lb-nav.prev { left: 0.8rem; }
  .lb-nav.next { right: 0.8rem; }
  .lb-nav svg { width: 1.4rem; height: 1.4rem; }
  @media (max-width: 640px) {
    .lb-nav { width: 40px; height: 40px; }
    .lb-nav.prev { left: 0.4rem; }
    .lb-nav.next { right: 0.4rem; }
  }
  .lb-bottom {
    position: absolute; bottom: 0; left: 0; right: 0;
    display: flex; align-items: center; justify-content: center; gap: 0.7rem;
    padding: 0.9rem 1rem calc(0.9rem + env(safe-area-inset-bottom));
    background: linear-gradient(to top, rgba(0,0,0,0.6), transparent);
    z-index: 2;
  }
  .lb-title {
    color: #fff; font-size: 0.9rem; font-weight: 600;
    max-width: 45%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
  }
  .lb-desc {
    color: rgba(255,255,255,0.72); font-size: 0.82rem; font-weight: 500;
    max-width: 30%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
    cursor: pointer; text-decoration: underline dotted rgba(255,255,255,0.5);
  }
  .lb-btn {
    display: inline-flex; align-items: center; justify-content: center; gap: 0.35rem;
    min-height: 38px; padding: 0.4rem 1rem; border-radius: 980px;
    font-size: 0.82rem; font-weight: 600; border: none; cursor: pointer; text-decoration: none;
    background: rgba(255,255,255,0.16); color: #fff;
    transition: background 0.25s ease;
  }
  .lb-btn:hover { background: rgba(255,255,255,0.28); }
  .lb-btn.red:hover { background: var(--apple-red); }
  .lb-btn svg { width: 0.95rem; height: 0.95rem; }

  /* ---------- Modal (description edit) ---------- */
  .modal-mask {
    position: fixed; inset: 0; z-index: 100;
    display: none; align-items: center; justify-content: center;
    background: rgba(0, 0, 0, 0.45); backdrop-filter: blur(6px);
    padding: 1.2rem;
  }
  .modal-mask.open { display: flex; animation: lb-fade 0.25s var(--apple-ease); }
  .modal-card {
    background: #fff; border-radius: var(--apple-radius-lg);
    box-shadow: 0 30px 80px rgba(0, 0, 0, 0.28);
    width: 100%; max-width: 480px; overflow: hidden;
    animation: lb-zoom 0.3s var(--apple-ease);
  }
  .modal-head {
    display: flex; align-items: center; justify-content: space-between;
    padding: 1.2rem 1.4rem 0.4rem;
  }
  .modal-title { font-size: 1.1rem; font-weight: 700; margin: 0; }
  .modal-x {
    display: inline-flex; align-items: center; justify-content: center;
    width: 34px; height: 34px; border-radius: 50%; border: none; cursor: pointer;
    background: rgba(0,0,0,0.05); color: var(--apple-gray);
    transition: background 0.25s ease;
  }
  .modal-x:hover { background: rgba(0,0,0,0.1); }
  .modal-x svg { width: 1.05rem; height: 1.05rem; }
  .modal-body { padding: 0.8rem 1.4rem 1.4rem; }
  .modal-body textarea {
    width: 100%; min-height: 110px; resize: vertical;
    padding: 0.8rem 1rem; border-radius: 14px;
    border: 1px solid rgba(0, 0, 0, 0.12); font-size: 0.95rem; font-family: inherit;
    outline: none; transition: border-color 0.25s ease, box-shadow 0.25s ease;
  }
  .modal-body textarea:focus { border-color: var(--apple-blue); box-shadow: 0 0 0 4px rgba(0, 113, 227, 0.14); }
  .modal-foot { display: flex; justify-content: flex-end; gap: 0.6rem; padding: 0 1.4rem 1.4rem; }
  .modal-btn {
    display: inline-flex; align-items: center; justify-content: center;
    min-height: 42px; padding: 0.5rem 1.3rem; border-radius: 980px;
    font-size: 0.9rem; font-weight: 600; border: none; cursor: pointer;
    transition: background 0.25s ease, transform 0.25s ease;
  }
  .modal-btn:active { transform: scale(0.97); }
  .modal-btn-cancel { background: rgba(0,0,0,0.06); color: var(--apple-text); }
  .modal-btn-cancel:hover { background: rgba(0,0,0,0.1); }
  .modal-btn-save { background: var(--apple-blue); color: #fff; }
  .modal-btn-save:hover { background: var(--apple-blue-hover); }

  /* Toast */
  .toast {
    position: fixed; left: 50%; bottom: 2.2rem; transform: translateX(-50%) translateY(20px);
    z-index: 120; background: rgba(29, 29, 31, 0.92); color: #fff;
    padding: 0.7rem 1.4rem; border-radius: 980px; font-size: 0.88rem; font-weight: 600;
    opacity: 0; pointer-events: none; transition: opacity 0.35s ease, transform 0.35s ease;
    box-shadow: 0 12px 40px rgba(0,0,0,0.3); backdrop-filter: blur(10px);
    max-width: 90vw; text-align: center;
  }
  .toast.show { opacity: 1; transform: translateX(-50%) translateY(0); }
</style>
{% endblock %}

{% block content %}
<div class="apple-wrap">
    <!-- Back -->
    <a href="{% url 'collection-list' %}" class="back-link">
        <svg fill="none" stroke="currentColor" viewBox="0 0 24 24" stroke-width="2.2">
            <path stroke-linecap="round" stroke-linejoin="round" d="M10 19l-7-7m0 0l7-7m-7 7h18"/>
        </svg>
        {% trans "Collections" %}
    </a>

    <!-- Header -->
    <div class="detail-header">
        <div class="detail-title-group">
            <h1 class="detail-title">{{ collection.name }}</h1>
            <div class="detail-meta">
                <span>{{ collection.images.count }} {% trans "images" %}</span>
                <span class="sep">·</span>
                <span>{{ collection.created_at|date:"Y-m-d" }}</span>
                {% if collection.updated_at != collection.created_at %}
                    <span class="sep">·</span>
                    <span>{% trans "Updated" %} {{ collection.updated_at|date:"Y-m-d" }}</span>
                {% endif %}
            </div>
            {% if collection.description %}
                <p class="detail-desc">{{ collection.description }}</p>
            {% endif %}
            {% if collection.tags.exists %}
                <div class="tag-chips">
                    {% for tag in collection.tags.all %}
                        <a href="{% url 'tag-detail' tag.slug %}" class="tag-chip">{{ tag.name }}</a>
                    {% endfor %}
                </div>
            {% endif %}
        </div>
        <div class="flex flex-wrap gap-2" style="align-items:center;">
            <button type="button" class="apple-btn apple-btn-primary" onclick="document.getElementById('fileInput').click()">
                <svg fill="none" stroke="currentColor" viewBox="0 0 24 24" stroke-width="2">
                    <path stroke-linecap="round" stroke-linejoin="round" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-8l-4-4m0 0L8 8m4-4v12"/>
                </svg>
                {% trans "Upload" %}
            </button>
            <a href="{% url 'collection-slideshow' collection.pk %}" class="apple-btn apple-btn-secondary">
                <svg fill="none" stroke="currentColor" viewBox="0 0 24 24" stroke-width="2">
                    <path stroke-linecap="round" stroke-linejoin="round" d="M5 3l14 9-14 9V3z"/>
                </svg>
                {% trans "Slideshow" %}
            </a>
            <a href="{% url 'collection-update' collection.pk %}" class="apple-btn apple-btn-secondary">
                <svg fill="none" stroke="currentColor" viewBox="0 0 24 24" stroke-width="2">
                    <path stroke-linecap="round" stroke-linejoin="round" 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>
                {% trans "Edit" %}
            </a>
            <button type="button" class="apple-btn apple-btn-danger" onclick="deleteCollection('{{ collection.pk }}')">
                <svg fill="none" stroke="currentColor" viewBox="0 0 24 24" stroke-width="2">
                    <path stroke-linecap="round" stroke-linejoin="round" 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>
                {% trans "Delete" %}
            </button>
        </div>
    </div>

    <!-- Upload zone -->
    <input type="file" id="fileInput" multiple accept="image/*" style="display:none;">

    <!-- Images grid -->
    <div class="image-grid" id="imagesGrid">
        {% for image in collection.images.all %}
            <div class="image-tile" id="image-{{ image.id }}">
                <img src="{{ image.get_thumbnail_url }}" alt="{{ image.title }}" loading="lazy" decoding="async"
                     onclick="openLightbox('{{ image.id }}')">
                <div class="tile-actions">
                    <a href="{{ image.get_url }}" target="_blank" rel="noopener"
                       class="tile-btn" title="{% trans 'View Full Size' %}" aria-label="{% trans 'View Full Size' %}">
                        <svg fill="none" stroke="currentColor" viewBox="0 0 24 24" stroke-width="2">
                            <path stroke-linecap="round" stroke-linejoin="round" d="M21 21l-5.197-5.197m0 0A7.5 7.5 0 105.196 5.196a7.5 7.5 0 0010.607 10.607zM10.5 7.5v6m3-3h-6"/>
                        </svg>
                    </a>
                    <button type="button" class="tile-btn blue" onclick="event.stopPropagation(); editDescription('{{ image.id }}')" title="{% trans 'Edit Description' %}" aria-label="{% trans 'Edit Description' %}">
                        <svg fill="none" stroke="currentColor" viewBox="0 0 24 24" stroke-width="2">
                            <path stroke-linecap="round" stroke-linejoin="round" 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 type="button" class="tile-btn red" onclick="event.stopPropagation(); deleteImage('{{ image.id }}')" title="{% trans 'Delete Image' %}" aria-label="{% trans 'Delete Image' %}">
                        <svg fill="none" stroke="currentColor" viewBox="0 0 24 24" stroke-width="2">
                            <path stroke-linecap="round" stroke-linejoin="round" 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="empty-state">
                <svg fill="none" stroke="currentColor" viewBox="0 0 24 24" stroke-width="1.5">
                    <path stroke-linecap="round" stroke-linejoin="round" d="M2.25 15.75l5.159-5.159a2.25 2.25 0 013.182 0l5.159 5.159m-1.5-1.5l1.409-1.409a2.25 2.25 0 013.182 0l2.909 2.909M3.75 21h16.5A2.25 2.25 0 0022.5 18.75V5.25A2.25 2.25 0 0020.25 3H3.75A2.25 2.25 0 001.5 5.25v13.5A2.25 2.25 0 003.75 21zm10.5-11.25h.008v.008h-.008v-.008z"/>
                </svg>
                <h3 class="empty-title">{% trans "No images yet" %}</h3>
                <p class="empty-sub">{% trans "Drop some images above to start this collection." %}</p>
                <button type="button" class="apple-btn apple-btn-primary" onclick="document.getElementById('fileInput').click()">
                    <svg fill="none" stroke="currentColor" viewBox="0 0 24 24" stroke-width="2">
                        <path stroke-linecap="round" stroke-linejoin="round" d="M12 4v16m8-8H4"/>
                    </svg>
                    {% trans "Upload Images" %}
                </button>
            </div>
        {% endfor %}
    </div>
</div>

<!-- Lightbox -->
<div class="lightbox" id="lightbox">
    <div class="lb-topbar">
        <span class="lb-counter" id="lbCounter"></span>
        <button type="button" class="lb-close" onclick="closeLightbox()" aria-label="{% trans 'Close' %}">
            <svg fill="none" stroke="currentColor" viewBox="0 0 24 24" stroke-width="2">
                <path stroke-linecap="round" stroke-linejoin="round" d="M6 18L18 6M6 6l12 12"/>
            </svg>
        </button>
    </div>
    <button type="button" class="lb-nav prev" onclick="prevImage()" aria-label="{% trans 'Previous' %}">
        <svg fill="none" stroke="currentColor" viewBox="0 0 24 24" stroke-width="2.4">
            <path stroke-linecap="round" stroke-linejoin="round" d="M15 19l-7-7 7-7"/>
        </svg>
    </button>
    <div class="lb-img-wrap"><img id="lbImg" src="" alt=""></div>
    <button type="button" class="lb-nav next" onclick="nextImage()" aria-label="{% trans 'Next' %}">
        <svg fill="none" stroke="currentColor" viewBox="0 0 24 24" stroke-width="2.4">
            <path stroke-linecap="round" stroke-linejoin="round" d="M9 5l7 7-7 7"/>
        </svg>
    </button>
    <div class="lb-bottom">
        <span class="lb-title" id="lbTitle"></span>
        <span class="lb-desc" id="lbDesc" onclick="editDescription(currentImageId, currentImageDesc)"></span>
        <a class="lb-btn" id="lbOpen" href="#" target="_blank" rel="noopener">
            <svg fill="none" stroke="currentColor" viewBox="0 0 24 24" stroke-width="2">
                <path stroke-linecap="round" stroke-linejoin="round" d="M21 21l-5.197-5.197m0 0A7.5 7.5 0 105.196 5.196a7.5 7.5 0 0010.607 10.607zM10.5 7.5v6m3-3h-6"/>
            </svg>
            {% trans "Full size" %}
        </a>
        <button type="button" class="lb-btn red" onclick="deleteImageFromLightbox()">
            <svg fill="none" stroke="currentColor" viewBox="0 0 24 24" stroke-width="2">
                <path stroke-linecap="round" stroke-linejoin="round" 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>
            {% trans "Delete" %}
        </button>
    </div>
</div>

<!-- Description modal -->
<div class="modal-mask" id="descriptionModal">
    <div class="modal-card">
        <div class="modal-head">
            <h3 class="modal-title">{% trans "Edit Description" %}</h3>
            <button type="button" class="modal-x" onclick="closeDescriptionModal()">
                <svg fill="none" stroke="currentColor" viewBox="0 0 24 24" stroke-width="2">
                    <path stroke-linecap="round" stroke-linejoin="round" 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-foot">
            <button type="button" class="modal-btn modal-btn-cancel" onclick="closeDescriptionModal()">{% trans "Cancel" %}</button>
            <button type="button" class="modal-btn modal-btn-save" onclick="saveImageDescription()">{% trans "Save" %}</button>
        </div>
    </div>
</div>

<div class="toast" id="toast"></div>

<!-- Image data for lightbox (server-rendered, valid JSON via json_script) -->
{{ image_data|json_script:"image-data" }}
{% endblock %}

{% block extra_js %}
<script>
(function() {
    'use strict';

    function getCookie(name) {
        let cookieValue = null;
        if (document.cookie && document.cookie !== '') {
            const cookies = document.cookie.split(';');
            for (let i = 0; i < cookies.length; i++) {
                const cookie = cookies[i].trim();
                if (cookie.substring(0, name.length + 1) === (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }

    function showToast(msg) {
        const t = document.getElementById('toast');
        t.textContent = msg;
        t.classList.add('show');
        clearTimeout(showToast._timer);
        showToast._timer = setTimeout(() => t.classList.remove('show'), 2600);
    }

    /* ── Upload (via header Upload button → hidden file input) ── */
    const fileInput = document.getElementById('fileInput');

    fileInput.addEventListener('change', () => { if (fileInput.files.length) uploadFiles(fileInput.files); });

    function uploadFiles(fileList) {
        const files = Array.from(fileList).filter(f => f.type.startsWith('image/') || /\.(jpe?g|png|webp|gif|heic|heif|avif)$/i.test(f.name));
        if (!files.length) {
            showToast('{% trans "Only image files are allowed" %}');
            return;
        }
        const total = files.length;
        let done = 0, failed = 0;
        showToast('0 / ' + total + ' {% trans "uploading…" %}');

        files.forEach(file => {
            const fd = new FormData();
            fd.append('file', file);
            const xhr = new XMLHttpRequest();
            xhr.open('POST', '/api/collections/{{ collection.pk }}/upload_images');
            xhr.setRequestHeader('X-CSRFToken', getCookie('csrftoken'));
            xhr.onload = () => {
                done++;
                if (xhr.status >= 200 && xhr.status < 300) {
                    showToast(done + ' / ' + total + ' {% trans "uploaded" %}');
                } else {
                    failed++;
                    showToast(done + ' / ' + total + ' (failed: ' + failed + ')');
                }
                if (done === total) {
                    if (!failed) showToast('{% trans "All images uploaded ✓" %}');
                    else showToast(done - failed + ' {% trans "uploaded" %}, ' + failed + ' {% trans "failed" %}');
                    setTimeout(() => location.reload(), 900);
                }
            };
            xhr.onerror = () => {
                done++; failed++;
                showToast(done + ' / ' + total + ' (failed: ' + failed + ')');
                if (done === total) setTimeout(() => location.reload(), 900);
            };
            xhr.send(fd);
        });
    }

    /* ── Lightbox ── */
    let images = [];
    try {
        images = JSON.parse(document.getElementById('image-data').textContent);
    } catch (e) { images = []; }
    let currentIndex = 0;
    let currentImageId = null;
    let currentImageDesc = '';

    window.openLightbox = function(id) {
        currentIndex = images.findIndex(i => i.id === id);
        if (currentIndex < 0) currentIndex = 0;
        renderLightbox();
        document.getElementById('lightbox').classList.add('open');
        document.body.style.overflow = 'hidden';
    };
    window.closeLightbox = function() {
        document.getElementById('lightbox').classList.remove('open');
        document.body.style.overflow = '';
    };
    window.prevImage = function() {
        if (images.length < 2) return;
        currentIndex = (currentIndex - 1 + images.length) % images.length;
        renderLightbox();
    };
    window.nextImage = function() {
        if (images.length < 2) return;
        currentIndex = (currentIndex + 1) % images.length;
        renderLightbox();
    };

    function renderLightbox() {
        const img = images[currentIndex];
        if (!img) return;
        currentImageId = img.id;
        currentImageDesc = img.description || '';
        document.getElementById('lbImg').src = img.url;
        document.getElementById('lbImg').alt = img.title;
        document.getElementById('lbCounter').textContent = (currentIndex + 1) + ' / ' + images.length;
        document.getElementById('lbTitle').textContent = img.title;
        const descEl = document.getElementById('lbDesc');
        descEl.textContent = currentImageDesc || '{% trans "Add description" %}';
        descEl.style.opacity = currentImageDesc ? '1' : '0.5';
        document.getElementById('lbOpen').href = img.url;
    }

    /* Swipe support (mobile) */
    let touchX = null;
    const lb = document.getElementById('lightbox');
    lb.addEventListener('touchstart', e => { touchX = e.touches[0].clientX; }, { passive: true });
    lb.addEventListener('touchend', e => {
        if (touchX === null) return;
        const dx = e.changedTouches[0].clientX - touchX;
        if (Math.abs(dx) > 48) { dx < 0 ? window.nextImage() : window.prevImage(); }
        touchX = null;
    }, { passive: true });

    document.addEventListener('keydown', e => {
        if (!lb.classList.contains('open')) return;
        if (e.key === 'Escape') window.closeLightbox();
        if (e.key === 'ArrowLeft') window.prevImage();
        if (e.key === 'ArrowRight') window.nextImage();
    });

    /* ── Description modal ── */
    window.editDescription = function(id) {
        const hit = images.find(i => i.id === id);
        currentImageId = id;
        currentImageDesc = (hit && hit.description) || '';
        document.getElementById('imageDescription').value = currentImageDesc;
        document.getElementById('descriptionModal').classList.add('open');
    };
    window.closeDescriptionModal = function() {
        document.getElementById('descriptionModal').classList.remove('open');
    };
    window.saveImageDescription = async function() {
        if (!currentImageId) return;
        const description = document.getElementById('imageDescription').value;
        try {
            const resp = await fetch('/api/images/' + currentImageId + '/update-description', {
                method: 'PATCH',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRFToken': getCookie('csrftoken')
                },
                body: JSON.stringify({ description: description })
            });
            if (resp.ok) {
                window.closeDescriptionModal();
                // Update the in-memory lightbox data
                const hit = images.find(i => i.id === currentImageId);
                if (hit) hit.description = description;
                currentImageDesc = description;
                const descEl = document.getElementById('lbDesc');
                descEl.textContent = description || '{% trans "Add description" %}';
                descEl.style.opacity = description ? '1' : '0.5';
                showToast('{% trans "Description saved" %}');
            } else {
                showToast('{% trans "Failed to update description" %}');
            }
        } catch (err) {
            console.error('Error updating description:', err);
            showToast('{% trans "Failed to update description" %}');
        }
    };
    document.getElementById('descriptionModal').addEventListener('click', function(e) {
        if (e.target === this) window.closeDescriptionModal();
    });

    /* ── Delete ── */
    window.deleteImage = function(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');
                const el = document.getElementById('image-' + imageId);
                if (el) el.remove();
                images = images.filter(i => i.id !== imageId);
                showToast('{% trans "Image deleted" %}');
            })
            .catch(error => {
                console.error('Error:', error);
                showToast('{% trans "Failed to delete image" %}');
            });
        }
    };
    window.deleteImageFromLightbox = function() {
        const id = currentImageId;
        if (confirm('{% trans "Are you sure you want to delete this image?" %}')) {
            fetch('/api/images/' + id, {
                method: 'DELETE',
                headers: { 'X-CSRFToken': getCookie('csrftoken') }
            })
            .then(response => {
                if (!response.ok) throw new Error('Network response was not ok');
                const el = document.getElementById('image-' + id);
                if (el) el.remove();
                images = images.filter(i => i.id !== id);
                if (!images.length) {
                    window.closeLightbox();
                    setTimeout(() => location.reload(), 300);
                } else {
                    currentIndex = Math.min(currentIndex, images.length - 1);
                    renderLightbox();
                }
                showToast('{% trans "Image deleted" %}');
            })
            .catch(error => {
                console.error('Error:', error);
                showToast('{% trans "Failed to delete image" %}');
            });
        }
    };
    window.deleteCollection = function(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);
                showToast('{% trans "Failed to delete collection" %}');
            });
        }
    };
})();
</script>
{% endblock %}
