<!DOCTYPE html>
<html
        xmlns:th="http://www.thymeleaf.org"
        xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
        xmlns:sec="http://www.thymeleaf.org/extras/spring-security"
        layout:decorate="~{layout/default_layout}"
>
<head>
    <th:block layout:fragment="head">
    </th:block>
</head>
<th:block layout:fragment="content" id="content">
    <section class="wrapper style1">
        <div class="container">
            <div class="row justify-content-center">
                <div class="col-12">
                    <div id="content_inner">
                        <article>
                            <header class="major" th:if="${filterTitle}">
                                <h2 th:text="${filterTitle}">필터링된 게시물</h2>
                                <p><a th:href="@{/blog/posts}">모든 글 보기</a></p>
                            </header>
                            <th:block th:each="post, iterStat : ${postsPage.content}">
                                <section th:id="'post-section-' + ${post.id}">
                                    <div class="box post" th:id="${post.id}">
                                        <a href="javascript:void(0);" th:onclick="'goToViewer(this.parentNode)'" class="image left">
                                            <img th:src="${post.thumb != null and not #strings.isEmpty(post.thumb)} ? ${apiBaseUrl + post.thumb} : @{/images/pic01.jpg}"
                                                 alt="Post Thumbnail"
                                                 th:onerror="|this.onerror=null; this.src='@{/images/bum.png}';|" />
                                        </a>
                                        <div class="inner">
                                            <h3 style="display: flex; justify-content: space-between; align-items: center;">
                                                <span>
                                                    <span th:if="${!post.posting}" style="background-color: #888; color: white; font-size: 0.7em; padding: 2px 6px; border-radius: 4px; margin-right: 8px; vertical-align: middle;">
                                                        비공개
                                                    </span>
                                                    <span th:text="${post.title != null and not #strings.isEmpty(post.title)} ? ${post.title} : 'untitled[' + ${#temporals.format(T(java.time.Instant).ofEpochMilli(post.writeTime).atZone(T(java.time.ZoneId).systemDefault()).toLocalDateTime(), 'yyyy-MM-dd HH:mm')} + ']'"></span>
                                                </span>
                                                <span style="font-size: 0.75em; color: #888; font-weight: normal; white-space: nowrap; margin-left: 1em;">
                                                    (읽음: <span th:text="${post.readCount}">0</span>)
                                                </span>
                                            </h3>
                                            <p style="font-size: 0.9em; color: #555; margin-bottom: 0.5em;" th:text="${'by ' + post.writer}"></p>
                                            <p th:text="${#strings.abbreviate(post.html, 80)}" class="ellipsis"></p>
                                        </div>
                                        <footer sec:authorize="isAuthenticated()"
                                                th:if="${#authentication.name == post.writer or #authorization.expression('hasRole(''ADMIN'')')}"
                                                style="text-align: right; margin-top: 1em;">
                                            <a th:href="@{/blog/edit/{postId}(postId=${post.id})}" class="button small">수정</a>
                                            <button class="button small alt" th:onclick="handleDeletePostInList([[${post.id}]], event)">삭제</button>
                                        </footer>
                                    </div>
                                </section>

                                <th:block th:if="${iterStat.count % 3 == 0}">
                                    <section>
                                        <div class="box ad-container" style="padding: 2em; text-align: center;">
                                            <p style="margin-bottom: 1em; color: #888;">- Advertisement -</p>
                                            <ins class="adsbygoogle"
                                                 style="display:block"
                                                 data-ad-client="ca-pub-9504446465764716"
                                                 data-ad-slot="5334609005"
                                                 data-ad-format="auto"
                                                 data-full-width-responsive="true"></ins>
                                            <script>
                                                (adsbygoogle = window.adsbygoogle || []).push({});
                                            </script>
                                        </div>
                                    </section>
                                </th:block>
                            </th:block>
                        </article>

                        <nav aria-label="Page navigation" th:if="${postsPage.totalPages > 1}" style="text-align: center; margin-top: 2.5em; font-size: 0.9em;">
                            <ul class="pagination" style="display: inline-block; padding-left: 0; list-style: none; border-radius: 5px; border: 1px solid #e0e0e0; overflow: hidden;">
                                <li th:styleappend="${postsPage.isFirst()} ? 'opacity: 0.5; pointer-events: none;' : ''" style="display: inline; float: left;">
                                    <a th:href="${postsPage.isFirst()} ? '#' : @{/blog/posts(page=${postsPage.number - 1}, category=${currentCategory}, tag=${currentTag})}"
                                       class="button alt small" style="border-radius:0; margin:0; border-right: 1px solid #e0e0e0;">
                                        &laquo; Prev
                                    </a>
                                </li>
                                <li th:each="pageNum : ${#numbers.sequence(0, postsPage.totalPages - 1)}"
                                    style="display: inline; float: left; border-right: 1px solid #e0e0e0;">
                                    <a th:href="@{/blog/posts(page=${pageNum}, category=${currentCategory}, tag=${currentTag})}"
                                       th:text="${pageNum + 1}"
                                       th:class="${pageNum == postsPage.number} ? 'button small' : 'button alt small'"
                                       style="border-radius:0; margin:0;">
                                    </a>
                                </li>
                                <li th:styleappend="${postsPage.isLast()} ? 'opacity: 0.5; pointer-events: none;'" style="display: inline; float: left;">
                                    <a th:href="${postsPage.isLast()} ? '#' : @{/blog/posts(page=${postsPage.number + 1}, category=${currentCategory}, tag=${currentTag})}"
                                       class="button alt small" style="border-radius:0; margin:0;">
                                        Next &raquo;
                                    </a>
                                </li>
                            </ul>
                        </nav>
                    </div>
                </div>
            </div>
        </div>
    </section>

    <script th:inline="javascript">
        // CSRF 토큰을 meta 태그에서 읽어옴 (POST, DELETE 요청 시 필요)
        const csrfToken = document.querySelector('meta[name="_csrf"]')?.getAttribute('content');
        const csrfHeader = document.querySelector('meta[name="_csrf_header"]')?.getAttribute('content');

        /**
         * 게시물 목록에서 게시물을 삭제하는 함수
         * @param {string} postId - 삭제할 게시물의 ID
         * @param {Event} event - 클릭 이벤트 객체
         */
        function handleDeletePostInList(postId, event) {
            // 이벤트 버블링을 막아 게시물 상세보기로 이동하는 것을 방지합니다.
            event.stopPropagation();

            const cleanPostId = postId.replace(/^"|"$/g, '');
            if (confirm('이 게시물을 정말로 삭제하시겠습니까? 이 작업은 되돌릴 수 없습니다.')) {
                fetch(`/blog/post/${cleanPostId}`, {
                    method: 'DELETE',
                    headers: {
                        [csrfHeader]: csrfToken
                    }
                })
                    .then(response => {
                        if (response.ok) {
                            return response.json();
                        } else {
                            // 서버에서 에러 메시지를 보냈을 경우를 대비
                            return response.json().then(err => { throw new Error(err.message || '삭제에 실패했습니다.') });
                        }
                    })
                    .then(data => {
                        alert(data.message || '게시물이 성공적으로 삭제되었습니다.');
                        // UI에서 해당 게시물 섹션을 제거하여 즉시 반영
                        const postSection = document.getElementById(`post-section-${cleanPostId}`);
                        if (postSection) {
                            postSection.remove();
                        }
                    })
                    .catch(error => {
                        console.error('Error:', error);
                        alert('삭제 처리 중 오류가 발생했습니다: ' + error.message);
                    });
            }
        }
    </script>
</th:block>
</html>