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

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

  /* ============================================================
     Apple-inspired design system — Files page
     Mirrors the home page tokens & components so the two pages
     share one visual language.
     ============================================================ */
  :root {
    --apple-bg: #f5f5f7;
    --apple-text: #1d1d1f;
    --apple-gray: #6e6e73;
    --apple-blue: #0071e3;
    --apple-blue-hover: #0077ed;
    --apple-red: #ff3b30;
    --apple-green: #1e7b34;
    --apple-yellow: #ff9f0a;
    --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: 72rem; margin: 0 auto; padding: 0 1rem; }

  /* ---------- Library header (mirrors home .library-header) ---------- */
  .library-header {
    display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between;
    gap: 1rem; padding: 1.7rem 1.8rem 1.25rem;
  }
  .library-title-group { display: flex; flex-direction: column; gap: 0.15rem; }
  .section-title { font-size: clamp(1.45rem, 3vw, 1.8rem); font-weight: 700; letter-spacing: -0.022em; margin: 0; }
  .library-count { font-size: 0.88rem; color: var(--apple-gray); margin: 0; }
  .library-actions { display: flex; flex-wrap: wrap; align-items: center; gap: 0.75rem; }

  /* ---------- Buttons ---------- */
  .apple-btn {
    display: inline-flex; align-items: center; justify-content: center; gap: 0.45rem;
    min-height: 44px; padding: 0.6rem 1.4rem; border-radius: 980px;
    font-weight: 600; font-size: 0.95rem; 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: var(--apple-bg); color: var(--apple-text); border: 1px solid rgba(0, 0, 0, 0.10); }
  .apple-btn-secondary:hover { background: #ececef; }

  /* ---------- Card ---------- */
  .apple-card {
    background: #fff; border-radius: var(--apple-radius-lg);
    border: 1px solid rgba(0, 0, 0, 0.04); box-shadow: var(--apple-shadow-card);
    overflow: hidden;
  }

  /* ---------- File list ---------- */
  .file-list { list-style: none; margin: 0; padding: 0; }
  .file-row {
    display: flex; align-items: flex-start; gap: 0.9rem;
    padding: 1rem 1.8rem; border-bottom: 1px solid var(--apple-separator);
    transition: background 0.25s ease;
  }
  .file-row:hover { background: rgba(0, 0, 0, 0.025); }
  .file-list > li:last-child { border-bottom: none; }

  .file-icon { flex: none; margin-top: 0.2rem; color: #8e8e93; }
  .file-icon svg { width: 1.25rem; height: 1.25rem; display: block; }

  .file-main { flex: 1 1 auto; min-width: 0; }
  .file-name {
    color: var(--apple-blue); font-weight: 600; font-size: 0.98rem; text-decoration: none;
    display: inline-block; max-width: 100%;
    overflow: hidden; text-overflow: ellipsis;
  }
  .file-name:hover { text-decoration: underline; }
  .file-meta {
    display: flex; flex-wrap: wrap; align-items: center; gap: 0.4rem;
    margin: 0.3rem 0 0; font-size: 0.8rem; color: var(--apple-gray);
  }
  .file-meta dd { margin: 0; }
  .file-meta .sep { color: #c7c7cc; }
  .file-sub {
    display: flex; flex-wrap: wrap; align-items: center; gap: 0.5rem;
    margin-top: 0.5rem;
  }

  /* ---------- Badges ---------- */
  .badge {
    display: inline-flex; align-items: center; gap: 0.35rem;
    padding: 0.26rem 0.7rem; border-radius: 980px;
    font-size: 0.76rem; font-weight: 600; border: none; cursor: pointer;
    transition: background 0.25s ease;
  }
  .badge-public { background: rgba(48, 209, 88, 0.15); color: var(--apple-green); }
  .badge-public:hover { background: rgba(48, 209, 88, 0.24); }
  .badge-private { background: rgba(0, 0, 0, 0.05); color: var(--apple-gray); }
  .badge-private:hover { background: rgba(0, 0, 0, 0.09); }

  .expiry-chip { font-size: 0.76rem; color: var(--apple-gray); cursor: pointer; }
  .expiry-chip:hover { text-decoration: underline; }
  .expiry-chip.expired { color: var(--apple-red); }

  /* ---------- Inline link ---------- */
  .apple-link {
    color: var(--apple-blue); font-weight: 500; font-size: 0.82rem;
    display: inline-flex; align-items: center; gap: 0.25rem; text-decoration: none;
    background: none; border: none; cursor: pointer; padding: 0;
  }
  .apple-link:hover { text-decoration: underline; }
  .apple-link svg { width: 0.8rem; height: 0.8rem; }

  /* ---------- Icon buttons ---------- */
  .icon-btn {
    display: inline-flex; align-items: center; justify-content: center;
    width: 40px; height: 40px; border-radius: 50%; color: #8e8e93;
    transition: background 0.25s ease, color 0.25s ease, transform 0.25s ease;
    flex: none; text-decoration: none;
  }
  .icon-btn:hover { background: rgba(0, 0, 0, 0.05); transform: translateY(-1px); }
  .icon-btn.blue:hover { color: var(--apple-blue); }
  .icon-btn.amber:hover { color: var(--apple-yellow); }
  .icon-btn.red:hover { color: var(--apple-red); }
  .icon-btn svg { width: 1.2rem; height: 1.2rem; }

  .file-actions { flex: none; display: flex; align-items: center; gap: 0.15rem; }

  /* ---------- Empty state ---------- */
  .empty-state {
    padding: 2.75rem 1.5rem; text-align: center; color: var(--apple-gray);
    display: flex; flex-direction: column; align-items: center; gap: 1rem;
  }
  .empty-state svg { width: 2.6rem; height: 2.6rem; color: #c7c7cc; }
  .empty-state p { margin: 0; }
  .empty-state .es-title { font-size: 0.95rem; font-weight: 600; }
  .empty-state .es-sub { font-size: 0.82rem; }

  /* ---------- Drag overlay ---------- */
  .drag-overlay {
    position: fixed; inset: 0; z-index: 40; pointer-events: none;
    display: flex; align-items: center; justify-content: center;
    background: rgba(0, 113, 227, 0.08);
    border: 3px dashed rgba(0, 113, 227, 0.45);
    opacity: 0; transition: opacity 0.15s ease;
  }
  .drag-overlay .drag-inner { text-align: center; padding: 0 1rem; }
  .drag-overlay svg { width: 4rem; height: 4rem; margin: 0 auto 0.75rem; color: var(--apple-blue); }
  .drag-overlay p { font-size: 1.25rem; font-weight: 600; color: var(--apple-blue); margin: 0; }

  /* ---------- Toast (frosted dark pill) ---------- */
  .apple-toast {
    position: fixed; top: 5rem; right: 1.25rem; z-index: 9999; pointer-events: none;
    display: flex; align-items: center; gap: 0.5rem;
    background: rgba(29, 29, 31, 0.86); color: #fff;
    -webkit-backdrop-filter: blur(20px) saturate(180%); backdrop-filter: blur(20px) saturate(180%);
    font-size: 0.875rem; padding: 0.625rem 1rem; border-radius: 980px;
    box-shadow: 0 18px 44px rgba(0, 0, 0, 0.30);
  }
  .apple-toast svg { width: 1rem; height: 1rem; color: #30d158; flex: none; }

  /* ---------- Upload HUD (frosted card) ---------- */
  .upload-hud {
    position: fixed; bottom: 1.25rem; right: 1.25rem; z-index: 9999;
    width: 20rem; max-width: calc(100vw - 2rem);
    background: rgba(255, 255, 255, 0.88);
    -webkit-backdrop-filter: blur(24px) saturate(180%); backdrop-filter: blur(24px) saturate(180%);
    border: 1px solid rgba(0, 0, 0, 0.06); border-radius: var(--apple-radius-md);
    box-shadow: var(--apple-shadow-lift); overflow: hidden;
  }
  .hud-header {
    display: flex; align-items: center; justify-content: space-between;
    padding: 0.85rem 1.1rem; cursor: pointer; user-select: none;
    border-bottom: 1px solid var(--apple-separator);
  }
  .hud-title { display: flex; align-items: center; gap: 0.5rem; font-size: 0.875rem; font-weight: 600; color: var(--apple-text); }
  .hud-dot { width: 0.5rem; height: 0.5rem; border-radius: 50%; flex: none; }
  .hud-dot.live { background: var(--apple-blue); animation: hud-pulse 1.2s ease-in-out infinite; }
  .hud-dot.idle { background: #c7c7cc; }
  @keyframes hud-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.4; } }
  .hud-cancel { font-size: 0.75rem; font-weight: 600; color: var(--apple-red); padding: 0.15rem 0.5rem; border-radius: 980px; background: none; border: none; cursor: pointer; }
  .hud-cancel:hover { background: rgba(255, 59, 48, 0.10); }
  .hud-chev { width: 1rem; height: 1rem; color: #8e8e93; transition: transform 0.2s ease; }

  .hud-body { max-height: 15rem; overflow-y: auto; }
  .hud-empty { padding: 1.25rem 1rem; text-align: center; font-size: 0.75rem; color: var(--apple-gray); }
  .hud-item { padding: 0.75rem 1.1rem; border-bottom: 1px solid var(--apple-separator); }
  .hud-item:last-child { border-bottom: none; }
  .hud-item-top { display: flex; align-items: center; justify-content: space-between; margin-bottom: 0.4rem; }
  .hud-item-name { font-size: 0.75rem; font-weight: 600; color: var(--apple-text); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; max-width: 11rem; }
  .hud-item-status { font-size: 0.75rem; font-weight: 600; flex: none; margin-left: 0.5rem; }
  .hud-bar { height: 0.375rem; border-radius: 980px; background: rgba(0, 0, 0, 0.06); overflow: hidden; }
  .hud-bar-fill { height: 100%; border-radius: 980px; transition: width 0.2s ease; }

  /* ---------- Modals (Apple style) ---------- */
  .apple-modal-bg {
    position: fixed; inset: 0; z-index: 9999;
    display: flex; align-items: center; justify-content: center; padding: 1rem;
    background: rgba(0, 0, 0, 0.4);
    -webkit-backdrop-filter: blur(8px); backdrop-filter: blur(8px);
  }
  .apple-modal {
    background: #fff; border-radius: var(--apple-radius-md);
    box-shadow: 0 26px 68px rgba(0, 0, 0, 0.25);
    width: 100%; max-width: 24rem; overflow: hidden;
  }
  .modal-head { display: flex; align-items: center; justify-content: space-between; padding: 1.25rem 1.5rem 0.5rem; }
  .modal-head h3 { font-size: 1.05rem; font-weight: 700; margin: 0; }
  .modal-close {
    width: 2rem; height: 2rem; border-radius: 50%; display: flex;
    align-items: center; justify-content: center; color: #8e8e93;
    background: none; border: none; cursor: pointer;
  }
  .modal-close:hover { background: rgba(0,0,0,0.05); color: var(--apple-text); }
  .modal-close svg { width: 1rem; height: 1rem; }
  .modal-body { padding: 0.5rem 1.5rem 1.5rem; }
  .modal-desc { font-size: 0.85rem; color: var(--apple-gray); margin: 0 0 1rem; }

  .apple-input {
    width: 100%; height: 2.75rem; padding: 0 0.9rem;
    border: 1px solid rgba(0, 0, 0, 0.12); border-radius: 14px;
    font-size: 0.9rem; color: var(--apple-text); background: var(--apple-bg);
    transition: border-color 0.3s ease, box-shadow 0.3s ease, background 0.3s ease;
  }
  .apple-input:focus { outline: none; background: #fff; border-color: rgba(0,113,227,0.5); box-shadow: 0 0 0 4px rgba(0,113,227,0.14); }

  .modal-footer { display: flex; align-items: center; justify-content: space-between; margin-top: 1.25rem; }
  .modal-footer .right { display: flex; gap: 0.5rem; }
  .text-link { font-size: 0.875rem; font-weight: 600; color: var(--apple-red); background: none; border: none; cursor: pointer; padding: 0; }
  .text-link:hover { text-decoration: underline; }

  /* ---------- Preview modal ---------- */
  .preview-bg {
    position: fixed; inset: 0; z-index: 50;
    display: flex; align-items: center; justify-content: center; padding: 1rem;
    background: rgba(0, 0, 0, 0.82);
    -webkit-backdrop-filter: blur(8px); backdrop-filter: blur(8px);
  }
  .preview-shell {
    position: relative; background: #fff; border-radius: var(--apple-radius-md);
    box-shadow: 0 30px 80px rgba(0, 0, 0, 0.45);
    display: flex; flex-direction: column; overflow: hidden;
    max-width: min(92vw, 1280px); max-height: 92vh; width: max-content; min-width: 300px;
  }
  .preview-head { display: flex; align-items: center; justify-content: space-between; padding: 0.85rem 1.25rem; border-bottom: 1px solid var(--apple-separator); flex: none; }
  .preview-head h3 { font-size: 0.9rem; font-weight: 600; margin: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
  .preview-stage { flex: 1 1 auto; min-height: 0; overflow: auto; display: flex; align-items: center; justify-content: center; background: var(--apple-bg); position: relative; }
  .preview-foot { display: flex; align-items: center; justify-content: space-between; padding: 0.6rem 1.25rem; border-top: 1px solid var(--apple-separator); flex: none; background: #fff; }
  .preview-foot .meta { font-size: 0.75rem; color: var(--apple-gray); display: flex; gap: 0.75rem; }
  .preview-nav {
    position: absolute; top: 50%; transform: translateY(-50%); z-index: 10;
    width: 2.5rem; height: 2.5rem; border-radius: 50%; display: flex;
    align-items: center; justify-content: center;
    background: rgba(0,0,0,0.4); color: #fff; border: none; cursor: pointer;
    transition: background 0.2s ease;
  }
  .preview-nav:hover { background: rgba(0,0,0,0.6); }
  .preview-nav svg { width: 1.25rem; height: 1.25rem; }
  .preview-fallback { text-align: center; display: flex; flex-direction: column; align-items: center; gap: 1rem; padding: 3rem 2.5rem; width: 26rem; }
  .preview-fallback svg { width: 4rem; height: 4rem; color: #c7c7cc; }
  .preview-fallback .fb-title { font-size: 1rem; font-weight: 600; color: var(--apple-text); }
  .preview-fallback .fb-sub { font-size: 0.875rem; color: var(--apple-gray); }

  /* ---------- Accessibility: visible keyboard focus ---------- */
  a:focus-visible, button:focus-visible {
    outline: 2px solid var(--apple-blue); outline-offset: 3px; border-radius: 12px;
  }
  .apple-btn:focus-visible, .icon-btn:focus-visible, .badge:focus-visible, .modal-close:focus-visible { border-radius: 980px; }

  /* ---------- Small screens ---------- */
  @media (max-width: 640px) {
    .library-header { padding: 1.35rem 1.1rem 1rem; }
    .file-row { padding: 0.85rem 1.1rem; }
  }
  @media (prefers-reduced-motion: reduce) {
    .hud-dot.live { animation: none !important; }
    .apple-btn, .icon-btn, .file-row, .badge, .fan-card { transition: none !important; }
  }
</style>
{% endblock %}

{% block content %}
<div x-data="fileManager()"
     @open-expiry.window="openExpiry($event.detail)"
     @copy-link.window="copyAndToast($event.detail.url)"
     @open-preview.window="openPreview($event.detail)">

<input type="file" id="globalFileInput" multiple class="hidden" aria-hidden="true">

<!-- Full-page drag overlay -->
<div id="dragOverlay" class="drag-overlay" aria-hidden="true">
    <div class="drag-inner">
        <svg fill="none" stroke="currentColor" viewBox="0 0 24 24" aria-hidden="true">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5"
                  d="M7 16a4 4 0 01-.88-7.903A5 5 0 1115.9 6L16 6a5 5 0 011 9.9M15 13l-3-3m0 0l-3 3m3-3v12"/>
        </svg>
        <p>{% trans "Drop files to upload" %}</p>
    </div>
</div>

<div class="apple-wrap">

    <!-- File library card -->
    <section class="apple-card" style="margin-top: 1.5rem;" aria-labelledby="files-heading">

        <!-- Library header (title + count + upload) -->
        <div class="library-header">
            <div class="library-title-group">
                <h2 id="files-heading" class="section-title">{% trans "Files" %}</h2>
                <p class="library-count">
                    <span x-text="visibleFiles.length">{{ files.count }}</span>
                    <span x-text="visibleFiles.length === 1 ? '{% trans "file" %}' : '{% trans "files" %}'">{% trans "files" %}</span>
                </p>
            </div>
            <div class="library-actions">
                <button type="button" @click="openPicker()" class="apple-btn apple-btn-primary">
                    <svg width="16" height="16" fill="none" stroke="currentColor" viewBox="0 0 24 24" stroke-width="2.5" aria-hidden="true">
                        <path stroke-linecap="round" stroke-linejoin="round" d="M12 5v14m-7-7h14"/>
                    </svg>
                    {% trans "Upload Files" %}
                </button>
            </div>
        </div>

        <!-- Hidden JSON template of each initial file -->
        <script id="initial-file-data" type="application/json" aria-hidden="true">
        [{% for file in files %}{
            "id": "{{ file.pk }}",
            "name": "{{ file.name|escapejs }}",
            "mime_type": "{{ file.mime_type|escapejs }}",
            "size": "{{ file.formatted_size }}",
            "download_count": {{ file.download_count }},
            "created_at": "{{ file.created_at|date:'c' }}",
            "is_public": {{ file.is_public|lower }},
            "public_url": "{{ file.public_url|escapejs }}",
            "expires_at": "{{ file.expires_at|date:'c' }}",
            "download_url": "{{ file.download_url|escapejs }}",
            "is_image": {{ file.is_image|lower }}
        }{% if not forloop.last %},{% endif %}{% endfor %}]
        </script>

        <!-- List body. Single render per file — responsive layout adapts to viewport. -->
        <ul x-ref="listEl" role="list" class="file-list" @remove-file.window="removeFile($event.detail.id)">
            <template x-for="f in visibleFiles" :key="f.id">
                <li class="file-row" x-data="fileRow(f)" :data-pk="f.id">

                    <!-- File icon -->
                    <span class="file-icon" aria-hidden="true">
                        <svg x-show="f.is_image" 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>
                        <svg x-show="!f.is_image" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                                  d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"/>
                        </svg>
                    </span>

                    <!-- Filename (clickable -> preview) + metadata -->
                    <div class="file-main">
                        <a href="#" @click.prevent="$root.dispatchEvent(new CustomEvent('open-preview', {bubbles:true, detail:{name:f.name, mimeType:f.mime_type, url:f.download_url}}))"
                           class="file-name"
                           :title="f.name"
                           x-text="f.name"></a>

                        <!-- Metadata line -->
                        <dl class="file-meta">
                            <dt class="sr-only">{% trans "Size" %}</dt>
                            <dd class="whitespace-nowrap" x-text="f.size"></dd>
                            <span class="sep" aria-hidden="true">·</span>
                            <dt class="sr-only">{% trans "Type" %}</dt>
                            <dd class="truncate" style="max-width:12rem" x-text="f.mime_type" :title="f.mime_type"></dd>
                            <span class="sep" aria-hidden="true">·</span>
                            <dt class="sr-only">{% trans "Uploaded" %}</dt>
                            <dd class="whitespace-nowrap" x-text="formatDate(f.created_at)"></dd>
                            <span class="sep" aria-hidden="true">·</span>
                            <dt class="sr-only">{% trans "Downloads" %}</dt>
                            <dd class="whitespace-nowrap">
                                <span x-text="f.download_count"></span>
                                <span style="color:#c7c7cc;margin-left:0.15rem">{% trans "downloads" %}</span>
                            </dd>
                        </dl>

                        <!-- Public status + copy link -->
                        <div class="file-sub">
                            <button type="button" @click="togglePublic()"
                                    class="badge"
                                    :class="isPublic ? 'badge-public' : 'badge-private'"
                                    :title="isPublic ? '{% trans "Click to make private" %}' : '{% trans "Click to make public" %}'">
                                <span x-show="isPublic" aria-hidden="true">●</span>
                                <span x-show="!isPublic" aria-hidden="true">○</span>
                                <span x-text="isPublic ? '{% trans "Public" %}' : '{% trans "Private" %}'"></span>
                            </button>

                            <span x-show="isPublic && expiresAt"
                                  class="expiry-chip"
                                  :class="isExpired ? 'expired' : ''"
                                  @click="$root.dispatchEvent(new CustomEvent('open-expiry', {bubbles:true, detail:{pk, expiresAt}}))"
                                  x-text="isExpired ? '⚠ {% trans "Expired" %}' : '⏱ ' + formatExpiry(expiresAt)"></span>

                            <span x-show="isPublic && !expiresAt"
                                  class="expiry-chip"
                                  @click="$root.dispatchEvent(new CustomEvent('open-expiry', {bubbles:true, detail:{pk, expiresAt}}))">
                                {% trans "No expiry" %}
                            </span>

                            <button type="button" x-show="isPublic" @click="copyPublicUrl()" class="apple-link">
                                <svg fill="none" stroke="currentColor" viewBox="0 0 24 24" aria-hidden="true">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z"/>
                                </svg>
                                {% trans "Copy link" %}
                            </button>
                        </div>
                    </div>

                    <!-- Action buttons -->
                    <div class="file-actions">
                        <a :href="f.download_url" :download="f.name"
                           class="icon-btn blue"
                           :title="'{% trans "Download / View" %}'" aria-label="{% trans "Download / View" %}">
                            <svg fill="none" stroke="currentColor" viewBox="0 0 24 24" aria-hidden="true">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4"/>
                            </svg>
                        </a>
                        <button type="button" x-show="isPublic"
                                @click="$root.dispatchEvent(new CustomEvent('open-expiry', {bubbles:true, detail:{pk, expiresAt}}))"
                                class="icon-btn amber"
                                title="{% trans 'Set expiry' %}" aria-label="{% trans 'Set expiry' %}">
                            <svg fill="none" stroke="currentColor" viewBox="0 0 24 24" aria-hidden="true">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"/>
                            </svg>
                        </button>
                        <button type="button" @click="confirmDelete()"
                                class="icon-btn red"
                                title="{% trans 'Delete' %}" aria-label="{% trans 'Delete' %}">
                            <svg fill="none" stroke="currentColor" viewBox="0 0 24 24" aria-hidden="true">
                                <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>
                </li>
            </template>

            <!-- Empty state -->
            <li x-show="visibleFiles.length === 0" class="empty-state">
                <svg fill="none" stroke="currentColor" viewBox="0 0 24 24" aria-hidden="true">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5"
                          d="M7 21h10a2 2 0 002-2V9.414a1 1 0 00-.293-.707l-5.414-5.414A1 1 0 0012.586 3H7a2 2 0 00-2 2v14a2 2 0 002 2z"/>
                </svg>
                <p class="es-title">{% trans "No files yet" %}</p>
                <p class="es-sub">{% trans "Drag files anywhere on this page, or click Upload Files above." %}</p>
            </li>
        </ul>
    </section>

    <div style="height: 2.5rem;" aria-hidden="true"></div>

</div>

<!-- ── Toast notification ──────────────────────────────────────── -->
<div x-show="toastVisible" x-cloak
     x-transition:enter="transition ease-out duration-200"
     x-transition:enter-start="opacity-0 -translate-y-1"
     x-transition:enter-end="opacity-100 translate-y-0"
     x-transition:leave="transition ease-in duration-150"
     x-transition:leave-start="opacity-100 translate-y-0"
     x-transition:leave-end="opacity-0 -translate-y-1"
     class="apple-toast"
     role="status" aria-live="polite">
    <svg fill="none" stroke="currentColor" viewBox="0 0 24 24" aria-hidden="true">
        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"/>
    </svg>
    <span x-text="toastMsg"></span>
</div>

<!-- ── Global Expiry Modal ─────────────────────────────────────── -->
<div x-show="expiryModal.open" x-cloak
     x-transition:enter="transition ease-out duration-150"
     x-transition:enter-start="opacity-0"
     x-transition:enter-end="opacity-100"
     x-transition:leave="transition ease-in duration-100"
     x-transition:leave-start="opacity-100"
     x-transition:leave-end="opacity-0"
     class="apple-modal-bg"
     @click.self="expiryModal.open = false"
     role="dialog" aria-modal="true" :aria-label="'{% trans "Set expiry date" %}'">
    <div class="apple-modal"
         x-transition:enter="transition ease-out duration-150"
         x-transition:enter-start="opacity-0 scale-95"
         x-transition:enter-end="opacity-100 scale-100">
        <div class="modal-head">
            <h3>{% trans "Set Expiry Date" %}</h3>
            <button type="button" @click="expiryModal.open = false" class="modal-close"
                    aria-label="{% trans 'Close' %}">
                <svg fill="none" stroke="currentColor" viewBox="0 0 24 24" aria-hidden="true">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/>
                </svg>
            </button>
        </div>
        <div class="modal-body">
            <p class="modal-desc">{% trans "Leave blank for no expiry. The public link will stop working after this date." %}</p>
            <input type="datetime-local" x-model="expiryModal.expiryInput" class="apple-input">
            <div class="modal-footer">
                <button type="button" @click="clearExpiry()" class="text-link">{% trans "Clear expiry" %}</button>
                <div class="right">
                    <button type="button" @click="expiryModal.open = false" class="apple-btn apple-btn-secondary">{% trans "Cancel" %}</button>
                    <button type="button" @click="saveExpiry()" class="apple-btn apple-btn-primary">{% trans "Save" %}</button>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- ── Upload Progress HUD ──────────────────────────────────────── -->
<div class="upload-hud">
    <div class="apple-card" style="border:none;box-shadow:none;border-radius:inherit;overflow:visible">
        <!-- Header — click to fold/unfold -->
        <div @click="hudOpen = !hudOpen"
             class="hud-header"
             role="button" tabindex="0" @keydown.enter.prevent="hudOpen = !hudOpen" @keydown.space.prevent="hudOpen = !hudOpen"
             :aria-expanded="hudOpen">
            <div class="hud-title">
                <span x-show="uploads.some(u => u.status === 'uploading')" class="hud-dot live"></span>
                <span x-show="!uploads.some(u => u.status === 'uploading')" class="hud-dot idle"></span>
                <span>
                    <span x-show="uploads.some(u => u.status === 'uploading')"
                          x-text="'{% trans "Uploading" %} ' + uploads.filter(u => u.status === 'uploading').length + ' / ' + uploads.length"></span>
                    <span x-show="!uploads.some(u => u.status === 'uploading')">{% trans "Uploads" %}</span>
                </span>
            </div>
            <div style="display:flex;align-items:center;gap:0.5rem">
                <button x-show="uploads.some(u => u.status === 'uploading')"
                        @click.stop="cancelAll()"
                        class="hud-cancel">
                    {% trans "Cancel" %}
                </button>
                <svg class="hud-chev" :class="hudOpen ? '' : 'rotate-180'" fill="none" stroke="currentColor" viewBox="0 0 24 24" aria-hidden="true">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7"/>
                </svg>
            </div>
        </div>

        <!-- Collapsible body -->
        <div x-show="hudOpen" x-cloak
             x-transition:enter="transition ease-out duration-150"
             x-transition:enter-start="opacity-0 -translate-y-1"
             x-transition:enter-end="opacity-100 translate-y-0"
             x-transition:leave="transition ease-in duration-100"
             x-transition:leave-start="opacity-100 translate-y-0"
             x-transition:leave-end="opacity-0 -translate-y-1">

            <div x-show="uploads.length === 0" class="hud-empty">
                {% trans "Drag files anywhere or click Upload Files." %}
            </div>

            <div x-show="uploads.length > 0" class="hud-body">
                <template x-for="u in uploads" :key="u.id">
                    <div class="hud-item">
                        <div class="hud-item-top">
                            <span class="hud-item-name" x-text="u.name"></span>
                            <span class="hud-item-status"
                                  :class="{
                                    'text-blue-500': u.status === 'uploading',
                                    'text-green-600': u.status === 'done',
                                    'text-red-500': u.status === 'error',
                                    'text-gray-400': u.status === 'cancelled'
                                  }"
                                  :title="u.errorMsg || ''"
                                  x-text="u.status === 'uploading' ? u.progress + '%' : (u.errorMsg || u.status)"></span>
                        </div>
                        <div class="hud-bar">
                            <div class="hud-bar-fill"
                                 :class="{
                                   'bg-blue-500': u.status === 'uploading',
                                   'bg-green-500': u.status === 'done',
                                   'bg-red-400': u.status === 'error',
                                   'bg-gray-300': u.status === 'cancelled'
                                 }"
                                 :style="'width:' + u.progress + '%'"></div>
                        </div>
                    </div>
                </template>
            </div>
        </div>
    </div>
</div>

<!-- ── File Preview Modal ─────────────────────────────────────── -->
<div x-show="previewModal.open" x-cloak
     class="preview-bg"
     @click.self="closePreview()"
     @keydown.escape.window="closePreview()"
     role="dialog" aria-modal="true" aria-label="{% trans 'File preview' %}">

    <div class="preview-shell">

        <div class="preview-head">
            <h3 x-text="previewModal.name"></h3>
            <button type="button" @click="closePreview()" class="modal-close" aria-label="{% trans 'Close' %}">
                <svg fill="none" stroke="currentColor" viewBox="0 0 24 24" aria-hidden="true">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/>
                </svg>
            </button>
        </div>

        <div class="preview-stage">
            <button type="button" x-show="fileList.length > 1" @click="prevFile()"
                    class="preview-nav" style="left:0.5rem"
                    title="{% trans 'Previous' %} (←)" aria-label="{% trans 'Previous' %}">
                <svg fill="none" stroke="currentColor" viewBox="0 0 24 24" aria-hidden="true">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7"/>
                </svg>
            </button>
            <button type="button" x-show="fileList.length > 1" @click="nextFile()"
                    class="preview-nav" style="right:0.5rem"
                    title="{% trans 'Next' %} (→)" aria-label="{% trans 'Next' %}">
                <svg fill="none" stroke="currentColor" viewBox="0 0 24 24" aria-hidden="true">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7"/>
                </svg>
            </button>

            <img x-show="previewModal.open && previewModal.mimeType.startsWith('image/')" x-cloak
                 :src="previewModal.url" :alt="previewModal.name"
                 style="display:block; max-width:min(88vw,1200px); max-height:calc(92vh - 96px); width:auto; height:auto; object-fit:contain;">

            <video x-show="previewModal.open && previewModal.mimeType.startsWith('video/')" x-cloak
                   controls
                   style="display:block; max-width:min(88vw,1200px); max-height:calc(92vh - 96px); width:auto; height:auto;"
                   :src="previewModal.url"></video>

            <div x-show="previewModal.open && previewModal.mimeType.startsWith('audio/')" x-cloak
                 class="preview-fallback" style="width:22rem">
                <svg fill="none" stroke="currentColor" viewBox="0 0 24 24" aria-hidden="true">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M9 19V6l12-3v13M9 19c0 1.105-1.343 2-3 2s-3-.895-3-2 1.343-2 3-2 3 .895 3 2zm12-3c0 1.105-1.343 2-3 2s-3-.895-3-2 1.343-2 3-2 3 .895 3 2zM9 10l12-3"/>
                </svg>
                <p class="fb-title" x-text="previewModal.name"></p>
                <audio controls style="width:100%" :src="previewModal.url"></audio>
            </div>

            <div x-show="previewModal.open && !previewModal.mimeType.startsWith('image/') && !previewModal.mimeType.startsWith('video/') && !previewModal.mimeType.startsWith('audio/')" x-cloak
                 class="preview-fallback">
                <svg fill="none" stroke="currentColor" viewBox="0 0 24 24" aria-hidden="true">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"/>
                </svg>
                <p class="fb-title">{% trans "Unfortunately, we can't preview this file." %}</p>
                <p class="fb-sub">{% trans "But you can click the link below to download it." %}</p>
                <a :href="previewModal.url" :download="previewModal.name" class="apple-btn apple-btn-primary">
                    <svg width="16" height="16" fill="none" stroke="currentColor" viewBox="0 0 24 24" aria-hidden="true">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4"/>
                    </svg>
                    <span x-text="previewModal.name"></span>
                </a>
            </div>
        </div>

        <div class="preview-foot">
            <div class="meta">
                <span x-text="previewModal.mimeType"></span>
                <span x-show="fileList.length > 1" x-text="(currentIndex + 1) + ' / ' + fileList.length"></span>
            </div>
            <a :href="previewModal.url" :download="previewModal.name" class="apple-link">
                <svg fill="none" stroke="currentColor" viewBox="0 0 24 24" aria-hidden="true">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4"/>
                </svg>
                {% trans "Download" %}
            </a>
        </div>
    </div>
</div>

</div><!-- /Alpine scope -->

<script>
function fileManager() {
    return {
        visibleFiles: [],
        uploads: [],
        hudOpen: false,
        toastMsg: '',
        toastVisible: false,
        _toastTimer: null,
        expiryModal: { open: false, pk: '', expiryInput: '' },
        previewModal: { open: false, name: '', mimeType: '', url: '' },
        fileList: [],
        currentIndex: -1,

        init() {
            // Seed initial file list from server-rendered JSON
            try {
                this.visibleFiles = JSON.parse(document.getElementById('initial-file-data').textContent);
            } catch (e) {
                this.visibleFiles = [];
            }
            // Build file list for preview keyboard navigation
            this.fileList = this.visibleFiles.map(f => ({ name: f.name, mimeType: f.mime_type, url: f.download_url }));

            // Arrow key navigation in preview
            window.addEventListener('keydown', e => {
                if (!this.previewModal.open) return;
                if (e.key === 'ArrowRight') { e.preventDefault(); this.nextFile(); }
                else if (e.key === 'ArrowLeft') { e.preventDefault(); this.prevFile(); }
            });

            const overlay = document.getElementById('dragOverlay');
            const input = document.getElementById('globalFileInput');
            let dragCounter = 0;

            document.addEventListener('dragenter', e => {
                if (!e.dataTransfer || !e.dataTransfer.types || !e.dataTransfer.types.includes('Files')) return;
                dragCounter++;
                overlay.style.opacity = '1';
            });
            document.addEventListener('dragleave', () => {
                dragCounter = Math.max(0, dragCounter - 1);
                if (dragCounter === 0) overlay.style.opacity = '0';
            });
            document.addEventListener('dragover', e => e.preventDefault());
            document.addEventListener('drop', e => {
                e.preventDefault();
                dragCounter = 0;
                overlay.style.opacity = '0';
                const files = e.dataTransfer && e.dataTransfer.files;
                if (files && files.length) this.uploadFiles(files);
            });

            input.addEventListener('change', e => {
                if (e.target.files.length) this.uploadFiles(e.target.files);
                e.target.value = '';
            });

            // Re-sync expiry updates propagated from rows
            window.addEventListener('expiry-updated', e => {
                const id = String(e.detail.pk);
                const f = this.visibleFiles.find(x => String(x.id) === id);
                if (f) {
                    f.expires_at = e.detail.expires_at || null;
                }
            });
        },

        openPicker() {
            document.getElementById('globalFileInput').click();
        },

        // ── Uploads ─────────────────────────────────────────────────
        uploadFiles(fileList) {
            this.hudOpen = true;
            Array.from(fileList).forEach(file => {
                const id = Date.now() + '_' + Math.random().toString(36).slice(2);
                this.uploads.push({ id, name: file.name, progress: 0, status: 'uploading', errorMsg: '', xhr: null });
                this._uploadOne(file, id);
            });
        },

        _uploadOne(file, itemId) {
            const formData = new FormData();
            formData.append('files', file);
            formData.append('csrfmiddlewaretoken', getCsrfToken());

            const xhr = new XMLHttpRequest();
            const find = () => this.uploads.find(u => u.id === itemId);
            const u0 = find(); if (u0) u0.xhr = xhr;

            xhr.upload.onprogress = e => {
                if (e.lengthComputable) { const u = find(); if (u) u.progress = Math.round((e.loaded / e.total) * 100); }
            };
            xhr.onload = () => {
                const u = find();
                if (u) {
                    if (xhr.status >= 200 && xhr.status < 300) {
                        u.status = 'done';
                        u.progress = 100;
                        // Insert uploaded rows from server response — no full page reload
                        try {
                            const data = JSON.parse(xhr.responseText);
                            const inserted = (data && data.uploaded) || [];
                            inserted.forEach(rec => {
                                const newFile = {
                                    id: rec.id,
                                    name: rec.name,
                                    mime_type: rec.mime_type || guessMime(file.name),
                                    size: rec.formatted_size || formatBytes(rec.size || file.size),
                                    download_count: 0,
                                    created_at: rec.created_at || new Date().toISOString(),
                                    is_public: false,
                                    public_url: '',
                                    expires_at: null,
                                    download_url: rec.download_url || ('/ui/files/' + rec.id + '-' + encodeURIComponent(rec.name)),
                                    is_image: (rec.mime_type || guessMime(file.name)).startsWith('image/'),
                                };
                                // Avoid inserting duplicate (key by id)
                                if (!this.visibleFiles.some(x => String(x.id) === String(newFile.id))) {
                                    this.visibleFiles.unshift(newFile);
                                    this.fileList.unshift({ name: newFile.name, mimeType: newFile.mime_type, url: newFile.download_url });
                                }
                            });
                        } catch (e) { /* ignore parse error */ }
                    } else {
                        u.status = 'error';
                        try {
                            const data = JSON.parse(xhr.responseText);
                            const firstError = data && Array.isArray(data.errors) && data.errors[0];
                            if (firstError && firstError.error) u.errorMsg = firstError.error;
                        } catch (e) { /* ignore parse error, keep generic 'error' */ }
                    }
                }
                this._maybeCollapseHud();
            };
            xhr.onerror = () => { const u = find(); if (u) u.status = 'error'; this._maybeCollapseHud(); };
            xhr.onabort = () => { const u = find(); if (u) u.status = 'cancelled'; this._maybeCollapseHud(); };
            xhr.open('POST', '{% url "file-upload" %}');
            xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
            xhr.send(formData);
        },

        _maybeCollapseHud(delay = 2000) {
            if (this.uploads.length && this.uploads.every(u => u.status !== 'uploading')) {
                setTimeout(() => {
                    if (this.uploads.every(u => u.status !== 'uploading')) {
                        this.hudOpen = false;
                        // Optionally clear the list after a moment so the HUD shows its empty state
                        setTimeout(() => { this.uploads = []; }, 800);
                    }
                }, delay);
            }
        },

        cancelAll() {
            this.uploads.forEach(u => { if (u.xhr && u.status === 'uploading') { u.xhr.abort(); u.status = 'cancelled'; } });
            setTimeout(() => { this.uploads = []; }, 800);
        },

        removeFile(id) {
            const idx = this.visibleFiles.findIndex(f => String(f.id) === String(id));
            if (idx !== -1) this.visibleFiles.splice(idx, 1);
            const fidx = this.fileList.findIndex(f => f.url === (idx !== -1 ? 'placeholder' : ''));
            // rebuild fileList to keep preview nav in sync
            this.fileList = this.visibleFiles.map(f => ({ name: f.name, mimeType: f.mime_type, url: f.download_url }));
        },

        // ── Preview modal ────────────────────────────────────────────
        openPreview({ name, mimeType, url }) {
            this.currentIndex = this.fileList.findIndex(f => f.url === url);
            if (this.currentIndex === -1) this.currentIndex = 0;
            this.previewModal = { open: true, name, mimeType, url };
        },
        prevFile() {
            if (this.fileList.length < 2) return;
            this.currentIndex = (this.currentIndex - 1 + this.fileList.length) % this.fileList.length;
            const f = this.fileList[this.currentIndex];
            this.previewModal = { open: true, name: f.name, mimeType: f.mimeType, url: f.url };
        },
        nextFile() {
            if (this.fileList.length < 2) return;
            this.currentIndex = (this.currentIndex + 1) % this.fileList.length;
            const f = this.fileList[this.currentIndex];
            this.previewModal = { open: true, name: f.name, mimeType: f.mimeType, url: f.url };
        },
        closePreview() {
            this.previewModal.open = false;
            document.querySelectorAll('video, audio').forEach(el => el.pause());
        },

        // ── Expiry modal ─────────────────────────────────────────────
        openExpiry({ pk, expiresAt }) {
            this.expiryModal.pk = pk;
            this.expiryModal.expiryInput = expiresAt ? new Date(expiresAt).toISOString().slice(0, 16) : '';
            this.expiryModal.open = true;
        },
        saveExpiry() {
            const expires_at = this.expiryModal.expiryInput ? new Date(this.expiryModal.expiryInput).toISOString() : null;
            fetch(`/ui/files/${this.expiryModal.pk}/set-expiry/`, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json', 'X-CSRFToken': getCsrfToken() },
                body: JSON.stringify({ expires_at }),
            }).then(r => r.json()).then(d => {
                this.expiryModal.open = false;
                window.dispatchEvent(new CustomEvent('expiry-updated', { detail: { pk: this.expiryModal.pk, expires_at: d.expires_at } }));
            });
        },
        clearExpiry() { this.expiryModal.expiryInput = ''; this.saveExpiry(); },

        // ── Toast ────────────────────────────────────────────────────
        copyAndToast(url) {
            copyToClipboard(url);
            this.showToast('{% trans "Link copied!" %}');
        },
        showToast(msg) {
            this.toastMsg = msg;
            this.toastVisible = true;
            clearTimeout(this._toastTimer);
            this._toastTimer = setTimeout(() => { this.toastVisible = false; }, 2500);
        },

        // ── misc ────────────────────────────────────────────────────
        formatDate(iso) {
            if (!iso) return '';
            try {
                const d = new Date(iso);
                const pad = n => String(n).padStart(2, '0');
                return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}`;
            } catch (e) { return iso; }
        },
    };
}

function fileRow(f) {
    return {
        f: f,
        pk: f.id,
        isPublic: !!f.is_public,
        publicUrl: f.public_url || '',
        expiresAt: f.expires_at || null,
        get isExpired() { return this.expiresAt && new Date(this.expiresAt) < new Date(); },
        init() {
            window.addEventListener('expiry-updated', e => {
                if (String(e.detail.pk) === String(this.pk)) {
                    this.expiresAt = e.detail.expires_at || null;
                }
            });
        },
        togglePublic() {
            fetch(`/ui/files/${this.pk}/toggle-public/`, {
                method: 'POST', headers: { 'X-CSRFToken': getCsrfToken() },
            }).then(r => r.json()).then(d => {
                this.isPublic = d.is_public;
                this.publicUrl = d.public_url || '';
                // sync underlying model so preview/toast use the right URL
                this.f.is_public = d.is_public;
                this.f.public_url = d.public_url || '';
            });
        },
        formatExpiry(dt) { return dt ? new Date(dt).toLocaleDateString() : ''; },
        copyPublicUrl() {
            const url = this.publicUrl.startsWith('http') ? this.publicUrl : location.origin + this.publicUrl;
            copyToClipboard(url);
            window.dispatchEvent(new CustomEvent('copy-link', { detail: { url } }));
        },
        confirmDelete() {
            if (!confirm('{% trans "Delete this file?" %}')) return;
            fetch(`/ui/files/${this.pk}/delete/`, {
                method: 'POST',
                headers: { 'X-CSRFToken': getCsrfToken() },
            }).then(r => {
                if (r.ok) {
                    window.dispatchEvent(new CustomEvent('remove-file', { detail: { id: this.pk } }));
                }
            }).catch(() => {/* ignore */});
        },
    };
}

function getCsrfToken() {
    return document.cookie.split(';').find(c => c.trim().startsWith('csrftoken='))?.split('=')[1] || '';
}

function copyToClipboard(text) {
    if (navigator.clipboard && navigator.clipboard.writeText) {
        navigator.clipboard.writeText(text).catch(() => fallbackCopy(text));
    } else {
        fallbackCopy(text);
    }
}
function fallbackCopy(text) {
    const el = document.createElement('textarea');
    el.value = text; el.style.cssText = 'position:fixed;opacity:0';
    document.body.appendChild(el); el.select();
    try { document.execCommand('copy'); } catch (e) {}
    document.body.removeChild(el);
}

function guessMime(name) {
    const ext = (name.split('.').pop() || '').toLowerCase();
    const map = {
        jpg: 'image/jpeg', jpeg: 'image/jpeg', png: 'image/png', gif: 'image/gif',
        webp: 'image/webp', svg: 'image/svg+xml', pdf: 'application/pdf',
        mp4: 'video/mp4', webm: 'video/webm', mp3: 'audio/mpeg', wav: 'audio/wav',
        txt: 'text/plain', zip: 'application/zip',
    };
    return map[ext] || 'application/octet-stream';
}

function formatBytes(bytes) {
    if (!bytes) return '0 B';
    if (bytes < 1024) return bytes + ' B';
    if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(1) + ' KB';
    if (bytes < 1024 * 1024 * 1024) return (bytes / (1024 * 1024)).toFixed(1) + ' MB';
    return (bytes / (1024 * 1024 * 1024)).toFixed(2) + ' GB';
}
</script>

{% endblock %}
