<?php
/**
 * Directory Homepage
 */
require_once 'config.php';
require_once 'db.php';

// Capture filters
$search_q = isset($_GET['q']) ? trim($_GET['q']) : '';
$platform = isset($_GET['platform']) ? trim($_GET['platform']) : '';
$category = isset($_GET['category']) ? trim($_GET['category']) : 'all';
$country = isset($_GET['country']) ? trim($_GET['country']) : 'all';
$type = isset($_GET['type']) ? trim($_GET['type']) : 'all';
$sort = isset($_GET['sort']) ? trim($_GET['sort']) : 'newest';
$page = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;

// Page Caching (Bypass if AJAX request)
$is_ajax = (isset($_GET['ajax']) && $_GET['ajax'] === '1');
if (!$is_ajax) {
    $cache_key = "index_" . md5(serialize([$search_q, $platform, $category, $country, $type, $sort, $page]));
    $cached_html = get_page_cache($cache_key);
    if ($cached_html !== false) {
        echo $cached_html;
        exit;
    }
}

ob_start();

// Set platform variable for header dynamic theme
$active_platform = in_array($platform, ['whatsapp', 'telegram']) ? $platform : '';

// Build dynamic WHERE clause
$where_clauses = ["`status` = 'approved'"];
$sql_params = [];

if (!empty($search_q)) {
    $where_clauses[] = "(`title` LIKE ? OR `description` LIKE ? OR `tags` LIKE ?)";
    $search_param = "%$search_q%";
    $sql_params[] = $search_param;
    $sql_params[] = $search_param;
    $sql_params[] = $search_param;
}

if ($active_platform) {
    $where_clauses[] = "`platform` = ?";
    $sql_params[] = $active_platform;
}

if ($category !== 'all') {
    $where_clauses[] = "`category_id` = ?";
    $sql_params[] = intval($category);
}

if ($country !== 'all') {
    $where_clauses[] = "`country_id` = ?";
    $sql_params[] = intval($country);
}

if ($type !== 'all' && in_array($type, ['group', 'channel'])) {
    $where_clauses[] = "`type` = ?";
    $sql_params[] = $type;
}

$where_sql = implode(" AND ", $where_clauses);

// Determine Order
$order_sql = "`created_at` DESC";
if ($sort === 'popular') {
    $order_sql = "`hearts` DESC, `created_at` DESC";
}

// Pagination Logic
$homepage_limit = get_setting('homepage_limit');
$limit = !empty($homepage_limit) ? max(1, intval($homepage_limit)) : 12;
$offset = ($page - 1) * $limit;

try {
    // Get total count
    $count_stmt = $pdo->prepare("SELECT COUNT(*) FROM `listings` WHERE $where_sql");
    $count_stmt->execute($sql_params);
    $total_listings = $count_stmt->fetchColumn();
    $total_pages = ceil($total_listings / $limit);

    // Get listings with category and country details
    $listings_sql = "SELECT l.*, c.name AS category_name, co.name AS country_name, co.code AS country_code 
                     FROM `listings` l
                     JOIN `categories` c ON l.category_id = c.id
                     JOIN `countries` co ON l.country_id = co.id
                     WHERE $where_sql
                     ORDER BY (l.pinned_until IS NOT NULL AND l.pinned_until > NOW()) DESC, $order_sql
                     LIMIT $limit OFFSET $offset";
    $listings_stmt = $pdo->prepare($listings_sql);
    $listings_stmt->execute($sql_params);
    $listings = $listings_stmt->fetchAll();

    // Fetch categories and countries for filter dropdowns
    $all_categories = $pdo->query("SELECT * FROM `categories` ORDER BY `name` ASC")->fetchAll();
    $all_countries = $pdo->query("SELECT * FROM `countries` ORDER BY `name` ASC")->fetchAll();
} catch (PDOException $e) {
    die("Database query error: " . $e->getMessage());
}

