<?php
session_start();

$searchType = $_GET['search_type'] ?? 'comparisons';
$selectedCategory = $_GET['category'] ?? '';
$search = $_GET['q'] ?? '';

$searchedUsers = [];
if ($search && $searchType === 'users') {
    $search_lower = trim(mb_strtolower($search));
    $allUsers = [];

    $usersDirs = glob("users/*", GLOB_ONLYDIR);

    foreach ($usersDirs as $userDir) {
        $dataFile = $userDir . "/data.json";
        if (file_exists($dataFile)) {
            $userData = json_decode(file_get_contents($dataFile), true);
            if (!$userData) continue;

            $username = $userData['username'] ?? basename($userDir);
            $userId = basename($userDir);

            $bio = '';
            $bioFile = $userDir . "/bio.txt";
            if (file_exists($bioFile)) {
                $bio = file_get_contents($bioFile);
            }

            $username_lower = mb_strtolower(trim($username));
            $matchScore = 0;

            if ($username_lower === $search_lower) {
                $matchScore = 100;
            } elseif (strpos($username_lower, $search_lower) === 0) {
                $matchScore = 80;
            } elseif (strpos($username_lower, $search_lower) !== false) {
                $matchScore = 60;
            } else {
                similar_text($username_lower, $search_lower, $similarity);
                $matchScore = $similarity;
            }

            if ($matchScore > 15) {
                $profileImg = "images/default-avatar.png";
                if (file_exists($userDir . "/profile.jpg")) {
                    $profileImg = "users/$userId/profile.jpg";
                } elseif (file_exists($userDir . "/profile.png")) {
                    $profileImg = "users/$userId/profile.png";
                }

                $allUsers[] = [
                    'id' => $userId,
                    'username' => $username,
                    'similarity' => $matchScore,
                    'profile_img' => $profileImg,
                    'bio' => $bio
                ];
            }
        }
    }

    usort($allUsers, function ($a, $b) {
        return $b['similarity'] <=> $a['similarity'];
    });

    $searchedUsers = array_slice($allUsers, 0, 5);
}

$posts = [];

foreach (glob("posts/*") as $dir) {
    if (!is_dir($dir)) continue;

    $dataFile = "$dir/data.json";
    if (file_exists($dataFile)) {
        $data = json_decode(file_get_contents($dataFile), true);
        if ($data) {
            $data['id'] = basename($dir);
            $data['votes1'] = $data['votes1'] ?? [];
            $data['votes2'] = $data['votes2'] ?? [];
            $data['votes_count'] = count($data['votes1']) + count($data['votes2']);
            $data['published_at'] = $data['published_at'] ?? date('Y-m-d');
            $data['published_at_ts'] = strtotime($data['published_at']);
            $data['category'] = $data['category'] ?? 'General';
            $data['name1'] = $data['name1'] ?? 'Item 1';
            $data['name2'] = $data['name2'] ?? 'Item 2';
            $data['author'] = 'Rankly';
            $data['author_username'] = 'Rankly';
            $data['author_img'] = './images/logo.png';
            $data['source'] = 'main';

            $posts[] = $data;
        }
    }
}

$usersPostsDir = __DIR__ . "/posts/user_posts";
if (is_dir($usersPostsDir)) {
    foreach (glob("$usersPostsDir/*") as $postDir) {
        if (!is_dir($postDir)) continue;

        $dataFile = "$postDir/data.json";
        if (file_exists($dataFile)) {
            $data = json_decode(file_get_contents($dataFile), true);
            if ($data && ($data['request'] ?? true) === false && ($data['status'] ?? false) === true) {
                $data['id'] = basename($postDir);
                $data['source'] = 'user';
                $data['votes1'] = $data['votes1'] ?? [];
                $data['votes2'] = $data['votes2'] ?? [];
                $data['votes_count'] = count($data['votes1']) + count($data['votes2']);
                $data['published_at'] = $data['published_at'] ?? date('Y-m-d');
                $data['published_at_ts'] = strtotime($data['published_at']);
                $data['category'] = $data['category'] ?? 'General';
                $data['name1'] = $data['name1'] ?? 'Item 1';
                $data['name2'] = $data['name2'] ?? 'Item 2';

                $userDir = __DIR__ . "/users/" . ($data['user_id'] ?? '');
                $userDataFile = "$userDir/data.json";
                $get_data = json_decode(file_get_contents($userDataFile), true);
                $username = $data['user_id'] ?? 'Unknown';
                $display_name = $get_data['displayname'];
                $profileImg = "images/default-avatar.png";

                if (file_exists($userDataFile)) {
                    $userData = json_decode(file_get_contents($userDataFile), true);
                    if (isset($userData['username'])) $username = $userData['username'];
                    if (file_exists("$userDir/profile.jpg")) $profileImg = "users/{$data['user_id']}/profile.jpg";
                    elseif (file_exists("$userDir/profile.png")) $profileImg = "users/{$data['user_id']}/profile.png";
                }

                $data['author'] = $display_name;
                $data['author_username'] = $username;
                $data['author_img'] = $profileImg;

                if (!$selectedCategory || $data['category'] === $selectedCategory) {
                    $posts[] = $data;
                }
            }
        }
    }
}

