<%@ page contentType="text/html;charset=UTF-8" pageEncoding="UTF-8" language="java" %>
<%@ page import="org.springframework.web.util.HtmlUtils" %>
<%@ page import="com.pandoli365.bibimbap.data.PostData" %>
<%@ page import="com.pandoli365.bibimbap.data.PostCategoryData" %>
<%@ page import="java.util.Collections" %>
<%@ page import="java.util.List" %>
<%
    String ctx = request.getContextPath();
    String mode = (String) request.getAttribute("mode");
    boolean isEdit = "edit".equals(mode);
    PostData post = (PostData) request.getAttribute("post");
    List<PostCategoryData> categories = Collections.emptyList();
    Object categoriesAttr = request.getAttribute("categories");
    if (categoriesAttr instanceof List<?>) { categories = (List<PostCategoryData>) categoriesAttr; }
    String csrfToken = (String) request.getAttribute("csrfToken");
    String csrfTokenHtml = HtmlUtils.htmlEscape(csrfToken == null ? "" : csrfToken);

    Long postId = post == null ? null : post.getId();
    Long postCategoryId = post == null ? null : post.getCategoryId();
    String postTitle = post == null || post.getTitle() == null ? "" : post.getTitle();
    String postBodyMarkdown = post == null || post.getBodyMarkdown() == null ? "" : post.getBodyMarkdown();
    String postLinkUrl = post == null || post.getLinkUrl() == null ? "" : post.getLinkUrl();
    String postStatus = post == null ? null : post.getStatus();
    boolean isDraft = "DRAFT".equals(postStatus);
%>
<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <jsp:include page="/WEB-INF/views/theme-init.jsp"/>
    <title><%= isEdit ? "포스트 수정" : "포스트 작성" %> | bibimbap</title>
    <style>
      html {
        color-scheme: light;
        --surface: #faf8f5;
        --card-bg: #fff;
        --text: #1a1a1a;
        --text-muted: #5c5c5c;
        --accent: #e8a54b;
        --accent-soft: rgba(232, 165, 75, 0.16);
        --border: rgba(0, 0, 0, 0.08);
        --shadow: rgba(0, 0, 0, 0.06);
        --field-bg: #fff;
      }
      html[data-theme="dark"] {
        color-scheme: dark;
        --surface: #121212;
        --card-bg: #1e1e1e;
        --text: #ece8e1;
        --text-muted: #a39e96;
        --border: rgba(255, 255, 255, 0.1);
        --shadow: rgba(0, 0, 0, 0.35);
        --field-bg: #181818;
      }
      body {
        margin: 0;
        min-height: 100vh;
        font-family: system-ui, -apple-system, "Segoe UI", Roboto, "Noto Sans KR", sans-serif;
        background: var(--surface);
        color: var(--text);
      }
      .form-page {
        max-width: 48rem;
        margin: 0 auto;
        padding: 1.5rem max(1rem, env(safe-area-inset-left)) 3rem max(1rem, env(safe-area-inset-right));
      }
      .form-heading {
        margin-bottom: 1rem;
      }
      .form-heading__eyebrow {
        margin: 0 0 0.35rem;
        color: var(--accent);
        font-size: 0.75rem;
        font-weight: 900;
      }
      .form-heading h1 {
        margin: 0;
        font-size: 1.85rem;
        line-height: 1.2;
        letter-spacing: 0;
      }
      .post-form {
        padding: 1.35rem;
        border: 1px solid var(--border);
        border-radius: 12px;
        background: var(--card-bg);
        box-shadow: 0 2px 8px var(--shadow);
      }
      .field {
        display: grid;
        gap: 0.4rem;
        margin-bottom: 0.9rem;
      }
      .field label {
        color: var(--text);
        font-size: 0.8125rem;
        font-weight: 900;
      }
      .field input,
      .field select,
      .field textarea {
        width: 100%;
        box-sizing: border-box;
        border: 1px solid var(--border);
        border-radius: 10px;
        background: var(--field-bg);
        color: var(--text);
        font: inherit;
        font-size: 0.9375rem;
      }
      .field input,
      .field select {
        height: 2.85rem;
        padding: 0 0.8rem;
      }
      .field textarea {
        min-height: 16rem;
        padding: 0.8rem;
        line-height: 1.6;
        resize: vertical;
        font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
      }
      .field input:focus,
      .field select:focus,
      .field textarea:focus {
        outline: none;
        border-color: var(--accent);
        box-shadow: 0 0 0 3px rgba(232, 165, 75, 0.22);
      }
      .form-actions {
        margin-top: 1rem;
        display: flex;
        justify-content: flex-end;
        gap: 0.6rem;
      }
      .form-button {
        min-height: 2.75rem;
        padding: 0 1rem;
        border: 1px solid var(--border);
        border-radius: 10px;
        display: inline-flex;
        align-items: center;
        justify-content: center;
        background: var(--card-bg);
        color: var(--text);
        font-size: 0.9375rem;
        font-weight: 900;
        text-decoration: none;
        cursor: pointer;
      }
      .form-button--primary {
        border-color: transparent;
        background: var(--accent);
        color: #1a1a1a;
      }
    </style>