// AJAX JSON Responder for listings and pagination HTML fragments
if ($is_ajax) {
    header('Content-Type: application/json');
    
    // Render the grid items
    ob_start();
    if (empty($listings)) {
        ?>
        <div class="col-span-full py-16 text-center bg-surface-white border border-border-subtle rounded-xl shadow-sm">
            <span class="material-symbols-outlined text-4xl text-on-surface-variant mb-2">sentiment_dissatisfied</span>
            <h3 class="text-lg font-bold text-on-surface">No Groups Found</h3>
            <p class="text-on-surface-variant text-sm mt-1">Try adjusting your filters or search query.</p>
        </div>
        <?php
    } else {
        foreach ($listings as $listing) {
            $card_color = $listing['platform'] == 'whatsapp' ? 'whatsapp-green' : 'telegram-blue';
            $card_theme_hex = $listing['platform'] == 'whatsapp' ? '#25D366' : '#229ED9';
            
            $avatar_url = get_avatar_proxy_url($listing['avatar_url']);
            $has_avatar = !empty($avatar_url);
            $words = explode(' ', $listing['title']);
            $initials = mb_strtoupper(mb_substr($words[0], 0, 1));
            if (count($words) > 1) {
                $initials .= mb_strtoupper(mb_substr($words[1], 0, 1));
            }
            $is_pinned = !empty($listing['pinned_until']) && strtotime($listing['pinned_until']) > time();
            ?>
            <!-- Individual Group Card -->
            <div class="<?php echo $is_pinned ? 'bg-amber-500/10 rounded-xl shadow-sm border border-amber-400/50 hover:bg-amber-500/15 hover:border-amber-400 hover:shadow-md transition-all duration-200 p-5 flex flex-col gap-4 group relative' : 'bg-surface-white rounded-xl shadow-sm border border-border-subtle p-5 flex flex-col gap-4 hover:shadow-md hover:border-primary/40 transition-all duration-200 group relative'; ?>">
                <?php if ($is_pinned): ?>
                    <!-- Pinned/Featured Diagonal Triangle Ribbon -->
                    <div class="absolute top-0 right-0 w-12 h-12 overflow-hidden pointer-events-none rounded-tr-xl z-10">
                        <div class="absolute top-0 right-0 bg-amber-500 text-white w-16 h-16 rotate-45 -translate-y-1/2 translate-x-1/2 flex items-end justify-center pb-1.5">
                            <span class="material-symbols-outlined text-[13px] fill-1 -rotate-45" style="font-variation-settings: 'FILL' 1;">star</span>
                        </div>
                    </div>
                <?php endif; ?>
                <div class="flex justify-between items-start">
                    <div class="flex gap-3 items-center">
                        <!-- Avatar block -->
                        <div class="w-14 h-14 rounded-full bg-surface-container-high overflow-hidden shrink-0 flex items-center justify-center border border-border-subtle relative">
                            <?php if ($has_avatar): ?>
                                <img alt="<?php echo htmlspecialchars($listing['title']); ?>" referrerpolicy="no-referrer" class="w-full h-full object-cover transition-opacity duration-500 opacity-0" src="<?php echo htmlspecialchars($avatar_url); ?>" loading="lazy" onload="this.classList.remove('opacity-0'); this.classList.add('opacity-100'); this.nextElementSibling.classList.add('hidden');" onerror="this.style.display='none'; this.nextElementSibling.classList.remove('hidden');"/>
                                <span class="absolute inset-0 flex items-center justify-center text-on-surface-variant font-bold text-base tracking-wider bg-surface-container-high">
                                    <?php echo htmlspecialchars($initials); ?>
                                </span>
                            <?php else: ?>
                                <span class="text-on-surface-variant font-bold text-base tracking-wider"><?php echo htmlspecialchars($initials); ?></span>
                            <?php endif; ?>
                        </div>
                        <!-- Title & Badges -->
                        <div>
                            <h3 class="font-bold text-on-surface <?php echo $is_pinned ? 'group-hover:text-amber-600' : 'group-hover:text-primary'; ?> transition-colors line-clamp-1 text-base md:text-lg" title="<?php echo htmlspecialchars($listing['title']); ?>">
                                <?php echo htmlspecialchars($listing['title']); ?>
                            </h3>
                            <div class="flex items-center gap-2 mt-1">
                                <!-- Platform Badge -->
                                <span class="text-[10px] font-bold px-2 py-0.5 rounded-full flex items-center gap-1 bg-<?php echo $card_color; ?>/10 text-<?php echo $card_color; ?>">
                                    <span class="w-1.5 h-1.5 rounded-full bg-<?php echo $card_color; ?>"></span> 
                                    <?php echo ucfirst($listing['platform']); ?>
                                </span>
                                <!-- Group Type Badge -->
                                <span class="text-[10px] font-bold text-on-surface-variant bg-surface-container-low px-2 py-0.5 rounded-full">
                                    <?php echo $listing['type'] == 'group' ? 'Group' : 'Channel'; ?>
                                </span>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- Description -->
                <p class="text-xs md:text-sm text-on-surface-variant line-clamp-2 leading-relaxed">
                    <?php echo htmlspecialchars($listing['description']); ?>
                </p>
                
                <!-- Tags -->
                <div class="flex flex-wrap gap-1.5 mt-1">
                    <span class="text-[10px] font-bold text-on-surface-variant border border-border-subtle bg-surface-container-low/30 px-2 py-0.5 rounded"><?php echo htmlspecialchars($listing['category_name']); ?></span>
                    <span class="text-[10px] font-bold text-on-surface-variant border border-border-subtle bg-surface-container-low/30 px-2 py-0.5 rounded flex items-center gap-0.5">
                        <span class="material-symbols-outlined text-[12px]">location_on</span> 
                        <?php echo htmlspecialchars($listing['country_name']); ?>
                    </span>
                </div>
                
                <!-- Bottom actions -->
                <div class="flex justify-between items-center mt-auto pt-4 border-t border-border-subtle">
                    <div class="flex gap-4 text-on-surface-variant text-xs font-semibold">
                        <div class="flex items-center gap-1">
                            <span class="material-symbols-outlined text-[16px] text-red-500 fill-1" style="font-variation-settings: 'FILL' 1;">favorite</span> 
                            <?php echo number_format($listing['hearts']); ?>
                        </div>
                        <div class="flex items-center gap-1">
                            <span class="material-symbols-outlined text-[16px]">schedule</span> 
                            <?php 
                                $time_diff = time() - strtotime($listing['created_at']);
                                if ($time_diff < 60) echo 'just now';
                                elseif ($time_diff < 3600) echo round($time_diff/60) . 'm ago';
                                elseif ($time_diff < 86400) echo round($time_diff/3600) . 'h ago';
                                else echo round($time_diff/86400) . 'd ago';
                            ?>
                        </div>
                    </div>
                    <a href="<?php echo SITE_URL; ?>/group/<?php echo $listing['slug']; ?>-<?php echo $listing['id']; ?>" 
                       class="<?php echo $is_pinned ? 'bg-amber-500 hover:bg-amber-600 text-white' : 'bg-' . $card_color . ' hover:opacity-90 text-surface-white'; ?> font-bold text-xs px-4 py-2 rounded-full transition-all shadow-sm flex items-center gap-1">
                        <span>View Group</span>
                        <span class="material-symbols-outlined text-xs">arrow_forward</span>
                    </a>
                </div>
            </div>
            <?php
        }
    }
    $html_content = ob_get_clean();
    
    // Render the pagination
    ob_start();
    if ($total_pages > 1) {
        ?>
        <div class="flex justify-center items-center gap-2 mt-4">
            <?php if ($page > 1): ?>
                <a href="?<?php echo http_build_query(array_merge($_GET, ['page' => $page - 1])); ?>" 
                   class="bg-surface-white border border-border-subtle text-on-surface font-bold text-sm px-4 py-2 rounded-full hover:bg-surface-container-low transition-colors flex items-center gap-1">
                    <span class="material-symbols-outlined text-sm">arrow_back</span> Prev
                </a>
            <?php endif; ?>
            
            <span class="text-xs text-on-surface-variant font-semibold px-2">Page <?php echo $page; ?> of <?php echo $total_pages; ?></span>
            
            <?php if ($page < $total_pages): ?>
                <a href="?<?php echo http_build_query(array_merge($_GET, ['page' => $page + 1])); ?>" 
                   class="bg-surface-white border border-border-subtle text-on-surface font-bold text-sm px-4 py-2 rounded-full hover:bg-surface-container-low transition-colors flex items-center gap-1">
                    Next <span class="material-symbols-outlined text-sm">arrow_forward</span>
                </a>
            <?php endif; ?>
        </div>
        <?php
    }
    $pagination_content = ob_get_clean();
    
    echo json_encode([
        'success' => true,
        'html' => $html_content,
        'pagination' => $pagination_content
    ]);
    exit;
}