usort($posts, function ($a, $b) {
    $days_a = (time() - ($a['published_at_ts'] ?? time())) / 86400;
    $days_b = (time() - ($b['published_at_ts'] ?? time())) / 86400;
    $days_a = $days_a > 3 ? 3 : $days_a;
    $days_b = $days_b > 3 ? 3 : $days_b;

    $votes_count_a = $a['votes_count'] ?? 0;
    $votes_count_b = $b['votes_count'] ?? 0;

    if ($votes_count_b === $votes_count_a) {
        return $days_a <=> $days_b;
    }
    return $votes_count_b <=> $votes_count_a;
});

if ($search && $searchType !== 'users') {
    $search_lower = mb_strtolower($search);
    usort($posts, function ($a, $b) use ($search_lower) {
        $name_a = mb_strtolower(($a['name1'] ?? '') . ' ' . ($a['name2'] ?? ''));
        $name_b = mb_strtolower(($b['name1'] ?? '') . ' ' . ($b['name2'] ?? ''));
        similar_text($name_a, $search_lower, $percent_a);
        similar_text($name_b, $search_lower, $percent_b);
        return $percent_b <=> $percent_a;
    });
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['post_id'], $_POST['vote'])) {
    header('Content-Type: application/json');

    if (!isset($_SESSION['user_id'])) exit;

    $username = $_SESSION['user_id'];
    $postId = basename($_POST['post_id']);
    $vote = intval($_POST['vote']);

    $normalFile = __DIR__ . "/posts/$postId/data.json";
    $userFile   = __DIR__ . "/posts/user_posts/$postId/data.json";

    if (file_exists($normalFile)) {
        $dataFile = $normalFile;
    } elseif (file_exists($userFile)) {
        $dataFile = $userFile;
    } else {
        exit;
    }

    $data = json_decode(file_get_contents($dataFile), true);

    if (!isset($data['votes1'])) $data['votes1'] = [];
    if (!isset($data['votes2'])) $data['votes2'] = [];

    $alreadyVoted1 = in_array($username, $data['votes1']);
    $alreadyVoted2 = in_array($username, $data['votes2']);

    $data['votes1'] = array_values(array_diff($data['votes1'], [$username]));
    $data['votes2'] = array_values(array_diff($data['votes2'], [$username]));

    if ($vote === 1 && !$alreadyVoted1) {
        $data['votes1'][] = $username;
    } elseif ($vote === 2 && !$alreadyVoted2) {
        $data['votes2'][] = $username;
    }

    file_put_contents($dataFile, json_encode($data, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT));

    echo json_encode([
        'status' => 'success',
        'votes1' => count($data['votes1']),
        'votes2' => count($data['votes2']),
        'user_vote' => $alreadyVoted1 || $alreadyVoted2 ? 0 : $vote
    ]);
    exit;
}
?>

<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="icon" type="image/png" href="/images/favicon.png">
    <title>Rankly / Explore</title>
</head>

