<?php
declare(strict_types=1);

if (!function_exists('vm_mb_len')) {
    function vm_mb_len(string $s): int
    {
        if (function_exists('mb_strlen')) return (int)mb_strlen($s, 'UTF-8');
        return strlen($s);
    }
}

if (!function_exists('vm_mb_sub')) {
    function vm_mb_sub(string $s, int $start, int $len): string
    {
        if (function_exists('mb_substr')) return (string)mb_substr($s, $start, $len, 'UTF-8');
        return substr($s, $start, $len);
    }
}

if (!function_exists('vm_first_char')) {
    function vm_first_char(string $s): string
    {
        $s = trim($s);
        if ($s === '') return '?';
        return vm_mb_sub($s, 0, 1);
    }
}

if (!function_exists('vm_norm_spaces')) {
    function vm_norm_spaces(string $s): string
    {
        $s = trim($s);
        $s = preg_replace('~\s+~u', ' ', $s) ?? $s;
        return trim($s);
    }
}

if (!function_exists('vm_clip')) {
    function vm_clip(string $s, int $max): string
    {
        if ($max <= 0) return '';
        if (vm_mb_len($s) <= $max) return $s;
        return vm_mb_sub($s, 0, max(1, $max - 1)) . '…';
    }
}

if (!function_exists('vm_csrf_token')) {
    function vm_csrf_token(): string
    {
        if (function_exists('csrf_token')) return (string)csrf_token();
        if (function_exists('g_csrf_token')) return (string)g_csrf_token();
        return '';
    }
}

if (!function_exists('g_user_display')) {
    function g_user_display(array $p): string
    {
        $fn = trim((string)($p['first_name'] ?? ''));
        $ln = trim((string)($p['last_name'] ?? ''));
        $full = trim($fn . ' ' . $ln);
        return $full !== '' ? $full : (string)($p['username'] ?? '');
    }
}

if (!function_exists('g_back_uri')) {
    function g_back_uri(): string
    {
        if (function_exists('current_uri')) return (string)current_uri();
        return (string)($_SERVER['REQUEST_URI'] ?? '/');
    }
}

if (!function_exists('g_csrf_field_fallback')) {
    function g_csrf_field_fallback(): void
    {
        if (function_exists('csrf_field')) {
            echo csrf_field();
            return;
        }
        echo '<input type="hidden" name="csrf" value="' . g_h(vm_csrf_token()) . '">';
    }
}

if (!function_exists('g_linkify_text')) {
    function g_linkify_text(string $text): string
    {
        $text = (string)$text;
        if ($text === '') return '';

        $re = '~\bhttps?://[^\s<]+~i';
        $pos = 0;
        $out = '';

        while (preg_match($re, $text, $m, PREG_OFFSET_CAPTURE, $pos)) {
            $raw = (string)$m[0][0];
            $start = (int)$m[0][1];

            $before = substr($text, $pos, $start - $pos);
            $out .= g_h($before);

            $trimmed = rtrim($raw, '.,);!?]}>');
            $tail = substr($raw, strlen($trimmed));

            $url = trim($trimmed);
            if (strlen($url) > 2000) $url = substr($url, 0, 2000);

            $disp = $trimmed;
            if (function_exists('mb_strlen') && function_exists('mb_substr')) {
                if (mb_strlen($disp, 'UTF-8') > 80) {
                    $disp = mb_substr($disp, 0, 60, 'UTF-8') . '…' . mb_substr($disp, -15, 15, 'UTF-8');
                }
            } else {
                if (strlen($disp) > 80) {
                    $disp = substr($disp, 0, 60) . '…' . substr($disp, -15);
                }
            }

            $out .= '<a href="' . g_h($url) . '" target="_blank" rel="noopener nofollow ugc">' . g_h($disp) . '</a>';
            if ($tail !== '') $out .= g_h($tail);

            $pos = $start + strlen($raw);
        }

        $out .= g_h(substr($text, $pos));
        return nl2br($out);
    }
}

if (!function_exists('g_extract_first_url')) {
    function g_extract_first_url(string $text): string
    {
        $text = trim($text);
        if ($text === '') return '';

        if (preg_match('~\bhttps?://[^\s<>"\']+~i', $text, $m)) {
            $u = (string)($m[0] ?? '');
            $u = rtrim($u, '.,);!?]}>');
            if (strlen($u) > 2000) $u = substr($u, 0, 2000);
            return $u;
        }

        return '';
    }
}

