<?php
if (!defined('_GNUBOARD_')) exit; // 개별 페이지 접근 불가
include_once(G5_LIB_PATH.'/thumbnail.lib.php');
global $is_member;

// 썸네일 크기 수정
$thumb_width = 300; // 썸네일 너비
$thumb_height = 200; // 썸네일 높이
?>

<div class="latest_wrap">
    <?php
for ($i=0; $i<count($list); $i++) {
    $thumb = get_list_thumbnail($bo_table, $list[$i]['wr_id'], $thumb_width, $thumb_height, false, true);
    
    // Initialize img_content as empty
    $img_content = '';
    
    // 이미지 소스가 있을 때만 이미지 내용 생성
    if($thumb['src']) {
        $img_content = '<img src="' . G5_URL . '/img/loading.gif" data-src="'.$thumb['src'].'" alt="'.$thumb['alt'].'" class="lazyload" style="width: 100%; height: 200px; object-fit: cover; opacity: 1; transition: opacity 0.3s ease-in-out; border-radius: 10px">';
    }

    // 댓글 가져오기
    $comment_sql = "SELECT c.*, m.mb_nick AS nickname 
                    FROM {$g5['write_prefix']}{$bo_table} AS c
                    LEFT JOIN {$g5['member_table']} AS m ON c.mb_id = m.mb_id
                    WHERE c.wr_parent = '{$list[$i]['wr_id']}'
                    AND c.wr_is_comment = '1'
                    ORDER BY c.wr_datetime DESC
                    LIMIT 10"; // 최신순으로 10개만 가져오기

    $comment_result = sql_query($comment_sql);
    $comments = array();
    while ($comment_row = sql_fetch_array($comment_result)) {
        $comment_row['wr_name'] = $comment_row['nickname'] ? $comment_row['nickname'] : $comment_row['wr_name'];
        $comments[] = $comment_row;
    }
    
    // 댓글 수 조회
    $comment_count_sql = "SELECT COUNT(*) AS cnt 
                          FROM {$g5['write_prefix']}{$bo_table}
                          WHERE wr_parent = '{$list[$i]['wr_id']}'
                          AND wr_is_comment = '1'";
    $comment_count_result = sql_fetch($comment_count_sql);
    $comment_count = $comment_count_result['cnt'] ? $comment_count_result['cnt'] : 0;
    ?>

    <div class="latest_item" data-wr_id="<?php echo $list[$i]['wr_id'] ?>" style="display: inline-block; width: 100%; min-width: 200px; margin-bottom: 10px; border: 1px solid #eaeaea; border-radius: 10px; overflow: hidden; background-color: #fff; transition: transform 0.3s ease; cursor: pointer;">
        <div class="latest_info" style="padding: 15px;">
            <div class="latest_member_id" style="font-weight: bold; color: #333; margin-bottom: 10px;">
                <?php echo $list[$i]['name'] ?? ''; ?>
            </div>
            <!-- 날짜 -->
            <div class="latest_date" style="font-size: 12px; color: #999; margin-bottom: 10px;">
                <?php
                    $time_diff = time() - strtotime($list[$i]['wr_datetime']);
                    if ($time_diff < 60) {
                        echo $time_diff . '초 전';
                    } elseif ($time_diff < 3600) {
                        echo floor($time_diff / 60) . '분 전';
                    } elseif ($time_diff < 86400) {
                        echo floor($time_diff / 3600) . '시간 전';
                    } elseif ($time_diff < 604800) {
                        echo floor($time_diff / 86400) . '일 전';
                    } elseif ($time_diff < 2592000) {
                        echo floor($time_diff / 604800) . '주 전';
                    } elseif ($time_diff < 31536000) {
                        echo floor($time_diff / 2592000) . '개월 전';
                    } else {
                        echo floor($time_diff / 31536000) . '년 전';
                    }
                ?>
            </div>
            <!-- 제목 -->
            <div class="latest_subject" onclick="location.href='<?php echo $list[$i]['href'] ?>';" style="font-weight: bold; color: #333; margin-bottom: 10px;">
                <?php echo $list[$i]['subject'] ?>
            </div>

            <!-- 내용 -->
            <div class="latest_content" onclick="location.href='<?php echo $list[$i]['href'] ?>';" style="font-size: 14px; color: #777; line-height: 1.4; margin-bottom: 10px;">
                <?php echo cut_str(strip_tags($list[$i]['wr_content']), 80)?>
            </div>

            <!-- 이미지 출력 -->
            <div class="latest_img" style="width: 100%; height: auto; overflow: hidden; margin-top: 10px;">
                <?php echo $img_content; ?>
            </div>

            <!-- 댓글/공유 버튼 -->
<div class="comments_toggle_bar" style="display: flex; justify-content: flex-end; margin-top: 10px;">
    <button class="toggle_comments_btn" style="background: none; border: none; color: #999; cursor: pointer; font-size: 14px; display: flex; align-items: center; margin-right: 10px">
        <i class="fa fa-comments"></i>&nbsp;<span class="comment_count"><?php echo $comment_count; ?></span>
    </button>
    <button class="copy_link_btn" data-href="<?php echo $list[$i]['href'] ?>" style="background: none; border: none; color: #999; cursor: pointer; font-size: 14px; display: flex; align-items: center;">
        <i class="fa fa-share-square-o"></i>
    </button>
</div>

            <!-- 댓글 출력 시작 (기본 숨김) -->
            <?php if(count($comments) > 0) { ?>
                <div class="latest_comments" style="display: none; margin-top: 10px; border-top: 1px solid #eaeaea; padding-top: 10px;">
                    <?php foreach($comments as $comment) { ?>
                        <div class="latest_comment" style="margin-bottom: 10px; font-size: 0.9em;">
                            <div class="comment_member_id" style="font-weight: bold; color: #333;">
                                <?php echo htmlspecialchars($comment['wr_name']); ?>
                            </div>
                            <div class="comment_content" style="color: #555;">
                                <?php echo cut_str(strip_tags($comment['wr_content']), 30); ?>
                            </div>
                        </div>
                    <?php } ?>
                </div>
            <?php } ?>
            <!-- 댓글 출력 끝 -->

            <!-- 댓글 작성 폼 시작 -->
            <div class="comment_form" style="display: flex; flex-direction: column; margin-top: 10px; padding-top: 10px; border-top: 1px solid #eaeaea;">
                <?php if ($is_member) { ?>
                    <input type="text" class="comment_input" placeholder="댓글 추가하기" style="flex-grow: 1; padding: 8px; font-size: 14px; border-radius: 10px; border: 1px solid #ddd; width: 100%">
                    <button class="comment_submit" data-wr-id="<?php echo $list[$i]['wr_id'] ?>" style="padding: 8px 10px; margin-top: 5px; background-color: #3a89fc; color: white; border: none; border-radius: 15px; cursor: pointer; transition: background-color 0.3s ease; white-space: nowrap;">
                        게시
                    </button>
                <?php } else { } ?>
            </div>            
            <!-- 댓글 작성 폼 끝 -->
        </div>
    </div>

    <?php } ?>
    <?php if (count($list) == 0) { ?>
    <div class="latest_item">
        <div class="latest_content">
            등록된 게시물이 없습니다.
        </div>
    </div>
    <?php } ?>
