{% extends 'base.html' %}

{% block content %}
    <div class="container">
        <div class="content">
            {% if not posts %}
                <h4 style="margin-top: 100px">작성된 포스트가 없습니다.</h4>
            {% else %}
                <div class="content__inner">
                    <ul class="list__posts list__posts0">
                    </ul>
                    <ul class="list__posts list__posts1">
                    </ul>
                    <ul class="list__posts list__posts2">
                    </ul>
                </div>
                <ul class="fake__lists">
                    {% for r_post in posts %}
                        <li>
                            <a href="{{ url_for('post', post_id=r_post.id) }}">
                                <div class="lists__img">
                                    <img src="{{ r_post.thumbnail_img | default('https://via.placeholder.com/300x200', true) }}" alt="{{ r_post.title }}" onerror="this.onerror=null; this.src='https://via.placeholder.com/300x200';" />
                                </div>
                                <div class="lists__desc">
                                    <p class="lists__category">{{ r_post.category }}</p>
                                    <h3 class="lists__title">{{ r_post.title }}</h3>
                                    <p class="lists__content">
                                        {{ r_post.contents | safe }}
                                    </p>
                                    {# <p class="lists__content">{{ r_post.contents | safe }}</p> #}
                                    <p class="lists__date">
                                        <b>{{ (r_post.add_date).strftime("%b %d") }}</b> / {{ (r_post.add_date).strftime("%Y") }}
                                    </p>
                                </div>
                            </a>
                        </li>
                    {% endfor %}
                </ul>
            {% endif %}
        </div>
    </div>
    <footer>
        <div class="footer__inner">
            <div class="footer__info">
                <p class="footer__tel">
                    TEL 02-3141-1305  / 1306    E-mail  cser@wixon.co.kr  /  기업부설연구소 제 2021154317호
                </p>
                <address>
                    서울시 마포구 동교로 215-1 한사 스튜디오 406 (주)윅슨어소시에이츠 / #406 , HANSA Studio, 215-1, Donggyo-ro, Mapo-gu, Seoul,  Korea
                </address>
                <p class="copywriter">
                    &copy; wixon associates Inc. 2022
                </p>
                <p class="slogan">
                    wixon. Who Invariable eXistence On the New era " wixon associates Inc. "
                </p>
                <ul>
                    <li><a href="/"><img src="/static/images/opusclam.png" alt="WIXON" /></a></li>
                    <li><a href="/"><img src="/static/images/lpstock.png" alt="WIXON" /></a></li>
                </ul>
            </div>
            <h2 class="footer__logo">
                <a href="/"><img src="/static/images/logo.png" alt="WIXON" /></a>
            </h2>
        </div>
    </footer>
    <script>
        let currentPage = 1;
        let isLoading = false;

        function Mobile() {
            return $(window).width() <= 1023;
        }

        function getShortestColumnIndex() {
            const lengths = [
                $(".list__posts0 li").length,
                $(".list__posts1 li").length,
                $(".list__posts2 li").length
            ];
            return lengths.indexOf(Math.min(...lengths));
        }

        function distributePosts(posts) {
            posts.forEach((post) => {
                const postHTML = `
                <li>
                    <a href="/post/${post.id}">
                    <div class="lists__img">
                        <img src="${post.thumbnail_img || 'https://via.placeholder.com/300x200'}" alt="${post.title}" onerror="this.onerror=null; this.src='https://via.placeholder.com/300x200';" />
                    </div>
                    <div class="lists__desc">
                        <p class="lists__category">${post.category}</p>
                        <h3 class="lists__title">${post.title}</h3>
                        <p class="lists__content">${post.contents}</p>
                        <p class="lists__date"><b>${post.add_date_str}</b></p>
                    </div>
                    </a>
                </li>
                `;

                if (Mobile()) {
                    $(".fake__lists").append(postHTML);
                } else {
                    const columnIndex = getShortestColumnIndex(); // 가장 짧은 컬럼
                    $(`.list__posts${columnIndex}`).append(postHTML);
                }
            });
        }

        function loadMorePosts() {
            if (isLoading) return;
            isLoading = true;
            currentPage++;

            $.ajax({
                url: "/list_more",
                type: "GET",
                data: { page: currentPage },
                success: function(data) {
                    if (data.length === 0) {
                        $(window).off("scroll");
                        return;
                    }
                    distributePosts(data);
                    isLoading = false;
                },
                error: function() {
                    console.error("게시물 로딩 실패");
                }
            });
        }

        // 스크롤 감지
        $(window).on("scroll", function() {
            if ($(window).scrollTop() + $(window).height() >= $(document).height() - 200) {
                loadMorePosts();
            }
        });

        if (!Mobile()) {
            let initialPosts = [];
            $(".fake__lists li").each(function() {
                let $li = $(this);
                initialPosts.push({
                id: $li.find("a").attr("href").split("/post/")[1],
                title: $li.find(".lists__title").text(),
                category: $li.find(".lists__category").text(),
                thumbnail_img: $li.find("img").attr("src"),
                contents: $li.find(".lists__content").text(),
                add_date_str: $li.find(".lists__date").text()
                });
            });

            distributePosts(initialPosts);
        }
    </script>
{% endblock %}
    </div>
    </body>
</html>