if (!function_exists('g_render_link_preview_card')) {
    function g_render_link_preview_card(string $url): void
    {
        if ($url === '' || !preg_match('~^https?://~i', $url)) return;
        ?>
        <div class="lp-card-feed mt-3" data-lp-url="<?= g_h($url) ?>">
            <a class="lp-card-inner" href="<?= g_h($url) ?>" target="_blank" rel="noopener nofollow ugc">
                <div class="lp-img"><img src="" alt=""></div>
                <div class="lp-meta">
                    <div class="lp-title"><?= g_h($url) ?></div>
                    <div class="lp-desc" style="display:none;"></div>
                    <div class="lp-site" style="display:none;"></div>
                </div>
            </a>
        </div>
        <?php
    }
}

if (!function_exists('g_render_comment')) {
    function g_render_comment(
        array $c,
        array $repliesByParent,
        array $commentAttById,
        int $postId,
        bool $canComment,
        ?array $me,
        bool $viewerIsAdmin,
        bool $isManager,
        string $backUri,
        bool $isReply = false
    ): void {
        $cid = (int)($c['id'] ?? 0);
        $galleryId = 'gc' . $cid;

        $authorId = (int)($c['user_id'] ?? 0);
        $canManage = (bool)$me && (
            ((int)($me['id'] ?? 0) === $authorId) ||
            $viewerIsAdmin ||
            $isManager
        );

        $fullName = g_user_display($c);
        $username = trim((string)($c['username'] ?? ''));
        $avatar   = trim((string)($c['avatar_path'] ?? ''));
        $initials = vm_first_char($fullName !== '' ? $fullName : ($username !== '' ? $username : 'U'));

        $likes = (int)($c['likes'] ?? 0);
        $dislikes = (int)($c['dislikes'] ?? 0);
        $myReaction = (string)($c['my_reaction'] ?? '');

        $likeBtnClass = ($myReaction === 'like') ? 'btn-success' : 'btn-outline-success';
        $disBtnClass  = ($myReaction === 'dislike') ? 'btn-danger' : 'btn-outline-danger';

        $likeTitle = g_t('Лайків: ', 'Лайков: ', 'Likes: ') . $likes;
        $disTitle  = g_t('Дизлайків: ', 'Дизлайков: ', 'Dislikes: ') . $dislikes;

        $commentBody = (string)($c['body'] ?? '');
        $firstUrl = g_extract_first_url($commentBody);

        $atts = $commentAttById[$cid] ?? [];
        $imgs = array_values(array_filter($atts, fn($a) => (string)($a['file_type'] ?? '') === 'image'));
        $aud  = array_values(array_filter($atts, fn($a) => (string)($a['file_type'] ?? '') === 'audio'));
        $vid  = array_values(array_filter($atts, fn($a) => (string)($a['file_type'] ?? '') === 'video'));
        $fil  = array_values(array_filter($atts, fn($a) => (string)($a['file_type'] ?? '') === 'file'));

        $confirmDel = g_t('Видалити коментар?', 'Удалить комментарий?', 'Delete comment?');
        $backToComment = $backUri . '#comment-' . $cid;
        ?>
        <div class="comment <?= $isReply ? 'is-reply' : '' ?>" id="comment-<?= $cid ?>">
            <div class="comment-head d-flex justify-content-between align-items-start gap-2">
                <div class="d-flex align-items-center gap-2">
                    <div class="vm-ava-sm">
                        <?php if ($avatar !== ''): ?>
                            <img src="<?= g_h($avatar) ?>" alt="" loading="lazy">
                        <?php else: ?>
                            <div class="vm-ava-ph"><?= g_h($initials) ?></div>
                        <?php endif; ?>
                    </div>

                    <div>
                        <div class="comment-author">
                            <?= g_h($fullName !== '' ? $fullName : $username) ?>
                            <?php if ($username !== ''): ?>
                                <span class="text-muted small"> @<?= g_h($username) ?></span>
                            <?php endif; ?>
                        </div>
                        <div class="comment-meta"><?= g_h((string)($c['created_at'] ?? '')) ?></div>
                    </div>
                </div>

                <?php if ($canManage): ?>
                    <details class="vm-menu">
                        <summary class="vm-menu-btn" aria-label="menu">⋯</summary>
                        <div class="vm-menu-box">
                            <a class="vm-menu-item" href="/comment_edit.php?id=<?= $cid ?>&back=<?= urlencode($backUri) ?>">
                                <?= g_h(g_t('Редагувати','Редактировать','Edit')) ?>
                            </a>

                            <form method="post" action="/functional/comment/manage.php"
                                  onsubmit="return confirm(<?= json_encode($confirmDel, JSON_UNESCAPED_UNICODE) ?>);">
                                <?php g_csrf_field_fallback(); ?>
                                <input type="hidden" name="action" value="delete">
                                <input type="hidden" name="id" value="<?= $cid ?>">
                                <input type="hidden" name="back" value="<?= g_h($backToComment) ?>">
                                <button type="submit" class="vm-menu-item vm-menu-danger">
                                    <?= g_h(g_t('Видалити','Удалить','Delete')) ?>
                                </button>
                            </form>
                        </div>
                    </details>
                <?php endif; ?>
            </div>

            <?php if (trim($commentBody) !== ''): ?>
                <div class="comment-body"><?= g_linkify_text($commentBody) ?></div>
            <?php endif; ?>

            <?php if ($firstUrl !== ''): ?>
                <?php g_render_link_preview_card($firstUrl); ?>
            <?php endif; ?>

            <?php if ($atts): ?>
                <div class="comment-attachments mt-2" data-gallery-images="<?= g_h($galleryId) ?>">
                    <?php if ($imgs): ?>
                        <?php if (count($imgs) === 1): $a = $imgs[0]; ?>
                            <div class="attachments-single">
                                <a class="att-img att-img-single js-lightbox"
                                   href="<?= g_h((string)($a['path'] ?? '')) ?>"
                                   data-gallery="<?= g_h($galleryId) ?>"
                                   target="_blank" rel="noopener">
                                    <img src="<?= g_h((string)($a['path'] ?? '')) ?>" alt="" loading="lazy">
                                </a>
                            </div>
                        <?php else: ?>
                            <div class="attachments-grid">
                                <?php foreach ($imgs as $a): ?>
                                    <a class="att-img js-lightbox"
                                       href="<?= g_h((string)($a['path'] ?? '')) ?>"
                                       data-gallery="<?= g_h($galleryId) ?>"
                                       target="_blank" rel="noopener">
                                        <img src="<?= g_h((string)($a['path'] ?? '')) ?>" alt="" loading="lazy">
                                    </a>
                                <?php endforeach; ?>
                            </div>
                        <?php endif; ?>
                    <?php endif; ?>

                    <?php foreach ($aud as $a): ?>
                        <div class="mt-2">
                            <audio controls preload="none" class="w-100">
                                <source src="<?= g_h((string)($a['path'] ?? '')) ?>" type="<?= g_h((string)($a['mime'] ?? '')) ?>">
                            </audio>
                        </div>
                    <?php endforeach; ?>

                    <?php foreach ($vid as $a): ?>
                        <div class="mt-2">
                            <video controls preload="metadata" class="w-100 rounded-3"
                                   playsinline webkit-playsinline
                                   disablepictureinpicture
                                   controlslist="nodownload noplaybackrate">
                                <source src="<?= g_h((string)($a['path'] ?? '')) ?>" type="<?= g_h((string)($a['mime'] ?? '')) ?>">
                            </video>
                        </div>
                    <?php endforeach; ?>

                    <?php if ($fil): ?>
                        <div class="mt-2 d-flex flex-column gap-1">
                            <?php foreach ($fil as $a): ?>
                                <a class="att-file" href="<?= g_h((string)($a['path'] ?? '')) ?>" target="_blank" rel="noopener">
                                    <?= g_h((string)($a['original_name'] ?? 'file')) ?>
                                </a>
                            <?php endforeach; ?>
                        </div>
                    <?php endif; ?>
                </div>
            <?php endif; ?>

            <div class="comment-actions mt-2 d-flex align-items-center gap-2">
                <?php if ($me): ?>
                    <form method="post" action="/comment_react.php" class="d-inline js-comment-react-form" data-no-pjax="1">
                        <input type="hidden" name="csrf" value="<?= g_h(vm_csrf_token()) ?>">
                        <input type="hidden" name="comment_id" value="<?= $cid ?>">
                        <input type="hidden" name="reaction" value="like">
                        <input type="hidden" name="back" value="<?= g_h($backToComment) ?>">
                        <button type="submit"
                                class="btn btn-sm <?= g_h($likeBtnClass) ?>"
                                data-comment="<?= $cid ?>"
                                data-cmtreact="like"
                                title="<?= g_h($likeTitle) ?>">
                            👍 <span class="count" id="clikes-<?= $cid ?>"><?= $likes ?></span>
                        </button>
                    </form>

                    <form method="post" action="/comment_react.php" class="d-inline js-comment-react-form" data-no-pjax="1">
                        <input type="hidden" name="csrf" value="<?= g_h(vm_csrf_token()) ?>">
                        <input type="hidden" name="comment_id" value="<?= $cid ?>">
                        <input type="hidden" name="reaction" value="dislike">
                        <input type="hidden" name="back" value="<?= g_h($backToComment) ?>">
                        <button type="submit"
                                class="btn btn-sm <?= g_h($disBtnClass) ?>"
                                data-comment="<?= $cid ?>"
                                data-cmtreact="dislike"
                                title="<?= g_h($disTitle) ?>">
                            👎 <span class="count" id="cdislikes-<?= $cid ?>"><?= $dislikes ?></span>
                        </button>
                    </form>

                    <?php if ($canComment): ?>
                        <button type="button" class="comment-reply-btn" data-reply-toggle="<?= $cid ?>">
                            <?= g_h(g_t('Відповісти','Ответить','Reply')) ?>
                        </button>
                    <?php endif; ?>
                <?php else: ?>
                    <button type="button" class="btn btn-sm btn-outline-success" disabled>
                        👍 <span class="count"><?= $likes ?></span>
                    </button>
                    <button type="button" class="btn btn-sm btn-outline-danger" disabled>
                        👎 <span class="count"><?= $dislikes ?></span>
                    </button>
                <?php endif; ?>
            </div>

            <?php if ($canComment): ?>
                <div class="comment-reply-form d-none" id="reply-form-<?= $cid ?>">
                    <form method="post" action="/functional/comment/create.php" enctype="multipart/form-data" class="vstack gap-2 mt-2">
                        <input type="hidden" name="csrf" value="<?= g_h(vm_csrf_token()) ?>">
                        <input type="hidden" name="post_id" value="<?= $postId ?>">
                        <input type="hidden" name="parent_id" value="<?= $cid ?>">
                        <input type="hidden" name="back" value="<?= g_h($backToComment) ?>">

                        <div class="vm-emoji-wrap">
                            <textarea class="form-control js-emoji-target" name="body" rows="2" placeholder="<?= g_h(g_t('Коментар...', 'Комментарий...', 'Comment...')) ?>"></textarea>
                        </div>

                        <div class="d-flex flex-wrap gap-2 align-items-center justify-content-between">
                            <label class="btn btn-sm btn-outline-secondary mb-0">
                                <?= g_h(g_t('Прикріпити файли', 'Прикрепить файлы', 'Attach files')) ?>
                                <input type="file" name="files[]" multiple hidden
                                       accept="image/*,audio/*,video/*,.pdf,.zip,.rar,.7z,.txt,.doc,.docx,.xls,.xlsx">
                            </label>

                            <div class="d-flex gap-2">
                                <button class="btn btn-sm btn-primary" type="submit"><?= g_h(g_t('Надіслати', 'Отправить', 'Send')) ?></button>
                                <button class="btn btn-sm btn-outline-secondary" type="button" data-reply-cancel="<?= $cid ?>"><?= g_h(g_t('Скасувати', 'Отменить', 'Cancel')) ?></button>
                            </div>
                        </div>
                    </form>
                </div>
            <?php endif; ?>

            <?php
            $repls = $repliesByParent[$cid] ?? [];
            if ($repls):
            ?>
                <div class="comment-replies mt-2">
                    <?php foreach ($repls as $r): ?>
                        <?php g_render_comment($r, $repliesByParent, $commentAttById, $postId, $canComment, $me, $viewerIsAdmin, $isManager, $backUri, true); ?>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>
        </div>
        <?php
    }
}