<?php
if (!defined('__TYPECHO_ROOT_DIR__')) exit;

function Mirai_apiCommentList() {
    $cid = isset($_GET['cid']) ? (int)$_GET['cid'] : 0;
    if ($cid <= 0) return ['code' => -1, 'success' => false, 'msg' => '缺少文章ID'];

    $page = isset($_GET['page']) ? max(1, (int)$_GET['page']) : 1;
    $config = Mirai_getCommentConfig();
    $pageSize = intval($config['pageSize']);
    $pageSize = max(1, min(50, $pageSize));

    $db = \Typecho\Db::get();
    $options = Mirai_opt();

    $select = $db->select('COUNT(coid)')->from('table.comments')
        ->where('cid = ?', $cid)
        ->where('status = ?', 'approved')
        ->where('parent = ?', 0);
    if ($options->commentsShowCommentOnly) $select->where('type = ?', 'comment');
    $totalComments = (int)$db->fetchObject($select)->{'COUNT(coid)'};
    $totalPages = $pageSize > 0 ? ceil($totalComments / $pageSize) : 1;

    if ($page > $totalPages && $totalPages > 0) $page = $totalPages;

    $direction = ($config['pageDisplay'] === 'last') ? 'backward' : 'forward';
    $hasMore = ($direction === 'forward') ? ($page < $totalPages) : ($page > 1);
    $nextPage = ($direction === 'forward') ? $page + 1 : $page - 1;

    $postRow = $db->fetchRow($db->select('cid', 'slug', 'created', 'type')->from('table.contents')->where('cid = ?', $cid));
    if (!$postRow) return ['code' => -1, 'success' => false, 'msg' => '文章不存在'];

    $postPermalink = \Typecho\Router::url('post', $postRow, $options->index);

    ob_start();
    $comments = $db->fetchAll(
        $db->select()->from('table.comments')
            ->where('cid = ?', $cid)
            ->where('status = ?', 'approved')
            ->where('parent = ?', 0)
            ->order('table.comments.created', \Typecho\Db::SORT_DESC)
            ->page($page, $pageSize)
    );

    if (empty($comments)) {
        ob_end_clean();
        return [
            'code' => 0,
            'success' => true,
            'html' => '<div class="gt-comment-empty"><i class="ri-message-3-line"></i><span>暂无评论，快来抢沙发吧~</span></div>',
            'hasMore' => false,
            'nextPage' => 0,
            'total' => $totalComments,
            'paginationHtml' => ''
        ];
    }

    $coids = array_column($comments, 'coid');

    $childComments = [];
    if ($config['threaded']) {
        $childSelect = $db->select()->from('table.comments')
            ->where('cid = ?', $cid)
            ->where('status = ?', 'approved')
            ->where('parent IN ?', $coids)
            ->order('table.comments.created', \Typecho\Db::SORT_ASC);
        $childResults = $db->fetchAll($childSelect);
        foreach ($childResults as $child) {
            $childComments[$child['parent']][] = $child;
        }
    }

    foreach ($comments as $comment) {
        Mirai_renderCommentFromData($comment, $config, $childComments, 0, $postPermalink);
    }
    $html = ob_get_clean();

    $paginationHtml = '';
    if ($totalPages > 1) {
        if ($hasMore) {
            $nextUrl = $postPermalink . '/comment-page-' . $nextPage . '#comments';
            $triggerMode = $options->commentsAjaxPaginationTrigger ?? 'button';
            $paginationHtml = Mirai_buildAjaxPaginationHtml([
                'scopeType' => 'comments',
                'current' => $page,
                'total' => $totalPages,
                'nextUrl' => $nextUrl,
                'triggerMode' => $triggerMode,
                'direction' => $direction,
                'ariaLabel' => '评论分页',
                'hasMore' => true,
            ]);
        } else {
            $paginationHtml = Mirai_buildAjaxPaginationHtml([
                'scopeType' => 'comments',
                'current' => $page,
                'total' => $totalPages,
                'direction' => $direction,
                'ariaLabel' => '评论分页',
                'hasMore' => false,
            ]);
        }
    }

    return [
        'code' => 0,
        'success' => true,
        'html' => $html,
        'hasMore' => $hasMore,
        'nextPage' => $hasMore ? $nextPage : 0,
        'nextUrl' => $hasMore ? $postPermalink . '/comment-page-' . $nextPage . '#comments' : '',
        'total' => $totalComments,
        'paginationHtml' => $paginationHtml
    ];
}