// Set dynamic page title
$page_title = "Find WhatsApp & Telegram Invite Links";
require_once 'header.php';
?>

<!-- Main Content Container -->
<main class="flex-grow w-full max-page-width px-4 md:px-8 py-8 flex flex-col gap-8">
    
    <!-- Hero / Action Area -->
    <section class="text-center py-6">
        <?php
        $tagline_title = get_setting('seo_tagline_title');
        if (empty($tagline_title)) {
            $tagline_title = 'WhatsApp & Telegram Link Directory';
        }
        $tagline_desc = get_setting('seo_tagline_desc');
        if (empty($tagline_desc)) {
            $tagline_desc = 'Find, share, and join active group chats and broadcast channels globally.';
        }
        ?>
        <h2 class="text-3xl md:text-4xl font-extrabold tracking-tight text-on-surface mb-2"><?php echo htmlspecialchars($tagline_title); ?></h2>
        <p class="text-on-surface-variant font-medium max-w-xl mx-auto mb-6 text-sm md:text-base"><?php echo htmlspecialchars($tagline_desc); ?></p>
        
        <!-- Focused Single Submit Action above search bar -->
        <div class="flex justify-center items-center">
            <a href="<?php echo SITE_URL; ?>/submit" class="flex items-center gap-2 bg-primary text-on-primary font-bold px-8 py-3.5 rounded-full shadow-md hover:opacity-90 hover:scale-[1.02] transition-all duration-200 select-none text-sm md:text-base">
                <span class="material-symbols-outlined font-bold">add_circle</span> Add Group or Channel Link
            </a>
        </div>
    </section>

    <!-- Search & Filter Controls -->
    <section class="bg-surface-white rounded-xl shadow-sm border border-border-subtle p-5 md:p-6 flex flex-col gap-6">
        <form method="GET" action="./" id="filter-form" class="space-y-5">
            
            <!-- Redesigned Search Input (Responsive stacked layout on mobile) -->
            <div class="flex flex-col sm:flex-row gap-3 items-center w-full">
                <div class="relative w-full">
                    <span class="material-symbols-outlined absolute left-4 top-1/2 -translate-y-1/2 text-on-surface-variant">search</span>
                    <input class="w-full pl-12 pr-4 py-3.5 rounded-xl border border-border-subtle focus:ring-2 focus:ring-primary focus:border-primary bg-surface-container-low text-on-surface outline-none transition-all placeholder:text-on-surface-variant/60 text-sm md:text-base shadow-sm" 
                           placeholder="Search group names, tags, countries, categories..." type="text" name="q" value="<?php echo htmlspecialchars($search_q); ?>"/>
                </div>
                <button class="bg-primary text-on-primary font-bold px-8 py-3.5 rounded-xl hover:opacity-95 transition-all shrink-0 w-full sm:w-auto flex items-center justify-center gap-2 text-sm md:text-base shadow-sm hover:scale-[1.01]" type="submit">
                    <span class="material-symbols-outlined text-lg">search</span>
                    <span>Search</span>
                </button>
            </div>

            <!-- Platform Switcher Buttons -->
            <div class="flex gap-2 overflow-x-auto pb-1.5 scrollbar-hide border-b border-border-subtle">
                <input type="hidden" name="platform" id="platform-input" value="<?php echo htmlspecialchars($platform); ?>">
                
                <button type="button" onclick="setPlatform('')" 
                        class="px-5 py-2 rounded-full font-bold text-xs md:text-sm whitespace-nowrap transition-all border <?php echo empty($platform) ? 'bg-primary text-on-primary border-primary' : 'bg-surface-container-low text-on-surface border-border-subtle hover:border-primary'; ?>">
                    All Platforms
                </button>
                <button type="button" onclick="setPlatform('whatsapp')" 
                        class="px-5 py-2 rounded-full font-bold text-xs md:text-sm whitespace-nowrap transition-all border flex items-center gap-2 <?php echo $platform === 'whatsapp' ? 'bg-whatsapp-green text-surface-white border-whatsapp-green' : 'bg-surface-container-low text-on-surface border-border-subtle hover:border-whatsapp-green'; ?>">
                    <span class="w-2.5 h-2.5 rounded-full bg-whatsapp-green <?php echo $platform === 'whatsapp' ? 'bg-surface-white' : ''; ?>"></span> WhatsApp
                </button>
                <button type="button" onclick="setPlatform('telegram')" 
                        class="px-5 py-2 rounded-full font-bold text-xs md:text-sm whitespace-nowrap transition-all border flex items-center gap-2 <?php echo $platform === 'telegram' ? 'bg-telegram-blue text-surface-white border-telegram-blue' : 'bg-surface-container-low text-on-surface border-border-subtle hover:border-telegram-blue'; ?>">
                    <span class="w-2.5 h-2.5 rounded-full bg-telegram-blue <?php echo $platform === 'telegram' ? 'bg-surface-white' : ''; ?>"></span> Telegram
                </button>
            </div>

            <!-- Inline Filters (Redesigned Grid Layout with 4 Select Boxes) -->
            <div id="homepage-filters" class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-3.5 w-full pt-1">
                
                <!-- Category Select Box -->
                <div class="relative w-full">
                    <select name="category" onchange="this.form.submit()"
                        class="searchable-select w-full h-11 appearance-none bg-surface-container-lowest border border-border-subtle text-on-surface text-sm rounded-lg px-4 pr-10 outline-none focus:border-primary focus:ring-1 focus:ring-primary cursor-pointer">
                        <option value="all">All Categories</option>
                        <?php foreach ($all_categories as $cat): ?>
                            <option value="<?php echo $cat['id']; ?>" <?php echo $category == $cat['id'] ? 'selected' : ''; ?>>
                                <?php echo htmlspecialchars($cat['name']); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                    <span class="material-symbols-outlined absolute right-3 top-1/2 -translate-y-1/2 text-on-surface-variant pointer-events-none text-lg">
                        expand_more
                    </span>
                </div>

                <!-- Country Select Box -->
                <div class="relative w-full">
                    <select name="country" onchange="this.form.submit()"
                        class="searchable-select w-full h-11 appearance-none bg-surface-container-lowest border border-border-subtle text-on-surface text-sm rounded-lg px-4 pr-10 outline-none focus:border-primary focus:ring-1 focus:ring-primary cursor-pointer">
                        <option value="all">All Countries</option>
                        <?php foreach ($all_countries as $cnt): ?>
                            <option value="<?php echo $cnt['id']; ?>" <?php echo $country == $cnt['id'] ? 'selected' : ''; ?>>
                                <?php echo htmlspecialchars($cnt['name']); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                    <span class="material-symbols-outlined absolute right-3 top-1/2 -translate-y-1/2 text-on-surface-variant pointer-events-none text-lg">
                        expand_more
                    </span>
                </div>

                <!-- Type Select Box -->
                <div class="relative w-full">
                    <select name="type" onchange="this.form.submit()"
                        class="w-full h-11 appearance-none bg-surface-container-lowest border border-border-subtle text-on-surface text-sm rounded-lg px-4 pr-10 outline-none focus:border-primary focus:ring-1 focus:ring-primary cursor-pointer">
                        <option value="all">Any Type</option>
                        <option value="group" <?php echo $type === 'group' ? 'selected' : ''; ?>>
                            Group Chat
                        </option>
                        <option value="channel" <?php echo $type === 'channel' ? 'selected' : ''; ?>>
                            Channel (Broadcast)
                        </option>
                    </select>
                    <span class="material-symbols-outlined absolute right-3 top-1/2 -translate-y-1/2 text-on-surface-variant pointer-events-none text-lg">
                        expand_more
                    </span>
                </div>

                <!-- Sort Select Box -->
                <div class="relative w-full">
                    <select name="sort" onchange="this.form.submit()"
                        class="w-full h-11 appearance-none bg-surface-container-lowest border border-border-subtle text-on-surface text-sm rounded-lg px-4 pr-10 outline-none focus:border-primary focus:ring-1 focus:ring-primary cursor-pointer">
                        <option value="newest" <?php echo $sort === 'newest' ? 'selected' : ''; ?>>
                            Sort: Newest Added
                        </option>
                        <option value="popular" <?php echo $sort === 'popular' ? 'selected' : ''; ?>>
                            Sort: Most Liked
                        </option>
                    </select>
                    <span class="material-symbols-outlined absolute right-3 top-1/2 -translate-y-1/2 text-on-surface-variant pointer-events-none text-lg">
                        expand_more
                    </span>
                </div>

            </div>
        </form>
    </section>

    <!-- Listings Container -->
    <div class="w-full flex flex-col gap-6">
        <?php 
        $ad_home_enabled = get_setting('ad_home_enabled') === '1';
        if ($ad_home_enabled):
            $ad_home_728_type = get_setting('ad_home_728_type');
            $ad_home_728_code = get_setting('ad_home_728_code');
            $ad_home_728_image = get_setting('ad_home_728_image');
            $ad_home_728_link = get_setting('ad_home_728_link');

            $ad_home_250_type = get_setting('ad_home_250_type');
            $ad_home_250_code = get_setting('ad_home_250_code');
            $ad_home_250_image = get_setting('ad_home_250_image');
            $ad_home_250_link = get_setting('ad_home_250_link');
        ?>
            <!-- Homepage Responsive Ad (Leaderboard 728x90 on md+, Square 250x250 on mobile) -->
            <div class="bg-surface-white border border-border-subtle rounded-xl p-4 shadow-sm flex flex-col items-center mx-auto w-fit max-w-full">
                <span class="text-[9px] uppercase tracking-wider text-gray-400 font-bold mb-2 select-none">Advertisement</span>
                
                <!-- Desktop Ad (728x90) -->
                <div class="hidden md:flex w-[728px] h-[90px] overflow-hidden items-center justify-center relative max-w-full">
                    <?php if ($ad_home_728_type === 'image' && !empty($ad_home_728_image)): ?>
                        <a href="<?php echo htmlspecialchars($ad_home_728_link); ?>" target="_blank" class="block w-full h-full">
                            <img src="<?php echo htmlspecialchars($ad_home_728_image); ?>" alt="Advertisement" class="w-full h-full rounded-lg object-contain mx-auto" />
                        </a>
                    <?php elseif ($ad_home_728_type === 'code' && !empty($ad_home_728_code)): ?>
                        <div class="w-full h-full flex justify-center items-center">
                            <?php echo $ad_home_728_code; ?>
                        </div>
                    <?php else: ?>
                        <!-- Placeholder -->
                        <div class="border border-dashed border-gray-300 rounded-lg flex flex-col items-center justify-center bg-gray-50 text-gray-400 font-semibold select-none w-full h-full">
                            <span class="material-symbols-outlined text-lg mb-1">ads_click</span>
                            <div class="flex flex-col items-center">
                                <span class="text-[10px] uppercase tracking-wider">Leaderboard</span>
                                <span class="text-[9px] opacity-80 mt-0.5">728 x 90</span>
                            </div>
                        </div>
                    <?php endif; ?>
                </div>

                <!-- Mobile Ad (250x250) -->
                <div class="flex md:hidden w-[250px] h-[250px] overflow-hidden items-center justify-center relative max-w-full">
                    <?php if ($ad_home_250_type === 'image' && !empty($ad_home_250_image)): ?>
                        <a href="<?php echo htmlspecialchars($ad_home_250_link); ?>" target="_blank" class="block w-full h-full">
                            <img src="<?php echo htmlspecialchars($ad_home_250_image); ?>" alt="Advertisement" class="w-full h-full rounded-lg object-contain mx-auto" />
                        </a>
                    <?php elseif ($ad_home_250_type === 'code' && !empty($ad_home_250_code)): ?>
                        <div class="w-full h-full flex justify-center items-center">
                            <?php echo $ad_home_250_code; ?>
                        </div>
                    <?php else: ?>
                        <!-- Placeholder -->
                        <div class="border border-dashed border-gray-300 rounded-lg flex flex-col items-center justify-center bg-gray-50 text-gray-400 font-semibold select-none w-full h-full">
                            <span class="material-symbols-outlined text-lg mb-1">ads_click</span>
                            <div class="flex flex-col items-center">
                                <span class="text-[10px] uppercase tracking-wider">Square</span>
                                <span class="text-[9px] opacity-80 mt-0.5">250 x 250</span>
                            </div>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        <?php endif; ?>

        <!-- Grid of Cards -->
        <section id="listings-grid" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                <?php if (empty($listings)): ?>
                    <div class="col-span-full py-16 text-center bg-surface-white border border-border-subtle rounded-xl shadow-sm">
                        <span class="material-symbols-outlined text-4xl text-on-surface-variant mb-2">sentiment_dissatisfied</span>
                        <h3 class="text-lg font-bold text-on-surface">No Groups Found</h3>
                        <p class="text-on-surface-variant text-sm mt-1">Try adjusting your filters or search query.</p>
                    </div>
                <?php else: ?>
                    <?php foreach ($listings as $listing): 
                        $card_color = $listing['platform'] == 'whatsapp' ? 'whatsapp-green' : 'telegram-blue';
                        $card_theme_hex = $listing['platform'] == 'whatsapp' ? '#25D366' : '#229ED9';
                        
                        // Get dynamic avatar or generate initial fallback
                        $avatar_url = get_avatar_proxy_url($listing['avatar_url']);
                        $has_avatar = !empty($avatar_url);
                        $words = explode(' ', $listing['title']);
                        $initials = mb_strtoupper(mb_substr($words[0], 0, 1));
                        if (count($words) > 1) {
                            $initials .= mb_strtoupper(mb_substr($words[1], 0, 1));
                        }
                    $is_pinned = !empty($listing['pinned_until']) && strtotime($listing['pinned_until']) > time();
                    ?>
                        <!-- Individual Group Card -->
                        <div class="<?php echo $is_pinned ? 'bg-amber-500/10 rounded-xl shadow-sm border border-amber-400/50 hover:bg-amber-500/15 hover:border-amber-400 hover:shadow-md transition-all duration-200 p-5 flex flex-col gap-4 group relative' : 'bg-surface-white rounded-xl shadow-sm border border-border-subtle p-5 flex flex-col gap-4 hover:shadow-md hover:border-primary/40 transition-all duration-200 group relative'; ?>">
                            <?php if ($is_pinned): ?>
                                <!-- Pinned/Featured Diagonal Triangle Ribbon -->
                                <div class="absolute top-0 right-0 w-12 h-12 overflow-hidden pointer-events-none rounded-tr-xl z-10">
                                    <div class="absolute top-0 right-0 bg-amber-500 text-white w-16 h-16 rotate-45 -translate-y-1/2 translate-x-1/2 flex items-end justify-center pb-1.5">
                                        <span class="material-symbols-outlined text-[13px] fill-1 -rotate-45" style="font-variation-settings: 'FILL' 1;">star</span>
                                    </div>
                                </div>
                            <?php endif; ?>
                            <div class="flex justify-between items-start">
                                <div class="flex gap-3 items-center">
                                    <!-- Avatar block -->
                                    <div class="w-14 h-14 rounded-full bg-surface-container-high overflow-hidden shrink-0 flex items-center justify-center border border-border-subtle relative">
                                        <?php if ($has_avatar): ?>
                                            <img alt="<?php echo htmlspecialchars($listing['title']); ?>" referrerpolicy="no-referrer" class="w-full h-full object-cover transition-opacity duration-500 opacity-0" src="<?php echo htmlspecialchars($avatar_url); ?>" loading="lazy" onload="this.classList.remove('opacity-0'); this.classList.add('opacity-100'); this.nextElementSibling.classList.add('hidden');" onerror="this.style.display='none'; this.nextElementSibling.classList.remove('hidden');"/>
                                            <span class="absolute inset-0 flex items-center justify-center text-on-surface-variant font-bold text-base tracking-wider bg-surface-container-high">
                                                <?php echo htmlspecialchars($initials); ?>
                                            </span>
                                        <?php else: ?>
                                            <span class="text-on-surface-variant font-bold text-base tracking-wider"><?php echo htmlspecialchars($initials); ?></span>
                                        <?php endif; ?>
                                    </div>
                                    <!-- Title & Badges -->
                                    <div>
                                        <h3 class="font-bold text-on-surface <?php echo $is_pinned ? 'group-hover:text-amber-600' : 'group-hover:text-primary'; ?> transition-colors line-clamp-1 text-base md:text-lg" title="<?php echo htmlspecialchars($listing['title']); ?>">
                                            <?php echo htmlspecialchars($listing['title']); ?>
                                        </h3>
                                        <div class="flex items-center gap-2 mt-1">
                                            <!-- Platform Badge -->
                                            <span class="text-[10px] font-bold px-2 py-0.5 rounded-full flex items-center gap-1 bg-<?php echo $card_color; ?>/10 text-<?php echo $card_color; ?>">
                                                <span class="w-1.5 h-1.5 rounded-full bg-<?php echo $card_color; ?>"></span> 
                                                <?php echo ucfirst($listing['platform']); ?>
                                            </span>
                                            <!-- Group Type Badge -->
                                            <span class="text-[10px] font-bold text-on-surface-variant bg-surface-container-low px-2 py-0.5 rounded-full">
                                                <?php echo $listing['type'] == 'group' ? 'Group' : 'Channel'; ?>
                                            </span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Description -->
                            <p class="text-xs md:text-sm text-on-surface-variant line-clamp-2 leading-relaxed">
                                <?php echo htmlspecialchars($listing['description']); ?>
                            </p>
                            
                            <!-- Tags -->
                            <div class="flex flex-wrap gap-1.5 mt-1">
                                <span class="text-[10px] font-bold text-on-surface-variant border border-border-subtle bg-surface-container-low/30 px-2 py-0.5 rounded"><?php echo htmlspecialchars($listing['category_name']); ?></span>
                                <span class="text-[10px] font-bold text-on-surface-variant border border-border-subtle bg-surface-container-low/30 px-2 py-0.5 rounded flex items-center gap-0.5">
                                    <span class="material-symbols-outlined text-[12px]">location_on</span> 
                                    <?php echo htmlspecialchars($listing['country_name']); ?>
                                </span>
                            </div>
                            
                            <!-- Bottom actions -->
                            <div class="flex justify-between items-center mt-auto pt-4 border-t border-border-subtle">
                                <div class="flex gap-4 text-on-surface-variant text-xs font-semibold">
                                    <div class="flex items-center gap-1">
                                        <span class="material-symbols-outlined text-[16px] text-red-500 fill-1" style="font-variation-settings: 'FILL' 1;">favorite</span> 
                                        <?php echo number_format($listing['hearts']); ?>
                                    </div>
                                    <div class="flex items-center gap-1">
                                        <span class="material-symbols-outlined text-[16px]">schedule</span> 
                                        <?php 
                                            $time_diff = time() - strtotime($listing['created_at']);
                                            if ($time_diff < 60) echo 'just now';
                                            elseif ($time_diff < 3600) echo round($time_diff/60) . 'm ago';
                                            elseif ($time_diff < 86400) echo round($time_diff/3600) . 'h ago';
                                            else echo round($time_diff/86400) . 'd ago';
                                        ?>
                                    </div>
                                </div>
                                <a href="<?php echo SITE_URL; ?>/group/<?php echo $listing['slug']; ?>-<?php echo $listing['id']; ?>" 
                                   class="<?php echo $is_pinned ? 'bg-amber-500 hover:bg-amber-600 text-white' : 'bg-' . $card_color . ' hover:opacity-90 text-surface-white'; ?> font-bold text-xs px-4 py-2 rounded-full transition-all shadow-sm flex items-center gap-1">
                                    <span>View Group</span>
                                    <span class="material-symbols-outlined text-xs">arrow_forward</span>
                                </a>
                            </div>
                        </div>
                    <?php endforeach; ?>
                <?php endif; ?>
            </section>

            <!-- Pagination -->
            <div id="pagination-container">
                <?php if ($total_pages > 1): ?>
                    <div class="flex justify-center items-center gap-2 mt-4">
                        <?php if ($page > 1): ?>
                            <a href="?<?php echo http_build_query(array_merge($_GET, ['page' => $page - 1])); ?>" 
                               class="bg-surface-white border border-border-subtle text-on-surface font-bold text-sm px-4 py-2 rounded-full hover:bg-surface-container-low transition-colors flex items-center gap-1">
                                <span class="material-symbols-outlined text-sm">arrow_back</span> Prev
                            </a>
                        <?php endif; ?>
                        
                        <span class="text-xs text-on-surface-variant font-semibold px-2">Page <?php echo $page; ?> of <?php echo $total_pages; ?></span>
                        
                        <?php if ($page < $total_pages): ?>
                            <a href="?<?php echo http_build_query(array_merge($_GET, ['page' => $page + 1])); ?>" 
                               class="bg-surface-white border border-border-subtle text-on-surface font-bold text-sm px-4 py-2 rounded-full hover:bg-surface-container-low transition-colors flex items-center gap-1">
                                Next <span class="material-symbols-outlined text-sm">arrow_forward</span>
                            </a>
                        <?php endif; ?>
                    </div>
                <?php endif; ?>
            </div>
        </div>