</div>

<!-- Lazy Load Script -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/lazysizes/5.3.2/lazysizes.min.js" async></script>
<script>
document.addEventListener('DOMContentLoaded', function() {
    lazySizes.cfg.loadMode = 1;
    
    // 이미지 로딩 완료 이벤트 처리
    document.addEventListener('lazyloaded', function(e) {
        if (e.target.tagName === 'IMG') {
            e.target.style.opacity = '1';
        }
    });
});
</script>

<!-- 댓글 토글 기능 -->
<script>
document.addEventListener('DOMContentLoaded', function() {
    function initializeCommentToggles() {
        document.querySelectorAll('.toggle_comments_btn').forEach(button => {
            if (!button.classList.contains('toggle-initialized')) {
                button.classList.add('toggle-initialized');
                
                const latestItem = button.closest('.latest_item');
                const commentsContainer = latestItem.querySelector('.latest_comments');
                const commentCountSpan = button.querySelector('.comment_count');
                const commentCount = commentCountSpan ? commentCountSpan.textContent : '0';
                
                if (commentsContainer) {
                    button.addEventListener('click', function(e) {
                        e.stopPropagation();
                        
                        const isVisible = commentsContainer.style.display === 'block';
                        
                        if (isVisible) {
                            commentsContainer.style.display = 'none';
                            button.innerHTML = `<i class="fa fa-comments"></i>&nbsp;<span class="comment_count">${commentCount}</span>`;
                        } else {
                            commentsContainer.style.display = 'block';
                            button.innerHTML = `댓글 숨기기 <i class="fa fa-comments"></i>&nbsp;<span class="comment_count">${commentCount}</span>`;
                        }
                    });
                }
            }
        });
    }

    // 초기 실행
    initializeCommentToggles();

    // 댓글 작성 성공 후의 처리
    const originalFetch = window.fetch;
    window.fetch = function() {
        return originalFetch.apply(this, arguments)
            .then(async response => {
                const clone = response.clone();
                const data = await clone.json();
                
                if (data.success && arguments[0].includes('ajax_latest_comment.php')) {
                    const button = document.querySelector('.comment_submit[disabled]');
                    if (button) {
                        const latestItem = button.closest('.latest_item');
                        const toggleBtn = latestItem.querySelector('.toggle_comments_btn');
                        const commentCountSpan = toggleBtn.querySelector('.comment_count');
                        
                        if (commentCountSpan) {
                            const currentCount = parseInt(commentCountSpan.textContent || '0');
                            commentCountSpan.textContent = currentCount + 1;
                        }
                        
                        const commentsContainer = latestItem.querySelector('.latest_comments');
                        if (commentsContainer) {
                            commentsContainer.style.display = 'block';
                            toggleBtn.innerHTML = `댓글 숨기기 <i class="fa fa-comments"></i>&nbsp;<span class="comment_count">${parseInt(commentCountSpan.textContent)}</span>`;
                        }
                    }
                }
                
                return response;
            });
    };
});
</script>