</head>
<body>
    <jsp:include page="/WEB-INF/views/header.jsp"/>
    <main class="form-page">
        <section class="form-heading" aria-labelledby="form-title">
            <p class="form-heading__eyebrow">POSTING</p>
            <h1 id="form-title"><%= isEdit ? "포스트 수정" : "포스트 작성" %></h1>
        </section>

        <section class="post-form" aria-label="포스트 입력">
            <form id="post-form" novalidate>
                <input type="hidden" name="_csrf" value="<%= csrfTokenHtml %>">
                <div class="field">
                    <label for="categoryId">카테고리</label>
                    <select id="categoryId" name="categoryId" required>
                        <option value="">카테고리 선택</option>
                        <% for (PostCategoryData cat : categories) { %>
                            <option value="<%= cat.getId() %>" <%= postCategoryId != null && postCategoryId.equals(cat.getId()) ? "selected" : "" %>><%= HtmlUtils.htmlEscape(cat.getName() == null ? "" : cat.getName()) %></option>
                        <% } %>
                    </select>
                </div>
                <div class="field">
                    <label for="title">제목</label>
                    <input id="title" name="title" type="text" maxlength="200" value="<%= HtmlUtils.htmlEscape(postTitle) %>" placeholder="제목을 입력해 주세요." required>
                </div>
                <div class="field">
                    <label for="bodyMarkdown">본문 (Markdown)</label>
                    <textarea id="bodyMarkdown" name="bodyMarkdown" maxlength="20000" placeholder="마크다운으로 작성해 주세요."><%= HtmlUtils.htmlEscape(postBodyMarkdown) %></textarea>
                </div>
                <div class="field">
                    <label for="linkUrl">링크 URL</label>
                    <input id="linkUrl" name="linkUrl" type="url" maxlength="2048" value="<%= HtmlUtils.htmlEscape(postLinkUrl) %>" placeholder="https://example.com (선택)">
                </div>
                <div class="field">
                    <label for="status">공개 상태</label>
                    <select id="status" name="status">
                        <option value="PUBLISHED" <%= isDraft ? "" : "selected" %>>공개</option>
                        <option value="DRAFT" <%= isDraft ? "selected" : "" %>>비공개(임시저장)</option>
                    </select>
                </div>
                <div class="form-actions">
                    <a class="form-button" href="<%= ctx %>/posts">취소</a>
                    <button class="form-button form-button--primary" type="submit"><%= isEdit ? "수정" : "등록" %></button>
                </div>
            </form>
        </section>
    </main>
    <jsp:include page="/WEB-INF/views/footer.jsp"/>
    <script>
(function () {
  var ctx = '<%= HtmlUtils.htmlEscape(ctx) %>';
  var mode = '<%= HtmlUtils.htmlEscape(mode == null ? "" : mode) %>';
  var postId = '<%= postId == null ? "" : postId %>';
  var csrfToken = '<%= csrfTokenHtml %>';
  var form = document.getElementById('post-form');
  if (!form) return;

  var action = mode === 'edit' ? ctx + '/posts/' + postId : ctx + '/posts';

  form.addEventListener('submit', function (ev) {
    ev.preventDefault();
    if (!form.checkValidity()) {
      form.reportValidity();
      return;
    }

    var baseHeaders = {
      'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
      'Accept': 'application/json',
      'X-Requested-With': 'XMLHttpRequest',
      'X-CSRF-Token': csrfToken
    };
    var headers = window.BibimbapCsrf ? window.BibimbapCsrf.headers(baseHeaders) : baseHeaders;

    var body = new URLSearchParams(new FormData(form));
    fetch(action, {
      method: 'POST',
      headers: headers,
      body: body
    }).then(function (res) {
      return res.json().catch(function () {
        return { message: '포스트를 저장하지 못했습니다.' };
      }).then(function (data) {
        if (!res.ok) {
          var error = new Error(data && data.message ? data.message : '포스트를 저장하지 못했습니다.');
          error.status = res.status;
          throw error;
        }
        return data;
      });
    }).then(function (data) {
      var go = function () {
        window.location.href = ctx + (data.location || '/posts');
      };
      if (window.BibimbapModal && typeof window.BibimbapModal.alert === 'function') {
        window.BibimbapModal.alert({
          title: mode === 'edit' ? '포스트 수정 완료' : '포스트 등록 완료',
          message: mode === 'edit' ? '포스트가 수정되었습니다.' : '포스트가 등록되었습니다.',
          confirmText: '확인',
          onConfirm: go
        });
      } else {
        go();
      }
    }).catch(function (err) {
      var message = err.message || '포스트를 저장하지 못했습니다.';
      var redirectLogin = function () {
        if (err.status === 401) {
          window.location.href = ctx + '/login';
        }
      };
      if (window.BibimbapModal && typeof window.BibimbapModal.alert === 'function') {
        window.BibimbapModal.alert({
          title: '저장 실패',
          message: message,
          confirmText: '확인',
          onConfirm: redirectLogin
        });
      } else {
        alert(message);
        redirectLogin();
      }
    });
  });
})();
    </script>
</body>
</html>
