{# ── 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-new-form" method="post" class="max-w-[768px] mx-auto pb-[48px]">
  <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
  <input type="hidden" id="lexical-json-input" name="lexical" value="">
  <input type="hidden" id="feature-image-input" name="feature_image" value="">
  <input type="hidden" id="feature-image-caption-input" name="feature_image_caption" value="">

  {# ── Feature image ── #}
  <div id="feature-image-container" class="relative mt-[16px] mb-[24px] group">
    {# Empty state: add link #}
    <div id="feature-image-empty">
      <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 hidden">
      <img
        id="feature-image-preview"
        src=""
        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=""
        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=""
    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"
  ></textarea>

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

  {# ── Status + Save footer ── #}
  <div class="flex items-center gap-[16px] mt-[32px] pt-[16px] border-t border-stone-200">
    <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>Draft</option>
      <option value="published">Published</option>
    </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"
    >Create Post</button>
  </div>
</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.  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 ── */
    window.mountEditor('lexical-editor', {
      initialJson: null,
      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-new-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>
