<?php
$pageTitle = 'Play Free Online Games';
$pageDescription = $settings['site_description'] ?? 'Play the best free online games on our gaming portal. New games added daily!';
include __DIR__ . '/layout/header.php';
?>

<div class="container mx-auto px-4 py-6">
    <?php if (($settings['homepage_display_type'] ?? 'hero') === 'hero'): ?>
    <!-- Hero Section -->
    <section class="hero-section mb-12">
        <div class="flex flex-col md:flex-row items-center">
            <div class="md:w-1/2 mb-8 md:mb-0">
                <h1 class="text-4xl md:text-5xl font-bold mb-4"><?= htmlspecialchars($heroTitle) ?></h1>
                <p class="text-xl mb-6 text-gray-300"><?= htmlspecialchars($heroDescription) ?></p>
                <div class="flex flex-wrap gap-4">
                    <a href="#featured" class="btn-primary">
                        <i class="fas fa-star mr-2"></i>Featured Games
                    </a>
                    <a href="/categories" class="btn-secondary">
                        <i class="fas fa-th-large mr-2"></i>Browse Categories
                    </a>
                </div>
            </div>
            <div class="md:w-1/2 flex justify-center">
                <img src="<?= htmlspecialchars($heroImagePath) ?>" alt="Hero Image" class="w-full max-w-md" loading="lazy" onerror="this.src='https://placehold.co/600x400/1A2234/2C7BE5?text=Gaming+Character&font=Poppins'">
            </div>
        </div>
    </section>
    <?php else: ?>
    <!-- Featured Games Slider -->
    <section class="slider-section mb-12">
        <div class="relative overflow-hidden rounded-lg md:rounded-2xl md:bg-gradient-to-r md:from-dark md:to-card-bg">
            <div class="slider-container relative h-96 md:h-[500px]">
                <div class="slider-wrapper flex transition-transform duration-500 ease-in-out" id="gameSlider">
                    <?php 
                    $sliderGames = array_slice($featuredGames, 0, 5);
                    foreach ($sliderGames as $index => $game): 
                    ?>
                    <div class="slider-slide w-full flex-shrink-0 relative">
                        <div class="absolute inset-0 bg-gradient-to-r from-black/70 to-transparent z-10"></div>
                        <img src="<?= htmlspecialchars($game['thumbnail']) ?>" alt="<?= htmlspecialchars($game['title']) ?>" class="w-full h-full object-cover rounded-lg md:rounded-none">
                        <div class="absolute inset-0 z-20 flex items-center">
                            <div class="container mx-auto px-4">
                                <div class="max-w-2xl">
                                    <div class="mb-4">
                                        <span class="inline-block px-3 py-1 bg-primary text-white text-sm font-medium rounded-full">
                                            <i class="fas fa-tag mr-1"></i>
                                            <?= htmlspecialchars($game['category_name']) ?>
                                        </span>
                                    </div>
                                    <a href="/game/<?= $game['slug'] ?>" class="block">
                                        <h1 class="text-3xl md:text-5xl font-bold mb-4 text-white hover:text-primary transition-colors duration-300"><?= htmlspecialchars($game['title']) ?></h1>
                                    </a>
                                    <p class="text-lg md:text-xl mb-6 text-gray-200 line-clamp-2"><?= htmlspecialchars(substr($game['description'], 0, 120)) ?><?= strlen($game['description']) > 120 ? '...' : '' ?></p>
                                    <div class="hidden md:flex flex-wrap gap-4">
                                        <a href="/game/<?= $game['slug'] ?>" class="btn-primary">
                                            <i class="fas fa-play mr-2"></i>Play Now
                                        </a>
                                        <a href="/categories/<?= $game['category_slug'] ?>" class="btn-secondary">
                                            <i class="fas fa-th-large mr-2"></i>More <?= htmlspecialchars($game['category_name']) ?> Games
                                        </a>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <?php endforeach; ?>
                </div>
                
                <!-- Navigation Arrows -->
                <button class="slider-nav slider-prev absolute left-4 top-1/2 transform -translate-y-1/2 z-30 bg-black/50 hover:bg-black/70 text-white w-12 h-12 rounded-full transition-all duration-300 flex items-center justify-center">
                    <i class="fas fa-chevron-left"></i>
                </button>
                <button class="slider-nav slider-next absolute right-4 top-1/2 transform -translate-y-1/2 z-30 bg-black/50 hover:bg-black/70 text-white w-12 h-12 rounded-full transition-all duration-300 flex items-center justify-center">
                    <i class="fas fa-chevron-right"></i>
                </button>
                
                <!-- Dots Indicator -->
                <div class="absolute bottom-6 left-1/2 transform -translate-x-1/2 z-30 flex space-x-2">
                    <?php for ($i = 0; $i < count($sliderGames); $i++): ?>
                    <button class="slider-dot w-3 h-3 rounded-full bg-white/50 hover:bg-white/80 transition-all duration-300 <?= $i === 0 ? 'bg-white' : '' ?>" data-slide="<?= $i ?>"></button>
                    <?php endfor; ?>
                </div>
            </div>
        </div>
    </section>
    <?php endif; ?>

    <!-- Featured Games -->
    <section class="mb-12">
        <div class="flex items-center justify-between mb-6">
            <h2 class="text-2xl font-bold">Featured Games</h2>
            <div class="flex">
                <a href="/categories" class="px-3 py-1 rounded-full bg-primary text-white text-sm font-medium">View All</a>
            </div>
        </div>

        <div class="game-grid">
            <?php foreach ($featuredGames as $game): ?>
            <a href="/game/<?= $game['slug'] ?>" class="game-card group">
                <div class="relative aspect-square overflow-hidden rounded-xl">
                    <img src="<?= htmlspecialchars($game['thumbnail']) ?>" alt="<?= htmlspecialchars($game['title']) ?>"
                         class="w-full h-full object-cover transition-transform duration-500 group-hover:scale-110" loading="lazy">
                    <div class="absolute top-0 left-0 m-3 z-1">
                        <span class="category-badge">
                            <i class="fas fa-tag mr-1"></i>
                            <?= htmlspecialchars($game['category_name']) ?>
                        </span>
                    </div>
                    <div class="game-card-overlay">
                        <h3 class="game-card-title"><?= htmlspecialchars($game['title']) ?></h3>
                    </div>
                    <div class="absolute inset-0 bg-gradient-to-t from-black/80 to-transparent opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center">
                        <button class="w-10 h-10 bg-primary rounded-full flex items-center justify-center">
                            <i class="fas fa-play text-white"></i>
                        </button>
                    </div>
                </div>
            </a>
            <?php endforeach; ?>
        </div>
    </section>

    <!-- Between Content Ad - After Featured Games -->
    <?php if (isset($settings['enable_ads']) && $settings['enable_ads'] == '1' && isset($settings['between_content_ad']) && !empty($settings['between_content_ad'])): ?>
    <div class="ad-container between-content-ad mb-12">
        <?= $settings['between_content_ad'] ?>
    </div>
    <?php endif; ?>

    <?php foreach ($popularCategories as $category): ?>
    <!-- Games by Category: <?= htmlspecialchars($category['name']) ?> -->
    <section class="mb-12">
        <div class="flex justify-between items-center mb-6">
            <h2 class="text-2xl font-bold"><?= htmlspecialchars($category['name']) ?> Games</h2>
            <a href="/category/<?= $category['slug'] ?>" class="text-primary hover:underline flex items-center">
                View All <i class="fas fa-arrow-right ml-2"></i>
            </a>
        </div>

        <div class="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-6 xl:grid-cols-6 gap-4 md:gap-6">
            <?php
            // Get games for this category directly from database
            $categoryGames = $gameModel->getGamesByCategory($category['slug'], 12);

            // If no games in this category, use some from featured games
            if (empty($categoryGames)) {
                $categoryGames = array_slice($featuredGames, 0, 12);
            }

            foreach ($categoryGames as $game):
            ?>
            <a href="/game/<?= $game['slug'] ?>" class="game-card group">
                <div class="relative aspect-square overflow-hidden rounded-xl">
                    <img src="<?= htmlspecialchars($game['thumbnail']) ?>" alt="<?= htmlspecialchars($game['title']) ?>"
                         class="w-full h-full object-cover transition-transform duration-500 group-hover:scale-110" loading="lazy">
                    <div class="absolute top-0 left-0 m-3 z-1">
                        <span class="category-badge">
                            <i class="fas fa-tag mr-1"></i>
                            <?= htmlspecialchars($category['name']) ?>
                        </span>
                    </div>
                    <div class="game-card-overlay">
                        <h3 class="game-card-title"><?= htmlspecialchars($game['title']) ?></h3>
                    </div>
                    <div class="absolute inset-0 bg-gradient-to-t from-black/80 to-transparent opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center">
                        <button class="w-10 h-10 bg-primary rounded-full flex items-center justify-center">
                            <i class="fas fa-play text-white"></i>
                        </button>
                    </div>
                </div>
            </a>
            <?php endforeach; ?>
        </div>
    </section>
    <?php endforeach; ?>

    <!-- Between Content Ad - After Categories -->
    <?php if (isset($settings['enable_ads']) && $settings['enable_ads'] == '1' && isset($settings['between_content_ad']) && !empty($settings['between_content_ad'])): ?>
    <div class="ad-container between-content-ad mb-12">
        <?= $settings['between_content_ad'] ?>
    </div>
    <?php endif; ?>

    <!-- All Games -->
    <section class="mb-12">
        <div class="flex justify-between items-center mb-6">
            <h2 class="text-2xl font-bold">Recently Added</h2>
            <a href="/categories" class="px-3 py-1 rounded-full bg-primary text-white text-sm font-medium">View All</a>
        </div>

        <div class="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-6 gap-6">
            <?php foreach (array_slice($recentGames, 0, 12) as $game): ?>
            <a href="/game/<?= $game['slug'] ?>" class="game-card group">
                <div class="relative aspect-square overflow-hidden rounded-xl">
                    <img src="<?= htmlspecialchars($game['thumbnail']) ?>" alt="<?= htmlspecialchars($game['title']) ?>"
                         class="w-full h-full object-cover transition-transform duration-500 group-hover:scale-110" loading="lazy">
                    <div class="absolute top-0 left-0 m-3 z-1">
                        <span class="category-badge">
                            <i class="fas fa-tag mr-1"></i>
                            <?= htmlspecialchars($game['category_name']) ?>
                        </span>
                    </div>
                    <div class="game-card-overlay">
                        <h3 class="game-card-title"><?= htmlspecialchars($game['title']) ?></h3>
                    </div>
                    <div class="absolute inset-0 bg-gradient-to-t from-black/80 to-transparent opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center">
                        <button class="w-10 h-10 bg-primary rounded-full flex items-center justify-center">
                            <i class="fas fa-play text-white"></i>
                        </button>
                    </div>
                </div>
            </a>
            <?php endforeach; ?>
        </div>
    </section>

    <!-- Leaderboard Section -->
    <?php if (isset($showLeaderboard) && $showLeaderboard === '1' && !empty($leaderboard)): ?>
    <section class="mb-12">
        <div class="flex justify-between items-center mb-6">
            <h2 class="text-2xl font-bold">Top Players</h2>
            <?php if (isset($_SESSION['user_id'])): ?>
            <a href="/profile" class="inline-flex items-center px-4 py-2 rounded-full bg-card-bg text-white text-sm font-medium border border-gray-800/50 hover:bg-card-hover hover:border-primary/50 transition-all">
                My Profile
                <i class="fas fa-user ml-2"></i>
            </a>
            <?php else: ?>
            <a href="/login" class="inline-flex items-center px-4 py-2 rounded-full bg-card-bg text-white text-sm font-medium border border-gray-800/50 hover:bg-card-hover hover:border-primary/50 transition-all">
                Join Now
                <i class="fas fa-sign-in-alt ml-2"></i>
            </a>
            <?php endif; ?>
        </div>

        <div class="bg-card-bg rounded-xl overflow-hidden border border-gray-800/50">
            <div class="p-6">
                <div class="grid grid-cols-1 gap-4">
                    <?php foreach ($leaderboard as $index => $player): ?>
                    <div class="flex items-center p-3 <?= $index === 0 ? 'bg-primary/20' : 'bg-darker' ?> rounded-lg">
                        <div class="flex-shrink-0 mr-4 text-center w-8">
                            <span class="text-lg font-bold <?= $index < 3 ? 'text-primary' : 'text-gray-400' ?>">#<?= $index + 1 ?></span>
                        </div>
                        <div class="flex-shrink-0 mr-4">
                            <div class="w-10 h-10 rounded-full bg-primary flex items-center justify-center text-white text-lg font-bold">
                                <?= strtoupper(substr($player['username'], 0, 1)) ?>
                            </div>
                        </div>
                        <div class="flex-grow">
                            <h3 class="font-medium"><?= htmlspecialchars($player['name'] ?: $player['username']) ?></h3>
                            <p class="text-sm text-gray-400">@<?= htmlspecialchars($player['username']) ?></p>
                        </div>
                        <div class="flex-shrink-0 text-right">
                            <span class="text-lg font-bold"><?= $player['play_count'] ?></span>
                            <p class="text-xs text-gray-400">games played</p>
                        </div>
                    </div>
                    <?php endforeach; ?>
                </div>

                <?php if (!isset($_SESSION['user_id'])): ?>
                <div class="mt-6 text-center">
                    <p class="text-gray-300 mb-3">Create an account to track your games and compete on the leaderboard!</p>
                    <div class="flex justify-center gap-4">
                        <a href="/register" class="btn-primary">
                            <i class="fas fa-user-plus mr-2"></i>Register
                        </a>
                        <a href="/login" class="btn-secondary">
                            <i class="fas fa-sign-in-alt mr-2"></i>Login
                        </a>
                    </div>
                </div>
                <?php endif; ?>
            </div>
        </div>
    </section>
    <?php endif; ?>

    <!-- Blog Posts Section -->
    <?php if (isset($settings['show_blog_section']) && $settings['show_blog_section'] == '1'): ?>
    <section class="mb-12">
        <div class="flex justify-between items-center mb-6">
            <h2 class="text-2xl font-bold"><?= htmlspecialchars($settings['blog_section_title'] ?? 'Latest Blog Posts') ?></h2>
            <a href="/blog" class="inline-flex items-center px-4 py-2 rounded-full bg-card-bg text-white text-sm font-medium border border-gray-800/50 hover:bg-card-hover hover:border-primary/50 transition-all">
                View All
                <i class="fas fa-arrow-right ml-2"></i>
            </a>
        </div>

        <p class="text-gray-300 mb-6"><?= htmlspecialchars($settings['blog_section_description'] ?? 'Read our latest articles and stay updated with gaming news and tips.') ?></p>

        <div class="grid grid-cols-1 md:grid-cols-3 gap-6">
            <?php if (!empty($blogPosts)): ?>
                <?php foreach ($blogPosts as $post): ?>
                <a href="/blog/<?= $post['slug'] ?>" class="bg-card-bg rounded-xl overflow-hidden hover:shadow-hover transition-all duration-300 border border-gray-800/50 hover:border-primary/50">
                    <?php if (!empty($post['featured_image'])): ?>
                    <div class="aspect-video overflow-hidden">
                        <img src="<?= htmlspecialchars($post['featured_image']) ?>" alt="<?= htmlspecialchars($post['title']) ?>"
                             class="w-full h-full object-cover transition-transform duration-500 hover:scale-110" loading="lazy">
                    </div>
                    <?php endif; ?>
                    <div class="p-6">
                        <h3 class="text-lg font-semibold mb-2 group-hover:text-primary transition-colors"><?= htmlspecialchars($post['title']) ?></h3>
                        <div class="text-gray-400 text-sm mb-3">
                            <span class="flex items-center">
                                <i class="far fa-calendar-alt mr-2"></i>
                                <?= date('M j, Y', strtotime($post['created_at'])) ?>
                            </span>
                            <?php if (!empty($post['tags'])): ?>
                            <div class="flex flex-wrap gap-2 mt-2">
                                <?php
                                $tags = explode(',', $post['tags']);
                                foreach (array_slice($tags, 0, 2) as $tag):
                                ?>
                                <span class="bg-sidebar-bg px-2 py-1 rounded-full text-xs hover:bg-primary/20 transition-colors">
                                    <i class="fas fa-tag mr-1"></i><?= htmlspecialchars(trim($tag)) ?>
                                </span>
                                <?php endforeach; ?>
                                <?php if (count($tags) > 2): ?>
                                <span class="text-xs text-gray-400">+<?= count($tags) - 2 ?> more</span>
                                <?php endif; ?>
                            </div>
                            <?php endif; ?>
                        </div>
                        <div class="text-gray-300 line-clamp-3">
                            <?= substr(strip_tags($post['content']), 0, 150) ?>...
                        </div>
                    </div>
                </a>
                <?php endforeach; ?>
            <?php else: ?>
                <div class="col-span-3 bg-card-bg rounded-xl p-6 text-center border border-gray-800/50">
                    <p class="text-gray-300 mb-4">No blog posts available yet.</p>
                    <a href="/blog" class="inline-flex items-center px-4 py-2 bg-card-bg rounded-lg text-white hover:bg-card-hover border border-gray-800/50 hover:border-primary/50 transition-all">
                        Visit Blog
                        <i class="fas fa-arrow-right ml-2"></i>
                    </a>
                </div>
            <?php endif; ?>
        </div>
    </section>
    <?php endif; ?>