<!-- 링크 복사 기능 -->
<script>
document.addEventListener('DOMContentLoaded', function() {
    document.querySelectorAll('.copy_link_btn').forEach(button => {
        if (!button.classList.contains('initialized')) {
            button.classList.add('initialized'); // 초기화 클래스 추가
            button.addEventListener('click', function(e) {
                e.stopPropagation(); // 부모 요소의 클릭 이벤트 방지
                const link = button.getAttribute('data-href');
                navigator.clipboard.writeText(link).then(() => {
                    alert('링크가 복사되었습니다.');
                }).catch(err => {
                    console.error('링크 복사 오류:', err);
                    alert('링크 복사에 실패했습니다.');
                });
            });
        }
    });
});
</script>


<!-- 댓글 작성 기능 -->
<script>
document.addEventListener('DOMContentLoaded', function() {
    document.querySelectorAll('.comment_submit').forEach(button => {
        if (!button.classList.contains('initialized')) {
            button.classList.add('initialized'); // 초기화 클래스 추가
            button.addEventListener('click', (e) => {
                e.preventDefault();

                const wr_id = button.getAttribute('data-wr-id');
                const input = button.previousElementSibling;
                const commentContent = input.value.trim();

                // 비회원 필드 가져오기
                const nameInput = button.closest('.comment_form').querySelector('.comment_name');
                const passwordInput = button.closest('.comment_form').querySelector('.comment_password');
                const name = nameInput ? nameInput.value.trim() : null;
                const password = passwordInput ? passwordInput.value.trim() : null;

                if (commentContent === '') {
                    alert('댓글 내용을 입력하세요.');
                    return;
                }
                
                // 비회원일 때 이름과 비밀번호 체크
                if (!name && nameInput) {
                    alert('이름을 입력하세요.');
                    return;
                }
                if (!password && passwordInput) {
                    alert('비밀번호를 입력하세요.');
                    return;
                }

                button.disabled = true;
                button.textContent = '게시 중...';

                fetch('<?php echo G5_BBS_URL ?>/ajax_latest_comment.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        wr_id: wr_id,
                        content: commentContent,
                        password: password // 비회원 비밀번호
                    })
                })
                .then(response => response.json())
                .then(data => {
                    button.disabled = false;
                    button.textContent = '게시';

                    if (data.success) {
                        alert('댓글이 성공적으로 게시되었습니다.');

                        let latestItem = button.closest('.latest_item');
                        let commentsContainer = latestItem.querySelector('.latest_comments');
                        if (!commentsContainer) {
                            commentsContainer = document.createElement('div');
                            commentsContainer.classList.add('latest_comments');
                            latestItem.querySelector('.latest_info').insertBefore(commentsContainer, button.parentElement);
                        }

                        const newComment = document.createElement('div');
                        newComment.classList.add('latest_comment');
                        newComment.innerHTML = `
                           <div class="comment_member_id">(나) ${data.nickname || '익명'}</div>
                            <div class="comment_content" style="color:#444">${commentContent}</div>
                        `;
                        commentsContainer.appendChild(newComment);

                        input.value = '';
                        if (nameInput) nameInput.value = '';
                        if (passwordInput) passwordInput.value = '';

                        // 댓글이 추가되면 댓글이 보이도록 설정
                        commentsContainer.style.display = 'block';
                        const toggleBtn = latestItem.querySelector('.toggle_comments_btn');
                        if (toggleBtn) {
                            toggleBtn.innerHTML = '댓글 숨기기 <i class="fa fa-comments"></i>';
                        }
                    } else {
                        alert(data.message || '댓글 게시에 실패했습니다.');
                    }
                })
                .catch(error => {
                    console.error('댓글 작성 오류:', error);
                    alert('댓글 작성 중 오류가 발생했습니다.');
                    button.disabled = false;
                    button.textContent = '게시';
                });
            });
        }
    });
});
</script>

<style>
.latest_wrap {
    column-count: 3;
    column-gap: 10px;
    padding: 10px;
    max-width: 1200px;
    margin: 0 auto;
    width: 100%;
}

@media (max-width: 1024px) {
    .latest_wrap {
        column-count: 2; /* 화면이 좁아질 때 2열로 조정 */
    }
}

@media (max-width: 768px) {
    .latest_wrap {
        column-count: 1; /* 더 좁은 화면에서는 1열로 조정 */
    }
}
.latest_member_id img {
max-width:35px;
max-height:35px;
border-radius: 50%
}

.lazy {
    opacity: 0;
    transition: opacity 0.3s ease-in-out;
}

.lazy.lazyloaded {
    opacity: 1;
}
</style>
