<h1>Edit Post</h1>

<% if (forbidden) { %>
  <div class="alert alert-danger">Your role does not have permission to edit blog posts.</div>
<% } else if (!post) { %>
  <div class="alert alert-danger">Post not found.</div>
<% } else { %>

<% if (error) { %><div class="alert alert-danger"><%= error %></div><% } %>

<div class="card" style="max-width:760px">
  <p style="color:var(--muted);font-size:12px;margin-top:0">Slug <code class="mono"><%= post.slug %></code> (not editable — create a new post to change the URL) &middot; storefront URL <code class="mono">/resources/blog/<%= post.slug %></code></p>
  <form method="post" action="/marketing/blog/<%= post.id %>/edit" id="edit-post-form">
    <label>Title</label>
    <input type="text" name="title" value="<%= post.title %>" required>
    <label>Excerpt (shown on the blog list page)</label>
    <input type="text" name="excerpt" value="<%= post.excerpt || '' %>" maxlength="500">
    <label>Author</label>
    <input type="text" name="author" value="<%= post.author %>">
    <label>Tags (comma-separated)</label>
    <input type="text" name="tags" value="<%= post.tags %>">
    <label>Content</label>
    <textarea name="content" id="edit-post-content" rows="18" required><%= post.content %></textarea>
    <label><input type="checkbox" name="isPublished" value="true" <%= post.is_published ? 'checked' : '' %>> Published</label>
    <div style="display:flex;gap:12px;margin-top:16px">
      <button class="btn" type="submit" style="flex:1">Save Changes</button>
      <a href="/marketing/blog" class="btn" style="flex:1;text-align:center;background:#2a2e38">Cancel</a>
    </div>
  </form>
</div>

<script src="/assets/libs/@ckeditor/ckeditor5-build-classic/build/ckeditor.js"></script>
<script src="/js/ckeditor-helper.js"></script>
<script>
  // See posts.ejs's matching comment — same mount-then-sync-on-submit pattern.
  CkEditorField.mount('edit-post-content', { height: 320 });
  document.getElementById('edit-post-form').addEventListener('submit', () => {
    document.getElementById('edit-post-content').value = CkEditorField.getData('edit-post-content');
  });
</script>

<% } %>