function Mirai_renderCommentFromData($comment, $config, $childComments, $level, $postPermalink) {
    $isAuthor = $comment['authorId'] && $comment['ownerId'] && $comment['authorId'] == $comment['ownerId'];
    $masterClass = $isAuthor ? 'gt-comment-master' : '';
    $currentLevel = $level;
    $canReply = $config['threaded'] && $currentLevel < $config['maxNestingLevels'];

    $avatarUrl = '';
    if ($comment['authorId']) {
        $avatarUrl = Mirai_getUserAvatar($comment['authorId']);
    } else {
        $avatarUrl = Mirai_getDefaultAvatar();
    }

    $author = htmlspecialchars($comment['author'], ENT_QUOTES, 'UTF-8');
    $authorHtml = $author;
    if ($config['showUrl'] && !empty($comment['url'])) {
        $url = $comment['url'];
        if (preg_match('/^https?:\/\//i', $url)) {
            $rel = 'noopener';
            if ($config['urlNofollow']) $rel .= ' nofollow';
            $authorHtml = '<a href="' . htmlspecialchars($url, ENT_QUOTES, 'UTF-8') . '" target="_blank" rel="' . $rel . '">' . $author . '</a>';
        }
    }

    $content = $comment['text'];
    if (!empty($comment['parent'])) {
        $db = \Typecho\Db::get();
        $parent = $db->fetchRow($db->select('author')->from('table.comments')->where('coid = ?', $comment['parent']));
        if ($parent) {
            $atLink = '<a class="gt-comment-at" href="#comment-' . $comment['parent'] . '">@' . htmlspecialchars($parent['author'], ENT_QUOTES, 'UTF-8') . '</a> ';
            if (preg_match('/^<p>/i', $content)) {
                $content = preg_replace('/^<p>/i', '<p>' . $atLink, $content, 1);
            } else {
                $content = $atLink . $content;
            }
        }
    }

    $options = Mirai_opt();
    if (Mirai_featureEnabled('seo') && (string)$options->nofollowExternalLinks !== '0') {
        if (function_exists('Mirai_addNofollowToExternalLinks')) {
            $content = Mirai_addNofollowToExternalLinks($content);
        }
    }

    $locationHtml = '';
    if (!empty($options->ipLocationEnable) && !empty($comment['ip_location'])) {
        $locationHtml = '<span class="gt-comment-tag"><i class="ri-map-pin-line"></i>' . htmlspecialchars($comment['ip_location'], ENT_QUOTES, 'UTF-8') . '</span>';
    }

    $levelBadge = '';
    if (!$isAuthor && $comment['authorId'] && function_exists('Mirai_levelGetBadge') && function_exists('Mirai_levelGet') && function_exists('Mirai_levelEnabled') && Mirai_levelEnabled()) {
        $commentAuthorLevel = Mirai_levelGet((int)$comment['authorId']);
        if ($commentAuthorLevel > 1) {
            $levelBadge = Mirai_levelGetBadge($commentAuthorLevel);
        }
    }

    $replyUrl = $postPermalink . '?replyTo=' . $comment['coid'] . '#respond';

    echo '<div id="comment-' . $comment['coid'] . '" class="gt-comment-item ' . $masterClass . '" data-level="' . $currentLevel . '">';
    echo '<div class="gt-comment-avatar">';
    echo '<img class="avatar" loading="lazy" src="' . htmlspecialchars($avatarUrl, ENT_QUOTES, 'UTF-8') . '" alt="' . $author . '" width="48" height="48" />';
    echo '</div>';
    echo '<div class="gt-comment-main">';
    echo '<div class="gt-comment-head"><div class="gt-comment-meta-wrapper"><div class="gt-comment-meta">';
    echo '<span class="gt-comment-nick">' . $authorHtml . '</span>';
    if ($isAuthor) echo '<span class="gt-comment-badge">作者</span>';
    echo $levelBadge;
    echo '</div><div class="gt-comment-meta-info">' . $locationHtml . '</div></div></div>';
    echo '<div class="gt-comment-content">' . $content . '</div>';
    echo '<div class="gt-comment-footer">';
    echo '<time class="gt-comment-time" datetime="' . Mirai_formatISODate($comment['created']) . '">' . Mirai_formatTime($comment['created']) . '</time>';
    if ($canReply) {
        echo '<div class="gt-comment-actions"><a href="' . htmlspecialchars($replyUrl, ENT_QUOTES, 'UTF-8') . '" onclick="return TypechoComment.reply(\'comment-' . $comment['coid'] . '\', ' . $comment['coid'] . ');">回复</a></div>';
    }
    echo '</div></div>';

    if ($config['threaded'] && !empty($childComments[$comment['coid']])) {
        echo '<div class="gt-comment-replies">';
        foreach ($childComments[$comment['coid']] as $child) {
            $child['ownerId'] = $comment['ownerId'] ?? 0;
            Mirai_renderCommentFromData($child, $config, $childComments, $currentLevel + 1, $postPermalink);
        }
        echo '</div>';
    }

    echo '</div>';
}