<body>
    <?php include "header.php"; ?>

    <div class="px-4 sm:px-6 md:px-8 max-w-full mx-auto flex flex-col gap-4">
        <div class="relative w-full max-w-lg mx-auto">
            <input type="text" id="search-input"
                class="w-full p-3 bg-[#ffffff12] pr-10 border border-transparent rounded-lg text-left text-white placeholder-white outline-none
                  focus:border-[#ffffff25]">

            <div id="custom-placeholder"
                class="absolute left-4 top-1/2 -translate-y-1/2 pointer-events-none flex items-center gap-2 text-[15px] text-gray-300">
                <span>search for</span>
                <span class="px-1 py-0.5 bg-white/10 rounded-md">comparison name</span>
                <span>or</span>
                <span class="px-1 py-0.5 bg-white/10 rounded-md">user</span>
            </div>

            <span id="clear-search"
                class="absolute top-1/2 right-3 -translate-y-1/2 cursor-pointer text-gray-400 hover:text-gray-200 transition-colors text-xl font-bold">
                <i data-lucide="x" class="w-5 h-5"></i>
            </span>

            <script>
                const input = document.getElementById("search-input");
                const placeholder = document.getElementById("custom-placeholder");
                const clearBtn = document.getElementById("clear-search");

                function updatePlaceholderVisibility() {
                    if (input.value.trim() === "") {
                        placeholder.style.opacity = "1";
                    } else {
                        placeholder.style.opacity = "0";
                    }
                }
                input.addEventListener("input", updatePlaceholderVisibility);
                clearBtn.addEventListener("click", () => {
                    input.value = "";
                    input.focus();
                    updatePlaceholderVisibility();
                });
                updatePlaceholderVisibility();
            </script>
        </div>

        <div class="flex justify-between ml-[0.5px] mb-4 gap-4">
            <button id="search-comparisons-btn" class="search-type-btn w-[100%] active px-6 py-2 bg-[#ffffff12] text-white rounded-lg font-medium transition-all duration-300">
                Comparisons
            </button>
            <button id="search-users-btn" class="search-type-btn w-[100%] px-6 py-2 bg-[#ffffff12] text-white rounded-lg font-medium transition-all duration-300">
                Search Users
            </button>
        </div>

        <div id="categories-section" class="relative mt-[-14px] mb-8">
            <div class="overflow-x-auto scrollbar-hide mr-1" style="direction: ltr;">
                <div class="flex flex-row-reverse gap-3 min-w-max" style="direction: rtl;">
                    <?php
                    $categories = [
                        'Technology & Devices',
                        'Entertainment & Media',
                        'Games & Platforms',
                        'Lifestyle & Style',
                        'Food & Taste',
                        'Places & Travel',
                        'People & Public Figures',
                        'Cars & Tools',
                        'Life & Beliefs',
                        'Brands & Companies',
                        'Products & Instruments',
                        'Money & Services',
                        'Education & Learning',
                        'Memes & Culture',
                    ];
                    foreach ($categories as $cat): ?>
                        <a href="javascript:void(0);"
                            class="category-link flex-shrink-0 px-4 py-3 text-white rounded-[12px] border-[1px] border-[#ffffff25] text-[12.5px] font-medium transition-all duration-300 hover:bg-white/10"
                            data-category="<?= htmlspecialchars($cat) ?>">
                            <?= htmlspecialchars($cat) ?>
                        </a>
                    <?php endforeach; ?>
                </div>
            </div>
        </div>
    </div>

    <div class="mb-5 max-w-4xl mx-auto sm:px-6 md:px-8">
        <?php if ($search && $searchType === 'users' && !empty($searchedUsers)): ?>
            <div id="users-results" class="space-y-1">
                <?php foreach ($searchedUsers as $user): ?>
                    <div class="bg-[#ffffff08] p-4 transition-all duration-300 hover:bg-[#ffffff20]">
                        <?php if (isset($_SESSION['user_id'])): ?>
                            <a href="show_profile.php?user_id=<?= $user['id'] ?>" class="flex items-center gap-4">
                                <img src="<?= $user['profile_img'] ?>"
                                    alt="<?= htmlspecialchars($user['username']) ?>"
                                    class="w-14 h-14 rounded-full object-cover border-2 border-white/20">

                                <div class="flex-1">
                                    <div class="flex items-center gap-2 mb-1">
                                        <h3 class="text-white font-semibold text-lg"><?= htmlspecialchars($user['username']) ?></h3>
                                    </div>

                                    <p class="text-gray-300 text-sm line-clamp-2">
                                        <?php
                                        $bio = $user['bio'];
                                        if (mb_strlen($bio) > 27) {
                                            echo htmlspecialchars(mb_substr($bio, 0, 27)) . '...';
                                        } else {
                                            echo htmlspecialchars($bio);
                                        }
                                        ?>
                                    </p>
                                </div>
                            </a>
                        <?php else: ?>
                            <a href="login.php" class="flex items-center gap-4">
                                <img src="<?= $user['profile_img'] ?>"
                                    alt="<?= htmlspecialchars($user['username']) ?>"
                                    class="w-14 h-14 rounded-full object-cover border-2 border-white/20">

                                <div class="flex-1">
                                    <div class="flex items-center gap-2 mb-1">
                                        <h3 class="text-white font-semibold text-lg"><?= htmlspecialchars($user['username']) ?></h3>
                                    </div>

                                    <p class="text-gray-300 text-sm line-clamp-2">
                                        <?php
                                        $bio = $user['bio'];
                                        if (mb_strlen($bio) > 27) {
                                            echo htmlspecialchars(mb_substr($bio, 0, 27)) . '...';
                                        } else {
                                            echo htmlspecialchars($bio);
                                        }
                                        ?>
                                    </p>
                                </div>
                            </a>
                        <?php endif; ?>
                    </div>
                <?php endforeach; ?>
            </div>

        <?php elseif ($search && $searchType === 'users' && empty($searchedUsers)): ?>
            <div class="text-center py-12">
                <i data-lucide="user-x" class="w-20 h-20 text-gray-500 mx-auto mb-4"></i>
                <p class="text-gray-400 text-lg">User Not Found</p>
                <p class="text-gray-500 text-sm mt-2">search for a username more precisely</p>
            </div>

        <?php else: ?>
            <div id="posts-container" class="space-y-[10px]">
                <?php foreach ($posts as $post): ?>
                    <div class="relative bg-[#ffffff06] flex flex-col overflow-hidden post-item"
                        id="post-<?= $post['id'] ?>">
                        <div class="flex items-center p-4 pt-3 pb-3 border-b border-[#ffffff25] justify-between">
                            <?php if (isset($_SESSION['user_id'])): ?>
                                <div class="clickable-profile" data-user-id="<?= $post['user_id'] ?? '' ?>" data-is-rankly="<?= ($post['author'] === 'Rankly' || empty($post['user_id'])) ? 'true' : 'false' ?>">
                                    <?php
                                    $author_name = htmlspecialchars($post['author'] ?? 'Rankly');
                                    $author_username = htmlspecialchars($post['author_username'] ?? 'Rankly');
                                    $author_img = $post['author_img'] ?? './images/logo.png';
                                    $is_rankly = $author_name === 'Rankly' || $author_username === 'Rankly';
                                    ?>
                                    <div class="flex items-center gap-2">
                                        <img src="<?= $author_img ?>" alt="<?= $author_name ?>" class="w-10 h-10 rounded-full object-cover">
                                        <div class="flex flex-col items-start">
                                            <div class="flex items-center gap-1">
                                                <span class="font-semibold text-[15px] text-white"><?= $author_name ?></span>
                                                <?php if ($is_rankly): ?>
                                                    <i data-lucide="circle-check" class="text-[#6AB3F3] w-4 h-4"></i>
                                                <?php endif; ?>
                                            </div>
                                            <span class="font-medium text-[10px] text-gray-400">@<?= $author_username ?></span>
                                        </div>
                                    </div>
                                </div>
                            <?php else: ?>
                                <a href="login.php">
                                    <div class="clickable-profile" data-user-id="<?= $post['user_id'] ?? '' ?>" data-is-rankly="<?= ($post['author'] === 'Rankly' || empty($post['user_id'])) ? 'true' : 'false' ?>">
                                        <?php
                                        $author_name = htmlspecialchars($post['author'] ?? 'Rankly');
                                        $author_username = htmlspecialchars($post['author_username'] ?? 'Rankly');
                                        $author_img = $post['author_img'] ?? './images/logo.png';
                                        $is_rankly = $author_name === 'Rankly' || $author_username === 'Rankly';
                                        ?>
                                        <div class="flex items-center gap-2">
                                            <img src="<?= $author_img ?>" alt="<?= $author_name ?>" class="w-10 h-10 rounded-full object-cover">
                                            <div class="flex flex-col items-start">
                                                <div class="flex items-center gap-1">
                                                    <span class="font-semibold text-[15px] text-white"><?= $author_name ?></span>
                                                    <?php if ($is_rankly): ?>
                                                        <i data-lucide="circle-check" class="text-[#6AB3F3] w-4 h-4"></i>
                                                    <?php endif; ?>
                                                </div>
                                                <span class="font-medium text-[10px] text-gray-400">@<?= $author_username ?></span>
                                            </div>
                                        </div>
                                    </div>
                                </a>
                            <?php endif; ?>

                            <div class="flex ml-2">
                                <button class="comment-btn text-white py-1 px-4 rounded-lg flex items-center gap-1"
                                    data-post-id="<?= $post['id'] ?>">
                                    <i data-lucide="message-circle" class="w-4 h-4"></i>
                                    <span class="comment-count ml-1"><?= count($post['comments'] ?? []) ?></span>
                                </button>
                            </div>
                        </div>
                        <div class="flex justify-center items-center px-4 mt-4 gap-2 rtl text-gray-400 text-sm">
                            <i data-lucide="tag" class="w-4 h-4"></i>
                            <span><?= htmlspecialchars($post['category'] ?? 'General') ?></span>
                            <span>|</span>
                            <i data-lucide="calendar" class="w-4 h-4"></i>
                            <span><?= date('Y/m/d', strtotime($post['published_at'] ?? date('Y-m-d'))) ?></span>
                        </div>
                        <div class="flex flex-row justify-center items-start gap-4 p-4 pb-1">
                            <?php for ($i = 1; $i <= 2; $i++): ?>
                                <?php
                                $votedClass = '';
                                if (isset($_SESSION['user_id'])) {
                                    if (in_array($_SESSION['user_id'], $post['votes1'] ?? []) && $i === 1) $votedClass = 'border-white border-2';
                                    if (in_array($_SESSION['user_id'], $post['votes2'] ?? []) && $i === 2) $votedClass = 'border-white border-2';
                                }
                                ?>
                                <div class="flex flex-col items-center mb-5 flex-1">
                                    <?php
                                    $basePath = $post['source'] === 'user'
                                        ? "posts/user_posts/{$post['id']}/image_{$i}"
                                        : "posts/{$post['id']}/image_{$i}";

                                    $ext = file_exists($basePath . ".jpg") ? "jpg" : (file_exists($basePath . ".png") ? "png" : "");
                                    ?>
                                    <div class="aspect-square w-full max-w-[120px] rounded-lg overflow-hidden row-start-1">
                                        <img src="<?= $basePath . '.' . $ext ?>"
                                            alt="<?= htmlspecialchars($post["name$i"]) ?>"
                                            class="w-full h-full object-cover">
                                    </div>

                                    <div class="min-h-[3rem] flex items-center justify-center row-start-2 w-full">
                                        <p class="text-sm text-white text-center line-clamp-2 font_inter w-full px-2">
                                            <?= htmlspecialchars($post["name$i"]) ?>
                                        </p>
                                    </div>

                                    <div class="row-start-3 mt-0">
                                        <?php if (isset($_SESSION['user_id'])): ?>
                                            <form method="post" class="vote-form" data-post-id="<?= $post['id'] ?>" data-vote="<?= $i ?>" style="display:inline">
                                                <input type="hidden" name="post_id" value="<?= $post['id'] ?>">
                                                <input type="hidden" name="vote" value="<?= $i ?>">
                                                <button type="submit" class="vote-btn bg-[#ffffff25] text-white text-center py-1 px-11 rounded-lg flex items-center gap-1 <?= $votedClass ?>">
                                                    <i data-lucide="thumbs-up" class="icon w-4 h-4 mb-1"></i>
                                                    <span class="count"><?= count($post["votes$i"]) ?></span>
                                                </button>
                                            </form>
                                        <?php else: ?>
                                            <a href="login.php" class="vote-btn bg-[#ffffff25] text-white text-center py-1 px-11 rounded-lg flex items-center gap-1">
                                                <i data-lucide="thumbs-up" class="icon w-4 h-4 mb-1"></i>
                                                <span class="count"><?= count($post["votes$i"]) ?></span>
                                            </a>
                                        <?php endif; ?>
                                    </div>
                                </div>
                                <?php if ($i == 1): ?>
                                    <div class="text-white font-semibold text-lg mt-[14%] select-none flex items-center justify-center h-full">
                                        OR
                                    </div>
                                <?php endif; ?>
                                <div class="absolute left-1/2 bottom-0 w-[2px] mx-auto">
                                    <div class="h-[250px] bg-gradient-to-b from-transparent via-[#ffffff15] to-transparent mx-auto"></div>
                                </div>
                            <?php endfor; ?>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>
    </div>

    <script>
        function initVoteForms() {
            document.querySelectorAll('.vote-form').forEach(form => {
                if (!form.dataset.listenerAdded) {
                    form.addEventListener('submit', function(e) {
                        e.preventDefault();

                        const postId = this.dataset.postId;
                        const vote = this.dataset.vote;
                        const formData = new FormData(this);

                        fetch('index.php', {
                                method: 'POST',
                                body: formData
                            })
                            .then(res => res.json())
                            .then(data => {
                                if (data.status === 'success') {
                                    const postDiv = this.closest('.flex.flex-row');
                                    if (postDiv) {
                                        const voteBtns = postDiv.querySelectorAll('.vote-btn');
                                        const countSpans = postDiv.querySelectorAll('.count');
                                        countSpans[0].textContent = data.votes1;
                                        countSpans[1].textContent = data.votes2;

                                        if (data.user_vote === 0) {
                                            voteBtns.forEach(btn => btn.classList.remove('border-white', 'border-2'));
                                        } else {
                                            voteBtns.forEach(btn => btn.classList.remove('border-white', 'border-2'));
                                            const votedBtn = postDiv.querySelector(`.vote-form[data-vote="${vote}"] .vote-btn`);
                                            if (votedBtn) votedBtn.classList.add('border-white', 'border-2');
                                        }
                                    }
                                }
                            });
                    });
                    form.dataset.listenerAdded = "true";
                }
            });
        }

        initVoteForms();

        document.addEventListener("DOMContentLoaded", () => {

            const searchInput = document.getElementById("search-input");
            const clearBtn = document.getElementById("clear-search");

            const searchComparisonsBtn = document.getElementById("search-comparisons-btn");
            const searchUsersBtn = document.getElementById("search-users-btn");
            const categoriesSection = document.getElementById("categories-section");

            const MAIN_CONTAINER_SELECTOR = ".mb-5.max-w-4xl.mx-auto";
            let currentSearchType = "<?= $searchType ?>";

            function setActiveSearchType(type) {
                currentSearchType = type;

                if (type === "comparisons") {
                    searchComparisonsBtn.classList.add("active", "bg-[#ffffff50]");
                    searchUsersBtn.classList.remove("active", "bg-[#ffffff50]");
                    categoriesSection.style.display = "block";
                } else {
                    searchUsersBtn.classList.add("active", "bg-[#ffffff50]");
                    searchComparisonsBtn.classList.remove("active", "bg-[#ffffff50]");
                    categoriesSection.style.display = "none";
                }

                if (searchInput.value.trim().length > 0) {
                    performSearch();
                }
            }

            function performSearch() {
                const query = searchInput.value.trim();
                const url = new URL(window.location.href);

                if (query !== "") {
                    url.searchParams.set("q", query);
                    url.searchParams.set("search_type", currentSearchType);

                    url.searchParams.delete("category");

                } else {
                    url.searchParams.delete("q");
                    url.searchParams.delete("search_type");

                }

                window.history.replaceState({}, "", url);

                fetch(url)
                    .then(res => res.text())
                    .then(html => {
                        const parser = new DOMParser();
                        const doc = parser.parseFromString(html, "text/html");

                        const newContent = doc.querySelector(MAIN_CONTAINER_SELECTOR);
                        const container = document.querySelector(MAIN_CONTAINER_SELECTOR);

                        if (newContent && container) {
                            container.innerHTML = newContent.innerHTML;
                            initVoteForms();
                            rebindCategoryListeners();
                            if (window.lucide) lucide.createIcons();
                        }
                    })
                    .catch(err => console.error("Search failed:", err));
            }


            function rebindCategoryListeners() {
                document.querySelectorAll(".category-link").forEach(link => {
                    link.onclick = (e) => {
                        e.preventDefault();

                        const category = link.dataset.category;
                        const url = new URL(window.location.href);

                        const currentQ = searchInput.value.trim();
                        if (currentQ) {
                            url.searchParams.set("q", currentQ);
                            url.searchParams.set("search_type", currentSearchType);
                        }

                        url.searchParams.set("category", category);

                        window.history.pushState({}, "", url);

                        fetch(url)
                            .then(res => res.text())
                            .then(html => {
                                const parser = new DOMParser();
                                const doc = parser.parseFromString(html, "text/html");

                                const newPosts = doc.querySelector("#posts-container");
                                const posts = document.querySelector("#posts-container");

                                if (newPosts && posts) {
                                    posts.innerHTML = newPosts.innerHTML;
                                    initVoteForms();
                                    if (window.lucide) lucide.createIcons();
                                }
                            })
                            .catch(err => console.error("Category fetch failed:", err));
                    };
                });
            }

            searchInput.addEventListener("input", () => {
                const safe = searchInput.value.replace(/[^\p{L}\p{N}\s_]/gu, "");
                if (safe !== searchInput.value) searchInput.value = safe;
                performSearch();
            });

            clearBtn.addEventListener("click", () => {
                searchInput.value = "";
                const url = new URL(window.location.href);
                url.searchParams.delete("q");
                url.searchParams.delete("search_type");
                url.searchParams.delete("category");
                window.history.replaceState({}, "", url);
                performSearch();
            });

            searchComparisonsBtn.onclick = () => setActiveSearchType("comparisons");
            searchUsersBtn.onclick = () => setActiveSearchType("users");

            setActiveSearchType(currentSearchType);
            rebindCategoryListeners();

        });

        document.querySelectorAll('.vote-btn').forEach(btn => {
            btn.addEventListener('click', function(e) {
                this.style.animation = 'none';
                void this.offsetWidth;
                this.style.animation = 'active_vote_btn 2s';
                this.addEventListener('animationend', () => {
                    this.style.animation = '';
                }, {
                    once: true
                });
            });
        });

        document.addEventListener('DOMContentLoaded', () => {
            const commentLayer = document.getElementById('comment-layer');
            const commentBody = document.getElementById('comment-body');
            const commentTitle = document.getElementById('comment-title');
            const closeLayerBtn = document.getElementById('close-comment-layer');
            const commentBtns = document.querySelectorAll('.comment-btn');
            const loginPrompt = document.getElementById('login-prompt');
            const inputWrapper = document.getElementById('input-wrapper');
            const commentInput = document.getElementById('comment-input');
            const sendComment = document.getElementById('send-comment');

            let currentPostId = null;
            const isLoggedIn = <?= isset($_SESSION['user_id']) ? 'true' : 'false' ?>;

            let scrollY = 0;

            commentBtns.forEach(btn => {
                btn.addEventListener('click', () => {
                    currentPostId = btn.dataset.postId;

                    scrollY = window.scrollY;

                    document.body.style.overflow = 'hidden';
                    document.documentElement.style.overflow = 'hidden';


                    commentLayer.style.height = '60%';
                    commentLayer.style.position = 'fixed';
                    commentLayer.style.left = 0;
                    commentLayer.style.right = 0;
                    commentLayer.style.zIndex = '10000';

                    loadComments(currentPostId);

                    const overlay = document.createElement('div');
                    overlay.id = 'comment-overlay';
                    overlay.style.position = 'fixed';
                    overlay.style.top = '0';
                    overlay.style.left = '0';
                    overlay.style.width = '100%';
                    overlay.style.height = '100%';
                    overlay.style.zIndex = '9999';
                    overlay.style.background = 'rgba(0,0,0,0)';
                    document.body.appendChild(overlay);
                });
            });

            closeLayerBtn.addEventListener('click', () => {
                commentLayer.style.height = '0';
                commentBody.innerHTML = '';

                document.body.style.overflow = '';
                document.documentElement.style.overflow = '';

                document.documentElement.style.scrollBehavior = 'auto';
                window.scrollTo(0, scrollY);
                document.documentElement.style.scrollBehavior = '';

                const overlay = document.getElementById('comment-overlay');
                if (overlay) overlay.remove();
            });

            sendComment.addEventListener('click', () => {
                const text = commentInput.value.trim();
                if (!text) return;
                fetch('posts/comment/add_comment.php', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({
                            post_id: currentPostId,
                            text
                        })
                    })
                    .then(res => res.text())
                    .then(() => {
                        commentInput.value = '';
                        loadComments(currentPostId);
                    });
            });

            function loadComments(postId) {
                fetch(`posts/comment/load_comments.php?post_id=${postId}`)
                    .then(res => res.json())
                    .then(data => {
                        commentBody.innerHTML = '';
                        commentTitle.textContent = `Comments`;

                        data.sort((a, b) => (b.likes - b.dislikes) - (a.likes - a.dislikes));

                        data.forEach(c => {
                            const div = document.createElement('div');
                            div.className = 'flex flex-col p-4 bg-[#ffffff05] rounded-[12px] transition-all duration-300';
                            div.dataset.commentId = c.id;

                            const header = document.createElement('div');
                            header.className = 'flex justify-between items-center mb-1';
                            header.innerHTML = `
        <div class="flex items-center gap-2">
            <img src="${c.profile}" class="w-6 h-6 rounded-[6px] object-cover">
            <span class="font-bold text-white">${c.username}</span>
        </div>
        <span class="text-xs text-gray-500">${c.date}</span>
    `;

                            const commentText = document.createElement('p');
                            commentText.style.direction = 'ltr';
                            commentText.style.whiteSpace = 'pre-wrap';
                            commentText.className = 'mb-1 mt-3 text-left text-[14.5px] text-gray-200 break-words preserve-whitespace';
                            commentText.innerHTML = linkify(c.text);


                            const actions = document.createElement('div');
                            actions.className = 'flex gap-4 mt-3 ml-1 items-center text-sm';

                            let deleteBtnHTML = '';
                            if (c.user === "<?= $_SESSION['user_id'] ?? '' ?>") {
                                deleteBtnHTML = `<button class="delete-comment-btn mr-1"><i data-lucide="trash" class="text-[#ffffff75] w-[15px] h-[15px]"></i></button>`;
                            }

                            actions.innerHTML = `
        <button class="like-btn flex items-center gap-1 text-[#ffffff75]" data-user="<?= $_SESSION['user_id'] ?? '' ?>">
            <i data-lucide="thumbs-up" class="mr-[0.5px] w-[14px] h-[14px]"></i>
            <span>${c.likes}</span>
        </button>
        <button class="dislike-btn flex items-center gap-1 text-[#ffffff75]" data-user="<?= $_SESSION['user_id'] ?? '' ?>">
            <i data-lucide="thumbs-down" class="mr-[0.5px] w-[14px] h-[14px]"></i>
            <span>${c.dislikes}</span>
        </button>
        <div class="ml-auto">${deleteBtnHTML}</div>
    `;
                            div.appendChild(header);
                            div.appendChild(commentText);
                            div.appendChild(actions);

                            commentBody.appendChild(div);
                            lucide.createIcons();

                            if (c.user === "<?= $_SESSION['user_id'] ?? '' ?>") {
                                const delBtn = div.querySelector('.delete-comment-btn');
                                delBtn.addEventListener('click', () => deleteCommentAnimated(postId, c.id));
                            }

                            const likeBtn = div.querySelector('.like-btn');
                            const dislikeBtn = div.querySelector('.dislike-btn');

                            likeBtn.addEventListener('click', () => voteCommentAnimated(postId, c.id, 'like', div, likeBtn, dislikeBtn));
                            dislikeBtn.addEventListener('click', () => voteCommentAnimated(postId, c.id, 'dislike', div, likeBtn, dislikeBtn));
                        });

                        if (isLoggedIn) {
                            loginPrompt.style.display = 'none';
                            inputWrapper.style.display = 'flex';
                        } else {
                            loginPrompt.style.display = 'flex';
                            inputWrapper.style.display = 'none';
                        }
                    });
            }

            function linkify(text) {
                const urlRegex = /(https?:\/\/[^\s]+)/g;

                return text.replace(urlRegex, (url) => {
                    return `<a href="${url}" target="_blank" rel="noopener noreferrer" 
                   style="color:#56aaff; text-decoration: underline;">
                   ${url}
                </a>`;
                });
            }

            function deleteCommentAnimated(postId, commentId) {
                const commentDiv = document.querySelector(`[data-comment-id="${commentId}"]`);
                if (!commentDiv) return;

                fetch('posts/comment/delete_comment.php', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({
                            post_id: postId,
                            comment_id: commentId
                        })
                    })
                    .then(res => res.json())
                    .then(data => {
                        if (data.status === 'success') {
                            document.querySelector(`.comment-btn[data-post-id="${postId}"] .comment-count`).textContent = data.count;
                            commentDiv.style.transition = 'opacity 0.3s ease, transform 0.3s ease';
                            commentDiv.style.opacity = '0';
                            commentDiv.style.transform = 'translateY(-10px)';
                            setTimeout(() => commentDiv.remove(), 300);
                        } else {
                            alert(data.message);
                        }
                    });
            }

            function voteCommentAnimated(postId, commentId, type, commentDiv, likeBtn, dislikeBtn) {
                fetch('posts/comment/vote_comment.php', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({
                            post_id: postId,
                            comment_id: commentId,
                            type
                        })
                    })
                    .then(res => res.text())
                    .then(text => {
                        if (!text) return;
                        let data;
                        try {
                            data = JSON.parse(text);
                        } catch (e) {
                            return;
                        }

                        if (data.likes !== undefined && data.dislikes !== undefined) {
                            likeBtn.querySelector('span').textContent = data.likes;
                            dislikeBtn.querySelector('span').textContent = data.dislikes;

                            commentDiv.style.transition = 'background-color 0.4s';
                            commentDiv.style.backgroundColor = 'rgba(255,255,255,0.1)';
                            setTimeout(() => {
                                commentDiv.style.backgroundColor = '#ffffff05';
                            }, 400);
                        }
                    });
            }

            function deleteComment(postId, commentId) {
                fetch('posts/comment/delete_comment.php', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({
                            post_id: postId,
                            comment_id: commentId
                        })
                    })
                    .then(res => res.json())
                    .then(data => {
                        if (data.status === 'success') {
                            loadComments(postId);
                            document.querySelector(`.comment-btn[data-post-id="${postId}"] .comment-count`).textContent = data.count;
                        } else {
                            alert(data.message);
                        }
                    });
            }

            function voteComment(postId, commentId, type, likeBtn, dislikeBtn) {
                fetch('posts/comment/vote_comment.php', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({
                            post_id: postId,
                            comment_id: commentId,
                            type
                        })
                    })
                    .then(res => res.text())
                    .then(text => {
                        if (!text) return;
                        let data;
                        try {
                            data = JSON.parse(text);
                        } catch (e) {
                            return;
                        }
                        if (data.likes !== undefined && data.dislikes !== undefined) {
                            likeBtn.querySelector('span').textContent = data.likes;
                            dislikeBtn.querySelector('span').textContent = data.dislikes;
                        }
                    })
            }

        });

        document.addEventListener("click", function(e) {
            if (e.target.classList.contains("spoiler")) {
                e.target.classList.add("revealed");
            }
        });

        document.addEventListener('DOMContentLoaded', function() {
            const scrollToPostId = sessionStorage.getItem('scrollToPost');

            if (scrollToPostId) {
                sessionStorage.removeItem('scrollToPost');

                setTimeout(() => {
                    const targetPost = document.getElementById(`post-${scrollToPostId}`);

                    if (targetPost) {
                        targetPost.scrollIntoView({
                            behavior: 'smooth',
                            block: 'start'
                        });

                        targetPost.style.transition = 'all 0.5s ease';
                        targetPost.style.backgroundColor = 'rgba(255,255,255,0.2)';
                        targetPost.style.boxShadow = '0 0 30px rgba(255,255,255,0.1)';

                        setTimeout(() => {
                            targetPost.style.backgroundColor = '';
                            targetPost.style.boxShadow = '';
                        }, 2000);
                    }
                }, 500);
            }
        });

        document.addEventListener('DOMContentLoaded', function() {
            document.querySelectorAll('.clickable-profile').forEach(profile => {
                profile.addEventListener('click', function(e) {
                    e.stopPropagation();

                    const userId = this.dataset.userId;
                    const isRankly = this.dataset.isRankly === 'true';

                    if (isRankly || !userId) {
                        return;
                    }
                    this.style.opacity = '0.6';
                    this.style.transition = 'opacity 0.2s ease';

                    setTimeout(() => {
                        this.style.opacity = '1';

                        const currentUserId = '<?= $_SESSION['user_id'] ?? '' ?>';
                        if (userId === currentUserId) {
                            window.location.href = 'profile.php';
                        } else {
                            window.location.href = `show_profile.php?user_id=${userId}`;
                        }
                    }, 200);
                });
            });
        });

        document.addEventListener("DOMContentLoaded", () => {
            const textarea = document.getElementById("comment-input");
            const counter = document.getElementById("char-counter");

            const maxChars = 428;

            function updateCounter() {
                let val = textarea.value;

                if (val.length > maxChars) {
                    val = val.substring(0, maxChars);
                    textarea.value = val;
                }

                const remaining = maxChars - val.length;

                counter.textContent = remaining;

                if (remaining === 0) {
                    counter.style.color = "#ff4444";
                } else {
                    counter.style.color = "#ffffff75";
                }
            }

            textarea.addEventListener("input", updateCounter);

            updateCounter();
        });
    </script>

    <?php include "footer-nav.php"; ?>

    <div id="comment-layer" style="box-shadow: 0 -20px 50px rgba(0, 0, 0, 0.69);" class="fixed bottom-0 left-0 w-full h-0 bg-[#181818] backdrop-blur-sm overflow-hidden transition-all duration-500 z-50 rounded-t-[12px] flex flex-col">
        <div class="relative p-4 border-b border-[#ffffff25] flex justify-start items-center flex-shrink-0">
            <h3 class="text-lg ml-2 text-white font-medium" id="comment-title"></h3>
            <button id="close-comment-layer" class="absolute right-4 text-gray-500 font-bold text-xl">
                <i data-lucide="x" class="text-white w-[25px] h-[25px]"></i>
            </button>
        </div>

        <div id="comment-body" class="flex-1 p-4 overflow-y-auto flex flex-col gap-4"></div>

        <div id="comment-input-container" class="pt-1 flex-shrink-0">
            <div id="login-prompt" class="flex gap-2 text-sm text-white justify-center mb-5">
                <span>If you have an account</span>
                <a href="login.php" class="text-gray-400">log in</a>
                <span class="text-white">If not</span>
                <a href="login.php" class="text-gray-400">Register</a>
            </div>

            <div id="input-wrapper" class="flex-col hidden w-full border-t-[1px] border-[#ffffff10]">
                <div class="relative w-full mb-2 mt-1 ml-1">
                    <textarea
                        id="comment-input"
                        rows="1"
                        class="w-full h-[75px] bg-[#181818] text-left text-white pr-[95px] pl-4 py-3 border border-transparent rounded-lg placeholder-[#ffffff85] outline-none text-sm resize-y overflow-y-auto"
                        style="direction: ltr; resize: none;"
                        placeholder="Enter your comment"></textarea>
                    <button id="send-comment" class="absolute right-5 top-6 -translate-y-1/2 bg-[#ffffff] py-[1px] px-4 rounded-[5px] text-black text-[15px]">Send</button>
                </div>
                <div class="flex row justify-end absolute left-3 bottom-0 -translate-y-1/2">
                    <span id="char-counter"
                        class="text-right text-[11px] text-[#ffffff75]">
                    </span>
                </div>
            </div>
        </div>
    </div>
</body>

<script>
    lucide.createIcons();
</script>