<form hx-post="/editor/{{ p.id }}/save" hx-target="#post-container-{{ p.id }}" hx-swap="outerHTML" hx-encoding="multipart/form-data" id="post-container-{{ p.id }}" class="card flex flex-col group relative transition-colors border border-app-border {% if p.editorial_status == 'accepted' %}bg-app-successBg/10 border-app-success/20{% elif p.editorial_status == 'rejected' %}bg-app-errorBg/10 opacity-75{% else %}hover:border-app-borderFocus hover:shadow-glow{% endif %}">
  <input type="hidden" name="csrf_token" value="{{ user.csrf_token }}">

  <div class="flex flex-col xl:flex-row">
    <!-- Left: Meta Info & Status -->
    <div class="w-full xl:w-56 bg-app-bg/50 border-b xl:border-b-0 xl:border-r border-app-border p-4 flex flex-col gap-3">
      <div class="flex items-center justify-between">
        <span class="text-xs font-mono text-app-textMuted tracking-wider">#{{ p.id }}</span>
        {% if p.editorial_status == 'accepted' or p.editorial_status == 'published' %}
          <div class="flex items-center gap-1 text-xs font-medium text-app-success bg-app-success/10 px-2 py-1 rounded-md">
            <i data-lucide="check-circle-2" class="w-3 h-3"></i> Принят
          </div>
        {% elif p.editorial_status == 'rejected' or p.editorial_status == 'publish_failed' %}
          <div class="flex items-center gap-1 text-xs font-medium text-app-error bg-app-error/10 px-2 py-1 rounded-md">
            <i data-lucide="x-circle" class="w-3 h-3"></i> Отклонен
          </div>
        {% elif p.editorial_status == 'regenerating' %}
          <div class="flex items-center gap-1 text-xs font-medium text-app-warning bg-app-warning/10 px-2 py-1 rounded-md">
            <i data-lucide="refresh-cw" class="w-3 h-3 animate-spin"></i> В работе
          </div>
        {% else %}
          <div class="flex items-center gap-1 text-xs font-medium text-blue-400 bg-blue-400/10 px-2 py-1 rounded-md">
            <i data-lucide="clock" class="w-3 h-3"></i> Ожидает
          </div>
        {% endif %}
      </div>

      <div class="flex items-center gap-2">
        <div class="w-8 h-8 rounded bg-app-surface border border-app-border flex items-center justify-center flex-shrink-0">
          <i data-lucide="link" class="w-4 h-4 text-app-textMuted"></i>
        </div>
        <div class="flex flex-col min-w-0">
          <a href="{{ p.original_url }}" target="_blank" class="text-sm font-semibold text-app-textMain hover:text-app-primary truncate transition-colors" title="{{ p.source_name }}">{{ p.source_name }}</a>
          <div class="text-xs text-app-textMuted truncate">{{ p.posted_at_fmt or p.created_at_fmt }}</div>
        </div>
      </div>

      <div class="space-y-1 mt-1">
        <div class="flex justify-between text-xs">
          <span class="text-app-textMuted">AI Оценка:</span>
          <span class="font-mono text-white font-medium">{{ p.qualification_score or "?" }}/10</span>
        </div>
      </div>

      {% if p.publication_platforms %}
      <div class="mt-2 pt-3 border-t border-app-border/50">
        <div class="text-xs text-app-textMuted mb-2 font-semibold">Куда публикуем:</div>
        <div class="flex flex-wrap gap-1">
          {% for pub in p.publication_platforms %}
            {% if pub.url %}
              <a href="{{ pub.url }}" target="_blank" class="badge badge-info hover:bg-blue-500/20 transition-colors" title="{{ pub.error or pub.status_label }}">
                {{ pub.label }} <i data-lucide="external-link" class="w-3 h-3 ml-1"></i>
              </a>
            {% elif pub.status == 'published' %}
              <span class="badge badge-info" title="{{ pub.error or pub.status_label }}">
                {{ pub.label }}
              </span>
            {% else %}
              <span class="badge {% if pub.status == 'error' %}badge-error{% else %}badge-neutral{% endif %}" title="{{ pub.error or pub.status_label }}">
                {{ pub.label }}
              </span>
            {% endif %}
          {% endfor %}
        </div>
      </div>
      {% endif %}
    </div>

    <!-- Right: Edit Area & Spoilers -->
    <div class="flex-1 flex flex-col min-w-0 p-5">
      
      <!-- Photos (Moved above text, larger preview, alpine modal gallery) -->
      {% if p.media_items %}
      {% set photo_urls = [] %}
      {% for m in p.media_items %}
        {% if m.type == 'photo' and m.url %}
          {% set _ = photo_urls.append(m.url) %}
        {% endif %}
      {% endfor %}
      
      <div class="mb-4" x-data="{ galleryOpen: false, activeIdx: 0, images: {{ photo_urls | tojson | forceescape }} }" 
           @keydown.escape.window="galleryOpen = false"
           @keydown.left.window="if(galleryOpen && images.length > 1) activeIdx = (activeIdx === 0) ? images.length - 1 : activeIdx - 1"
           @keydown.right.window="if(galleryOpen && images.length > 1) activeIdx = (activeIdx === images.length - 1) ? 0 : activeIdx + 1">
        
        <div class="flex flex-wrap gap-2">
          {% for m in p.media_items %}
            {% if m.type == "photo" and m.url %}
              {% set photo_idx = photo_urls.index(m.url) %}
              <div @click="activeIdx = {{ photo_idx }}; galleryOpen = true" class="block w-32 h-32 rounded-lg overflow-hidden border border-app-border hover:border-app-primary transition-colors cursor-pointer">
                <img src="{{ m.url }}" class="w-full h-full object-cover" loading="lazy">
              </div>
            {% elif m.url %}
              <a href="{{ m.url }}" target="_blank" class="w-32 h-32 rounded-lg bg-app-bg border border-app-border flex items-center justify-center hover:text-app-primary transition-colors text-app-textMuted">
                <i data-lucide="play-circle" class="w-10 h-10"></i>
              </a>
            {% endif %}
          {% endfor %}
        </div>

        <!-- Alpine Modal Gallery -->
        <div x-show="galleryOpen" style="display: none;" x-transition.opacity class="fixed inset-0 z-[100] flex items-center justify-center bg-black/90 backdrop-blur-sm p-4">
          <!-- Close button -->
          <button @click.prevent="galleryOpen = false" type="button" class="absolute top-4 right-4 text-white hover:text-app-primary transition-colors p-2">
            <svg xmlns="http://www.w3.org/2000/svg" class="w-8 h-8" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path stroke-linecap="round" stroke-linejoin="round" d="M6 18L18 6M6 6l12 12" /></svg>
          </button>
          
          <!-- Previous -->
          <button x-show="images.length > 1" @click.prevent="activeIdx = (activeIdx === 0) ? images.length - 1 : activeIdx - 1" type="button" class="absolute left-4 top-1/2 -translate-y-1/2 text-white hover:text-app-primary p-2">
            <svg xmlns="http://www.w3.org/2000/svg" class="w-10 h-10" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path stroke-linecap="round" stroke-linejoin="round" d="M15 19l-7-7 7-7" /></svg>
          </button>

          <!-- Image -->
          <img :src="images[activeIdx]" class="max-w-full max-h-[90vh] object-contain rounded-lg shadow-2xl">
          
          <!-- Next -->
          <button x-show="images.length > 1" @click.prevent="activeIdx = (activeIdx === images.length - 1) ? 0 : activeIdx + 1" type="button" class="absolute right-4 top-1/2 -translate-y-1/2 text-white hover:text-app-primary p-2">
            <svg xmlns="http://www.w3.org/2000/svg" class="w-10 h-10" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path stroke-linecap="round" stroke-linejoin="round" d="M9 5l7 7-7 7" /></svg>
          </button>
          
          <!-- Counter -->
          <div x-show="images.length > 1" class="absolute bottom-4 left-1/2 -translate-x-1/2 text-white font-mono text-sm bg-black/50 px-3 py-1 rounded-full">
            <span x-text="activeIdx + 1"></span> / <span x-text="images.length"></span>
          </div>
        </div>
      </div>
      {% endif %}

      <!-- Edit Area (Auto resize textarea) -->
      <label class="block text-xs font-bold text-app-textMuted mb-2 uppercase tracking-wider">Финальный текст</label>
      <textarea name="final_text" 
                x-data="{ resize() { $el.style.height = 'auto'; $el.style.height = $el.scrollHeight + 'px' } }" 
                x-init="resize()" 
                @input="resize()"
                class="textarea w-full font-sans text-sm leading-relaxed resize-none overflow-hidden p-3 bg-app-bg border border-app-border min-h-[150px]" 
                placeholder="Напишите идеальный пост здесь...">{{ p.review_text }}</textarea>
      
      <!-- Meta Inputs row -->
      <div class="grid grid-cols-1 md:grid-cols-3 gap-4 mt-4">
        <div>
          <label class="block text-xs font-bold text-app-textMuted mb-1">Категория</label>
          <select name="final_category" class="select select-sm w-full bg-app-bg">
            {% for category in categories %}
            <option value="{{ category.name }}" data-tag="{{ category.tag }}" {% if p.review_category == category.name %}selected{% endif %}>{{ category.name }}</option>
            {% endfor %}
            {% set category_names = categories | map(attribute="name") | list %}
            {% if p.review_category and p.review_category not in category_names %}
            <option value="{{ p.review_category }}" selected>{{ p.review_category }} · старая</option>
            {% endif %}
          </select>
        </div>
        <div>
          <label class="block text-xs font-bold text-app-textMuted mb-1">Тег источника</label>
          <input type="text" name="final_source_tag" value="{{ p.review_source_tag or p.source_tag or '' }}" class="input input-sm w-full bg-app-bg">
        </div>
        <div>
          <label class="block text-xs font-bold text-app-textMuted mb-1">Доп. Медиа</label>
          <input type="file" name="media_files" class="block w-full text-xs text-app-textMuted file:mr-2 file:py-1 file:px-2 file:rounded file:border-0 file:text-xs file:font-semibold file:bg-app-border file:text-white hover:file:bg-app-borderFocus cursor-pointer border border-app-border bg-app-bg rounded-md" accept="image/*,video/*,.pdf,.doc,.docx" multiple>
        </div>
      </div>
      
      <!-- Original / AI Spoiler -->
      <div class="mt-4">
        <details class="group/details">
          <summary class="flex items-center gap-2 text-xs font-semibold tracking-wide text-app-textMuted hover:text-white cursor-pointer select-none">
            <i data-lucide="chevron-right" class="w-4 h-4 transition-transform group-open/details:rotate-90"></i>
            ПОСМОТРЕТЬ ИСХОДНИК И AI-ПРЕДЛОЖЕНИЕ
          </summary>
          <div class="mt-3 grid grid-cols-1 xl:grid-cols-2 gap-4 bg-app-bg/50 rounded-lg p-4 border border-app-border text-sm">
            <div>
              <div class="text-xs text-app-textMuted font-bold mb-2 uppercase tracking-wider">Оригинальный текст</div>
              <div class="whitespace-pre-wrap text-app-textMain/80 font-mono text-xs leading-relaxed max-h-[300px] overflow-y-auto">{{ p.raw_text }}</div>
            </div>
            <div>
              <div class="text-xs text-app-primary font-bold mb-2 uppercase tracking-wider">AI-Предложение</div>
              <div class="whitespace-pre-wrap text-app-textMain/90 font-mono text-xs leading-relaxed max-h-[300px] overflow-y-auto">{{ p.rewritten_text }}</div>
              
              <div class="text-xs text-app-textMuted font-bold mt-4 mb-2 uppercase tracking-wider">AI Заметки / Резолюция</div>
              <div class="text-app-textMain/80 whitespace-pre-wrap italic">{{ p.rewrite_notes or p.qualification_reason or "—" }}</div>
              
              <div class="mt-4">
                <label class="block text-xs font-bold text-app-textMuted mb-1 uppercase tracking-wider">Заметка редактора (внутренняя)</label>
                <input type="text" name="editor_notes" value="{{ p.editor_notes or '' }}" class="input input-sm w-full text-app-warning placeholder:text-app-warning/50 bg-app-bg">
              </div>
            </div>
          </div>
        </details>
      </div>
      
      <!-- Actions -->
      {% if p.editorial_status != 'published' %}
      <div class="mt-5 pt-4 border-t border-app-border flex flex-wrap items-center justify-between gap-3">
        {% if p.editorial_status == 'rejected' %}
          <div>
            <button class="btn btn-ghost btn-sm text-app-warning hover:bg-app-warning/10 hover:text-app-warning" type="button" 
                    hx-post="/editor/{{ p.id }}/return" hx-target="#post-container-{{ p.id }}" hx-swap="outerHTML" 
                    hx-vals='{"csrf_token": "{{ user.csrf_token }}"}'>
              <i data-lucide="corner-up-left" class="w-4 h-4"></i> Вернуть на проверку
            </button>
          </div>
        {% else %}
          <!-- Delete Button -->
          <div>
            <button class="btn btn-ghost btn-sm text-app-error hover:bg-app-errorBg hover:text-app-error" type="button" 
                    hx-post="/editor/{{ p.id }}/reject" hx-target="#post-container-{{ p.id }}" hx-swap="outerHTML" 
                    hx-vals='{"csrf_token": "{{ user.csrf_token }}"}'
                    onclick="return confirm('Отклонить пост?')">
              <i data-lucide="x" class="w-4 h-4"></i> Отклонить
            </button>
          </div>
          
          <div class="flex gap-2">
            <button type="submit" name="action" value="save" class="btn btn-surface btn-sm">
              <i data-lucide="save" class="w-4 h-4"></i> Сохранить как черновик
            </button>
            <button type="submit" name="action" value="accept" class="btn btn-primary btn-sm">
              <i data-lucide="send" class="w-4 h-4"></i> Сохранить и Опубликовать
            </button>
          </div>
        {% endif %}
      </div>
      {% endif %}
    </div>
  </div>
</form>