</main>

<script>
document.addEventListener('DOMContentLoaded', () => {
    const filterForm = document.getElementById('filter-form');
    const listingsGrid = document.getElementById('listings-grid');
    const paginationContainer = document.getElementById('pagination-container');
    const platformInput = document.getElementById('platform-input');
    
    // React-like pulse skeleton card HTML
    const skeletonHTML = `
        <div class="bg-surface-white rounded-xl border border-border-subtle p-5 flex flex-col gap-4 animate-pulse">
            <div class="flex gap-3 items-center">
                <div class="w-14 h-14 rounded-full bg-gray-200 shrink-0"></div>
                <div class="flex-grow space-y-2">
                    <div class="h-4 bg-gray-200 rounded w-2/3"></div>
                    <div class="flex gap-2">
                        <div class="h-3 bg-gray-200 rounded w-16"></div>
                        <div class="h-3 bg-gray-200 rounded w-12"></div>
                    </div>
                </div>
            </div>
            <div class="space-y-2">
                <div class="h-3.5 bg-gray-200 rounded w-full"></div>
                <div class="h-3.5 bg-gray-200 rounded w-5/6"></div>
            </div>
            <div class="flex gap-1.5">
                <div class="h-4 bg-gray-200 rounded w-20"></div>
                <div class="h-4 bg-gray-200 rounded w-24"></div>
            </div>
            <div class="flex justify-between items-center mt-auto pt-4 border-t border-gray-100">
                <div class="flex gap-4">
                    <div class="h-3 bg-gray-200 rounded w-12"></div>
                    <div class="h-3 bg-gray-200 rounded w-16"></div>
                </div>
                <div class="h-7 bg-gray-200 rounded-full w-24"></div>
            </div>
        </div>
    `;
    
    const showSkeletons = () => {
        listingsGrid.innerHTML = Array(6).fill(skeletonHTML).join('');
        paginationContainer.innerHTML = '';
    };
    
    const loadListings = (pageVal = 1) => {
        showSkeletons();
        
        // Build query string
        const formData = new FormData(filterForm);
        formData.set('page', pageVal);
        formData.set('ajax', '1');
        
        const params = new URLSearchParams(formData);
        const fetchUrl = './?' + params.toString();
        
        fetch(fetchUrl)
            .then(res => res.json())
            .then(data => {
                if (data.success) {
                    listingsGrid.innerHTML = data.html;
                    paginationContainer.innerHTML = data.pagination;
                    
                    // Update URL bar dynamically
                    const urlParams = new URLSearchParams(params);
                    urlParams.delete('ajax');
                    const newUrl = window.location.pathname + '?' + urlParams.toString();
                    window.history.pushState({ path: newUrl }, '', newUrl);
                } else {
                    listingsGrid.innerHTML = '<div class="col-span-full text-center text-red-500 py-8">An error occurred loading listings.</div>';
                }
            })
            .catch(err => {
                listingsGrid.innerHTML = '<div class="col-span-full text-center text-red-500 py-8">Connection error loading listings.</div>';
            });
    };
    
    // Intercept form submit
    if (filterForm) {
        filterForm.addEventListener('submit', (e) => {
            e.preventDefault();
            loadListings(1);
        });
        
        // Intercept changes on dropdown filters
        const selects = filterForm.querySelectorAll('select');
        selects.forEach(select => {
            select.addEventListener('change', () => {
                loadListings(1);
            });
        });
    }
    
    // Intercept pagination clicks dynamically
    if (paginationContainer) {
        paginationContainer.addEventListener('click', (e) => {
            const link = e.target.closest('a');
            if (link) {
                e.preventDefault();
                const url = new URL(link.href);
                const page = url.searchParams.get('page') || 1;
                loadListings(page);
                listingsGrid.scrollIntoView({ behavior: 'smooth', block: 'start' });
            }
        });
    }

    // Expose platform switcher function globally
    window.setPlatform = (platformVal) => {
        platformInput.value = platformVal;
        
        // Update switcher buttons UI styles
        const buttons = filterForm.querySelectorAll('button[type="button"]');
        buttons.forEach(btn => {
            const isAll = btn.textContent.includes('All Platforms');
            const isWA = btn.textContent.includes('WhatsApp');
            const isTG = btn.textContent.includes('Telegram');
            
            // Revert active states
            btn.className = btn.className.replace(/bg-primary|bg-whatsapp-green|bg-telegram-blue|text-on-primary|text-surface-white/g, 'bg-surface-container-low text-on-surface');
            
            if (platformVal === '' && isAll) {
                btn.className = btn.className.replace(/bg-surface-container-low text-on-surface/g, 'bg-primary text-on-primary border-primary');
            } else if (platformVal === 'whatsapp' && isWA) {
                btn.className = btn.className.replace(/bg-surface-container-low text-on-surface/g, 'bg-whatsapp-green text-surface-white border-whatsapp-green');
            } else if (platformVal === 'telegram' && isTG) {
                btn.className = btn.className.replace(/bg-surface-container-low text-on-surface/g, 'bg-telegram-blue text-surface-white border-telegram-blue');
            }
        });
        
        loadListings(1);
    };
});
</script>

<?php 
require_once 'footer.php'; 

$cache_content = ob_get_clean();
set_page_cache($cache_key, $cache_content);
echo $cache_content;
?>
