{# ── Error banner ── #}
{% if save_error %}
  <div class="max-w-[768px] mx-auto mt-[16px] rounded-[8px] border border-red-300 bg-red-50 px-[16px] py-[12px] text-[14px] text-red-700">
    <strong>Save failed:</strong> {{ save_error }}
  </div>
{% endif %}

<form id="post-edit-form" method="post" class="max-w-[768px] mx-auto pb-[48px]">
  <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
  <input type="hidden" name="updated_at" value="{{ ghost_post.updated_at if ghost_post else '' }}">
  <input type="hidden" id="lexical-json-input" name="lexical" value="">
  <input type="hidden" id="feature-image-input" name="feature_image" value="{{ ghost_post.feature_image or '' if ghost_post else '' }}">
  <input type="hidden" id="feature-image-caption-input" name="feature_image_caption" value="{{ ghost_post.feature_image_caption or '' if ghost_post else '' }}">

  {# ── Feature image ── #}
  <div id="feature-image-container" class="relative mt-[16px] mb-[24px] group">
    {# Empty state: add link #}
    <div
      id="feature-image-empty"
      class="{{ 'hidden' if ghost_post and ghost_post.feature_image else '' }}"
    >
      <button
        type="button"
        id="feature-image-add-btn"
        class="text-[14px] text-stone-400 hover:text-stone-600 transition-colors cursor-pointer"
      >+ Add feature image</button>
    </div>

    {# Filled state: image preview + controls #}
    <div
      id="feature-image-filled"
      class="relative {{ '' if ghost_post and ghost_post.feature_image else 'hidden' }}"
    >
      <img
        id="feature-image-preview"
        src="{{ ghost_post.feature_image or '' if ghost_post else '' }}"
        alt=""
        class="w-full max-h-[448px] object-cover rounded-[8px] cursor-pointer"
      >
      {# Delete button (top-right, visible on hover) #}
      <button
        type="button"
        id="feature-image-delete-btn"
        class="absolute top-[8px] right-[8px] w-[32px] h-[32px] rounded-full bg-black/50 text-white
               flex items-center justify-center opacity-0 group-hover:opacity-100
               transition-opacity hover:bg-black/70 cursor-pointer text-[14px]"
        title="Remove feature image"
      ><i class="fa-solid fa-trash-can"></i></button>

      {# Caption input #}
      <input
        type="text"
        id="feature-image-caption"
        value="{{ ghost_post.feature_image_caption or '' if ghost_post else '' }}"
        placeholder="Add a caption..."
        class="mt-[8px] w-full text-[14px] text-stone-500 bg-transparent border-none
               outline-none placeholder:text-stone-300 focus:text-stone-700"
      >
    </div>

    {# Upload spinner overlay #}
    <div id="feature-image-uploading" class="hidden flex items-center gap-[8px] mt-[8px] text-[14px] text-stone-400">
      <i class="fa-solid fa-spinner fa-spin"></i> Uploading...
    </div>

    {# Hidden file input #}
    <input
      type="file"
      id="feature-image-file"
      accept="image/jpeg,image/png,image/gif,image/webp,image/svg+xml"
      class="hidden"
    >
  </div>

  {# ── Title ── #}
  <input
    type="text"
    name="title"
    value="{{ ghost_post.title if ghost_post else '' }}"
    placeholder="Post title..."
    class="w-full text-[36px] font-bold bg-transparent border-none outline-none
           placeholder:text-stone-300 mb-[8px] leading-tight"
  >

  {# ── Excerpt ── #}
  <textarea
    name="custom_excerpt"
    rows="1"
    placeholder="Add an excerpt..."
    class="w-full text-[18px] text-stone-500 bg-transparent border-none outline-none
           placeholder:text-stone-300 resize-none mb-[24px] leading-relaxed"
  >{{ ghost_post.custom_excerpt or '' if ghost_post else '' }}</textarea>

  {# ── Editor mount point ── #}
  <div id="lexical-editor" class="relative w-full bg-transparent"></div>

  {# ── Initial Lexical JSON from Ghost ── #}
  <script id="lexical-initial-data" type="application/json">
    {{ (ghost_post.lexical or '{"root":{"children":[{"children":[],"direction":null,"format":"","indent":0,"type":"paragraph","version":1}],"direction":null,"format":"","indent":0,"type":"root","version":1}}')|safe }}
  </script>

  {# ── Status + Publish mode + Save footer ── #}
  {% set already_emailed = ghost_post and ghost_post.email and ghost_post.email.status %}
  <div class="flex flex-wrap items-center gap-[16px] mt-[32px] pt-[16px] border-t border-stone-200">
    <select
      id="status-select"
      name="status"
      class="text-[14px] rounded-[4px] border border-stone-200 px-[8px] py-[6px] bg-white text-stone-600"
    >
      <option value="draft" {{ 'selected' if not ghost_post or ghost_post.status == 'draft' else '' }}>Draft</option>
      <option value="published" {{ 'selected' if ghost_post and ghost_post.status == 'published' else '' }}>Published</option>
    </select>

    {# Publish mode — only relevant when publishing #}
    <select
      id="publish-mode-select"
      name="publish_mode"
      class="text-[14px] rounded-[4px] border border-stone-200 px-[8px] py-[6px] bg-white text-stone-600
             {{ 'hidden' if not ghost_post or ghost_post.status != 'published' else '' }}
             {{ 'opacity-50 pointer-events-none' if already_emailed else '' }}"
      {{ 'disabled' if already_emailed else '' }}
    >
      <option value="web" selected>Web only</option>
      <option value="email">Email only</option>
      <option value="both">Web + Email</option>
    </select>

    {# Newsletter picker — only when email is involved #}
    <select
      id="newsletter-select"
      name="newsletter_slug"
      class="text-[14px] rounded-[4px] border border-stone-200 px-[8px] py-[6px] bg-white text-stone-600 hidden"
      {{ 'disabled' if already_emailed else '' }}
    >
      <option value="">Select newsletter…</option>
      {% for nl in newsletters|default([]) %}
        <option value="{{ nl.slug }}">{{ nl.name }}</option>
      {% endfor %}
    </select>

    <button
      type="submit"
      class="px-[20px] py-[6px] bg-stone-700 text-white text-[14px] rounded-[8px]
             hover:bg-stone-800 transition-colors cursor-pointer"
    >Save</button>

    {% if save_success %}
      <span class="text-[14px] text-green-600">Saved.</span>
    {% endif %}
    {% if request.args.get('publish_requested') %}
      <span class="text-[14px] text-blue-600">Publish requested — an admin will review.</span>
    {% endif %}
    {% if post and post.publish_requested %}
      <span class="inline-block px-2 py-0.5 rounded-full text-xs font-semibold bg-blue-100 text-blue-800">Publish requested</span>
    {% endif %}
    {% if already_emailed %}
      <span class="inline-block px-2 py-0.5 rounded-full text-xs font-semibold bg-green-100 text-green-800">
        Emailed{% if ghost_post.newsletter %} to {{ ghost_post.newsletter.name }}{% endif %}
      </span>
    {% endif %}
  </div>

  {# ── Publish-mode show/hide logic ── #}
  <script>
  (function() {
    var statusSel   = document.getElementById('status-select');
    var modeSel     = document.getElementById('publish-mode-select');
    var nlSel       = document.getElementById('newsletter-select');
    var alreadyEmailed = {{ 'true' if already_emailed else 'false' }};

    function sync() {
      var isPublished = statusSel.value === 'published';
      // Show publish mode only when status is published and not already emailed
      if (isPublished && !alreadyEmailed) {
        modeSel.classList.remove('hidden');
      } else {
        modeSel.classList.add('hidden');
      }
      // Show newsletter picker when email is involved
      var needsEmail = isPublished && !alreadyEmailed && (modeSel.value === 'email' || modeSel.value === 'both');
      if (needsEmail) {
        nlSel.classList.remove('hidden');
      } else {
        nlSel.classList.add('hidden');
      }
    }

    statusSel.addEventListener('change', sync);
    modeSel.addEventListener('change', sync);
    sync();
  })();
  </script>
</form>

{# ── Koenig editor assets ── #}
<link rel="stylesheet" href="{{ asset_url('scripts/editor.css') }}">
<style>
  /* Koenig CSS uses rem, designed for Ghost Admin's html{font-size:62.5%}.
     We apply that via JS (see init() below) so the header bars render at
     normal size on first paint, then shrink only the editor area.
     A beforeSwap listener restores the default when navigating away. */
  #lexical-editor { display: flow-root; }
  /* Reset floats inside HTML cards to match Ghost Admin behaviour */
  #lexical-editor [data-kg-card="html"] * { float: none !important; }
  #lexical-editor [data-kg-card="html"] table { width: 100% !important; }
</style>
<script src="{{ asset_url('scripts/editor.js') }}"></script>
<script>
(function() {
  /* ── Koenig rem fix: apply 62.5% root font-size for the editor,
     restore default when navigating away via HTMX ── */
  function applyEditorFontSize() {
    document.documentElement.style.fontSize = '62.5%';
    document.body.style.fontSize = '1.6rem';
  }
  function restoreDefaultFontSize() {
    document.documentElement.style.fontSize = '';
    document.body.style.fontSize = '';
  }
  applyEditorFontSize();
  document.body.addEventListener('htmx:beforeSwap', function cleanup(e) {
    if (e.detail.target && e.detail.target.id === 'main-panel') {
      restoreDefaultFontSize();
      document.body.removeEventListener('htmx:beforeSwap', cleanup);
    }
  });

  function init() {
    var csrfToken = document.querySelector('input[name="csrf_token"]').value;
    var uploadUrl = '{{ url_for("blog.editor_api.upload_image") }}';
    var uploadUrls = {
      image: uploadUrl,
      media: '{{ url_for("blog.editor_api.upload_media") }}',
      file:  '{{ url_for("blog.editor_api.upload_file") }}',
    };

    /* ── Feature image upload / delete / replace ── */
    var fileInput     = document.getElementById('feature-image-file');
    var addBtn        = document.getElementById('feature-image-add-btn');
    var deleteBtn     = document.getElementById('feature-image-delete-btn');
    var preview       = document.getElementById('feature-image-preview');
    var emptyState    = document.getElementById('feature-image-empty');
    var filledState   = document.getElementById('feature-image-filled');
    var hiddenUrl     = document.getElementById('feature-image-input');
    var hiddenCaption = document.getElementById('feature-image-caption-input');
    var captionInput  = document.getElementById('feature-image-caption');
    var uploading     = document.getElementById('feature-image-uploading');

    function showFilled(url) {
      preview.src = url;
      hiddenUrl.value = url;
      emptyState.classList.add('hidden');
      filledState.classList.remove('hidden');
      uploading.classList.add('hidden');
    }

    function showEmpty() {
      preview.src = '';
      hiddenUrl.value = '';
      hiddenCaption.value = '';
      captionInput.value = '';
      emptyState.classList.remove('hidden');
      filledState.classList.add('hidden');
      uploading.classList.add('hidden');
    }

    function uploadFile(file) {
      emptyState.classList.add('hidden');
      uploading.classList.remove('hidden');
      var fd = new FormData();
      fd.append('file', file);
      fetch(uploadUrl, {
        method: 'POST',
        body: fd,
        headers: { 'X-CSRFToken': csrfToken },
      })
      .then(function(r) {
        if (!r.ok) throw new Error('Upload failed (' + r.status + ')');
        return r.json();
      })
      .then(function(data) {
        var url = data.images && data.images[0] && data.images[0].url;
        if (url) showFilled(url);
        else { showEmpty(); alert('Upload succeeded but no image URL returned.'); }
      })
      .catch(function(e) {
        showEmpty();
        alert(e.message);
      });
    }

    addBtn.addEventListener('click', function() { fileInput.click(); });
    preview.addEventListener('click', function() { fileInput.click(); });
    deleteBtn.addEventListener('click', function(e) {
      e.stopPropagation();
      showEmpty();
    });
    fileInput.addEventListener('change', function() {
      if (fileInput.files && fileInput.files[0]) {
        uploadFile(fileInput.files[0]);
        fileInput.value = '';
      }
    });
    captionInput.addEventListener('input', function() {
      hiddenCaption.value = captionInput.value;
    });

    /* ── Auto-resize excerpt textarea ── */
    var excerpt = document.querySelector('textarea[name="custom_excerpt"]');
    function autoResize() {
      excerpt.style.height = 'auto';
      excerpt.style.height = excerpt.scrollHeight + 'px';
    }
    excerpt.addEventListener('input', autoResize);
    autoResize();

    /* ── Mount Koenig editor ── */
    var dataEl = document.getElementById('lexical-initial-data');
    var initialJson = dataEl ? dataEl.textContent.trim() : null;
    if (initialJson) {
      var hidden = document.getElementById('lexical-json-input');
      if (hidden) hidden.value = initialJson;
    }
    window.mountEditor('lexical-editor', {
      initialJson: initialJson,
      csrfToken: csrfToken,
      uploadUrls: uploadUrls,
      oembedUrl: '{{ url_for("blog.editor_api.oembed_proxy") }}',
      unsplashApiKey: '{{ unsplash_api_key or "" }}',
      snippetsUrl: '{{ url_for("blog.editor_api.list_snippets") }}',
    });

    /* ── Ctrl-S / Cmd-S to save ── */
    document.addEventListener('keydown', function(e) {
      if ((e.ctrlKey || e.metaKey) && e.key === 's') {
        e.preventDefault();
        document.getElementById('post-edit-form').requestSubmit();
      }
    });
  }

  /* editor.js loads synchronously on full page loads but asynchronously
     when HTMX swaps the content in, so wait for it if needed. */
  if (typeof window.mountEditor === 'function') {
    init();
  } else {
    var _t = setInterval(function() {
      if (typeof window.mountEditor === 'function') { clearInterval(_t); init(); }
    }, 50);
  }
})();
</script>
