<?php /** @var array $items; @var array $artists */ ?>
<div class="p-5 md:p-8 max-w-5xl">
  <div class="text-[10px] uppercase tracking-[0.3em] text-gold"><?= e(t('admin.gallery.kicker')) ?></div>
  <h1 class="mt-1 text-2xl md:text-3xl font-display mb-6"><?= e(t('admin.gallery.title')) ?></h1>

  <!-- Upload form with progress -->
  <div class="bg-white/[0.02] border border-white/5 rounded-2xl p-6 mb-8"
       x-data="{
         mode: 'upload',
         uploading: false,
         progress: 0,
         error: '',
         success: '',
         fileName: '',
         fileSize: '',
         fileType: '',
         previewUrl: '',
         pickFile(e) {
           const f = e.target.files[0];
           if (!f) { this.fileName = ''; this.previewUrl = ''; return; }
           this.fileName = f.name;
           this.fileSize = f.size < 1048576 ? (f.size / 1024).toFixed(1) + ' KB' : (f.size / 1048576).toFixed(1) + ' MB';
           this.fileType = f.type.startsWith('video') ? 'video' : 'image';
           if (this.previewUrl) URL.revokeObjectURL(this.previewUrl);
           this.previewUrl = URL.createObjectURL(f);
         },
         submit(e) {
           e.preventDefault();
           const form = e.target;
           const fd = new FormData(form);
           this.uploading = true;
           this.progress = 0;
           this.error = '';
           this.success = '';

           const xhr = new XMLHttpRequest();
           xhr.open('POST', form.action);
           xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');

           xhr.upload.addEventListener('progress', (ev) => {
             if (ev.lengthComputable) this.progress = Math.round((ev.loaded / ev.total) * 100);
           });

           xhr.addEventListener('load', () => {
             this.uploading = false;
             try {
               const res = JSON.parse(xhr.responseText);
               if (res.ok) {
                 this.success = res.message || '<?= e(t('admin.gallery.upload_success')) ?>';
                 this.progress = 100;
                 setTimeout(() => location.reload(), 800);
               } else {
                 this.error = res.message || '<?= e(t('admin.gallery.upload_failed')) ?>';
                 this.progress = 0;
               }
             } catch (parseErr) {
               // Not JSON — server crashed or returned HTML (error recovery redirect)
               this.error = '<?= e(t('admin.gallery.upload_failed')) ?> — <?= e(t('admin.gallery.server_error_hint')) ?>';
               this.progress = 0;
             }
           });

           xhr.addEventListener('error', () => {
             this.uploading = false;
             this.error = '<?= e(t('admin.gallery.upload_failed')) ?>';
             this.progress = 0;
           });

           xhr.send(fd);
         }
       }">
    <form @submit="submit($event)" method="POST" action="<?= url('/admin/gallery') ?>" enctype="multipart/form-data">
      <?= csrf_field() ?>

      <!-- Mode tabs -->
      <div class="flex gap-2 mb-5">
        <button type="button" @click="mode='upload'" :class="mode==='upload' ? 'bg-gold text-ink' : 'bg-white/5 text-bone/50 hover:text-bone'" class="px-4 py-2 rounded-lg text-xs uppercase tracking-widest transition-colors">
          <?= e(t('admin.gallery.tab_upload')) ?>
        </button>
        <button type="button" @click="mode='url'" :class="mode==='url' ? 'bg-gold text-ink' : 'bg-white/5 text-bone/50 hover:text-bone'" class="px-4 py-2 rounded-lg text-xs uppercase tracking-widest transition-colors">
          <?= e(t('admin.gallery.tab_url')) ?>
        </button>
      </div>

      <!-- File upload -->
      <div x-show="mode === 'upload'" class="mb-4">
        <label class="label mb-2"><?= e(t('admin.gallery.upload')) ?></label>

        <!-- Empty state: drop zone -->
        <div x-show="!fileName" class="border-2 border-dashed border-white/10 hover:border-gold/30 rounded-xl p-6 text-center transition-colors cursor-pointer relative">
          <input type="file" name="file" accept="image/*,video/mp4,video/webm,video/quicktime"
                 @change="pickFile($event)"
                 class="absolute inset-0 w-full h-full opacity-0 cursor-pointer">
          <svg class="w-8 h-8 mx-auto text-bone/20 mb-2" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"><path d="M21 15v4a2 2 0 01-2 2H5a2 2 0 01-2-2v-4M17 8l-5-5-5 5M12 3v12"/></svg>
          <p class="text-sm text-bone/40"><?= e(t('admin.gallery.drop_hint')) ?></p>
          <p class="text-[10px] text-bone/25 mt-1"><?= e(t('admin.gallery.upload_hint')) ?></p>
        </div>

        <!-- Selected file preview -->
        <div x-show="fileName" x-cloak class="border border-gold/30 bg-gold/[0.03] rounded-xl p-4 relative">
          <div class="flex gap-4 items-start">
            <!-- Thumbnail -->
            <div class="w-24 h-24 rounded-lg bg-ink overflow-hidden shrink-0 border border-white/10">
              <template x-if="fileType === 'image'">
                <img :src="previewUrl" alt="" class="w-full h-full object-cover">
              </template>
              <template x-if="fileType === 'video'">
                <video :src="previewUrl" class="w-full h-full object-cover" muted></video>
              </template>
            </div>
            <!-- Info -->
            <div class="flex-1 min-w-0">
              <div class="text-sm font-medium truncate" x-text="fileName"></div>
              <div class="text-xs text-bone/40 mt-1" x-text="fileSize"></div>
              <div class="mt-2">
                <span x-show="fileType === 'image'" class="text-[9px] px-2 py-0.5 rounded-full bg-blue-500/10 text-blue-400 border border-blue-500/20 uppercase tracking-wider">Image</span>
                <span x-show="fileType === 'video'" class="text-[9px] px-2 py-0.5 rounded-full bg-purple-500/10 text-purple-400 border border-purple-500/20 uppercase tracking-wider">Video</span>
              </div>
            </div>
            <!-- Change button -->
            <label class="text-xs text-gold/60 hover:text-gold cursor-pointer transition-colors shrink-0 mt-1">
              <?= e(t('admin.gallery.change_file')) ?>
              <input type="file" name="file" accept="image/*,video/mp4,video/webm,video/quicktime"
                     @change="pickFile($event)" class="hidden">
            </label>
          </div>
        </div>
      </div>

      <!-- Video URL -->
      <div x-show="mode === 'url'" class="mb-4 space-y-3">
        <div>
          <label class="label"><?= e(t('admin.gallery.video_url')) ?></label>
          <input type="url" name="video_url" placeholder="https://youtube.com/watch?v=... or https://vimeo.com/..." class="input">
        </div>
        <div>
          <label class="label"><?= e(t('admin.gallery.thumb_url')) ?></label>
          <input type="url" name="thumb_url" placeholder="https://.../poster.jpg" class="input">
        </div>
      </div>

      <!-- Metadata -->
      <div class="grid sm:grid-cols-3 gap-3 pt-4 border-t border-white/5 mb-5">
        <div>
          <label class="label"><?= e(t('admin.gallery.artist')) ?></label>
          <select name="artist_id" class="input text-sm">
            <option value=""><?= e(t('admin.gallery.unassigned')) ?></option>
            <?php foreach ($artists as $a): ?>
              <option value="<?= e($a['id']) ?>"><?= e($a['display_name'] ?? '') ?></option>
            <?php endforeach; ?>
          </select>
        </div>
        <div><label class="label"><?= e(t('admin.gallery.tags')) ?></label><input name="tags" placeholder="realism, color" class="input text-sm"></div>
        <div><label class="label"><?= e(t('admin.gallery.caption')) ?></label><input name="caption" class="input text-sm"></div>
      </div>

      <!-- Progress bar -->
      <div x-show="uploading" class="mb-4">
        <div class="flex items-center justify-between text-xs text-bone/50 mb-1.5">
          <span><?= e(t('admin.gallery.uploading')) ?></span>
          <span x-text="progress + '%'"></span>
        </div>
        <div class="w-full h-2 bg-white/5 rounded-full overflow-hidden">
          <div class="h-full bg-gold rounded-full transition-all duration-300 ease-out" :style="'width:' + progress + '%'"></div>
        </div>
      </div>

      <!-- Messages -->
      <div x-show="error" x-cloak class="mb-4 rounded-xl px-4 py-3 text-sm bg-red-500/10 text-red-300 border border-red-500/20" x-text="error"></div>
      <div x-show="success" x-cloak class="mb-4 rounded-xl px-4 py-3 text-sm bg-gold/10 text-gold border border-gold/20" x-text="success"></div>

      <!-- Submit -->
      <button class="btn-gold text-xs" :disabled="uploading" :class="uploading ? 'opacity-50 cursor-wait' : ''">
        <span x-show="!uploading"><?= e(t('admin.gallery.add')) ?></span>
        <span x-show="uploading" class="flex items-center gap-2">
          <svg class="animate-spin w-4 h-4" viewBox="0 0 24 24" fill="none"><circle cx="12" cy="12" r="10" stroke="currentColor" stroke-width="3" stroke-dasharray="31.4" stroke-dashoffset="10"/></svg>
          <?= e(t('admin.gallery.uploading')) ?>
        </span>
      </button>
    </form>
  </div>

  <!-- Gallery grid -->
  <?php if (empty($items)): ?>
    <div class="bg-white/[0.02] border border-white/5 rounded-2xl p-16 text-center">
      <div class="text-4xl mb-3 opacity-20">🖼️</div>
      <p class="text-bone/30 text-sm"><?= e(t('admin.gallery.empty')) ?></p>
    </div>
  <?php else: ?>
    <div class="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-3">
      <?php foreach ($items as $it): ?>
        <div class="relative aspect-square bg-white/5 rounded-xl overflow-hidden group">
          <?php if (($it['kind'] ?? '') === 'VIDEO'): ?>
            <video src="<?= e(url($it['url'])) ?>" class="w-full h-full object-cover" muted loop playsinline
                   onmouseenter="this.play()" onmouseleave="this.pause();this.currentTime=0"></video>
            <div class="absolute top-2 left-2 px-2 py-0.5 rounded-full bg-ink/70 backdrop-blur text-[9px] uppercase tracking-widest text-gold border border-white/10">Video</div>
          <?php else: ?>
            <img src="<?= e(url($it['url'])) ?>" alt="<?= e($it['caption'] ?? '') ?>" class="w-full h-full object-cover" loading="lazy">
          <?php endif; ?>
          <!-- Delete overlay -->
          <div class="absolute inset-0 bg-ink/60 opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center">
            <form method="POST" action="<?= url('/admin/gallery/' . e($it['id']) . '/delete') ?>">
              <?= csrf_field() ?>
              <button class="w-10 h-10 rounded-full bg-red-500/80 text-white flex items-center justify-center hover:bg-red-500 transition-colors">
                <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="3 6 5 6 21 6"/><path d="M19 6l-1 14a2 2 0 01-2 2H8a2 2 0 01-2-2L5 6"/><path d="M10 11v6M14 11v6"/></svg>
              </button>
            </form>
          </div>
          <!-- Caption -->
          <?php if (!empty($it['caption'])): ?>
            <div class="absolute bottom-0 left-0 right-0 bg-gradient-to-t from-ink/80 to-transparent p-2 pt-6">
              <span class="text-[10px] text-bone/60"><?= e($it['caption']) ?></span>
            </div>
          <?php endif; ?>
        </div>
      <?php endforeach; ?>
    </div>
  <?php endif; ?>
</div>