</div>

<script>
// Slider functionality
document.addEventListener('DOMContentLoaded', function() {
    const slider = document.getElementById('gameSlider');
    const slides = document.querySelectorAll('.slider-slide');
    const dots = document.querySelectorAll('.slider-dot');
    const prevBtn = document.querySelector('.slider-prev');
    const nextBtn = document.querySelector('.slider-next');
    
    if (!slider || slides.length === 0) return;
    
    let currentSlide = 0;
    const totalSlides = slides.length;
    
    function updateSlider() {
        const translateX = -currentSlide * 100;
        slider.style.transform = `translateX(${translateX}%)`;
        
        // Update dots
        dots.forEach((dot, index) => {
            if (index === currentSlide) {
                dot.classList.add('bg-white');
                dot.classList.remove('bg-white/50');
            } else {
                dot.classList.remove('bg-white');
                dot.classList.add('bg-white/50');
            }
        });
    }
    
    function nextSlide() {
        currentSlide = (currentSlide + 1) % totalSlides;
        updateSlider();
    }
    
    function prevSlide() {
        currentSlide = (currentSlide - 1 + totalSlides) % totalSlides;
        updateSlider();
    }
    
    function goToSlide(index) {
        currentSlide = index;
        updateSlider();
    }
    
    // Event listeners
    if (nextBtn) nextBtn.addEventListener('click', nextSlide);
    if (prevBtn) prevBtn.addEventListener('click', prevSlide);
    
    dots.forEach((dot, index) => {
        dot.addEventListener('click', () => goToSlide(index));
    });
    
    // Auto-play slider
    let autoPlayInterval = setInterval(nextSlide, 5000);
    
    // Pause auto-play on hover
    const sliderContainer = document.querySelector('.slider-container');
    if (sliderContainer) {
        sliderContainer.addEventListener('mouseenter', () => {
            clearInterval(autoPlayInterval);
        });
        
        sliderContainer.addEventListener('mouseleave', () => {
            autoPlayInterval = setInterval(nextSlide, 5000);
        });
    }
    
    // Touch/swipe support for mobile
    let startX = 0;
    let endX = 0;
    
    if (sliderContainer) {
        sliderContainer.addEventListener('touchstart', (e) => {
            startX = e.touches[0].clientX;
        });
        
        sliderContainer.addEventListener('touchend', (e) => {
            endX = e.changedTouches[0].clientX;
            const diff = startX - endX;
            
            if (Math.abs(diff) > 50) {
                if (diff > 0) {
                    nextSlide();
                } else {
                    prevSlide();
                }
            }
        });
    }
});
</script>

<?php include __DIR__ . '/layout/footer.php'; ?>
