<?php
require_once 'config/database.php';
require_once 'config/auth.php';
require_once 'includes/functions.php';

$category_slug = $_GET['cat'] ?? '';
$page_title = 'Category';

if (!$category_slug) {
    header('HTTP/1.0 404 Not Found');
    $page_title = 'Category Not Found';
    include 'includes/header.php';
    echo '<div class="container"><div class="error-message"><h1>Category Not Found</h1><p>The category you are looking for does not exist.</p><a href="' . BASE_URL . 'home" class="btn btn-primary">Back to Home</a></div></div>';
    include 'includes/footer.php';
    exit;
}

$posts = getPostsByCategory($category_slug);
$category = getCategoryBySlug($category_slug); // Assuming this function exists, or we can get from posts

if ($category) {
    $page_title = $category['name'];
} else {
    $page_title = ucfirst($category_slug);
}

if ($category_slug == 'news') {
    $use_tailwind = true;
    $newsArticles = fetchNewsFromAPI(1, 10); // Initial load
}

include 'includes/header.php';
?>

<?php if ($category_slug == 'news'): ?>
<div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-12">

    <!-- Category Title Section -->
    <div class="mb-10 border-b-2 border-sky-400 pb-4">
        <h1 class="text-4xl sm:text-5xl font-extrabold text-primary-dark">Latest News & Updates</h1>
        <p class="mt-2 text-lg text-gray-500">In-depth coverage and insightful articles from our global correspondents.</p>
    </div>

    <!-- News Grid Layout -->
    <div id="news-grid" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8">
        <?php if (!empty($newsArticles)): ?>
            <?php foreach ($newsArticles as $index => $article): ?>
                <?php
                $isFeatured = $index === 0; // First article as featured
                $imageUrl = $article['urlToImage'] ?? 'https://placehold.co/600x400/cccccc/ffffff?text=No+Image';
                $title = htmlspecialchars($article['title'] ?? 'No Title');
                $description = htmlspecialchars($article['description'] ?? 'No description available.');
                $url = $article['url'] ?? '#';
                $author = $article['author'] ?? $article['source']['name'] ?? 'Unknown';
                $publishedAt = $article['publishedAt'] ? date('M j, Y', strtotime($article['publishedAt'])) : 'Unknown Date';
                $source = $article['source']['name'] ?? 'Unknown Source';
                $categoryColors = ['bg-sky-100 text-sky-800', 'bg-emerald-100 text-emerald-800', 'bg-amber-100 text-amber-800', 'bg-red-100 text-red-800', 'bg-violet-100 text-violet-800'];
                $categoryColor = $categoryColors[$index % count($categoryColors)];
                ?>
                <a href="<?php echo htmlspecialchars($url); ?>" target="_blank" class="<?php echo $isFeatured ? 'col-span-1 lg:col-span-2' : ''; ?> bg-white rounded-xl shadow-lg overflow-hidden transition duration-300 hover-lift group flex flex-col <?php echo $isFeatured ? 'md:flex-row shadow-2xl' : ''; ?>">
                    <!-- Image Area -->
                    <div class="<?php echo $isFeatured ? 'md:w-1/2' : ''; ?> overflow-hidden">
                        <img src="<?php echo htmlspecialchars($imageUrl); ?>" alt="<?php echo $title; ?>" class="w-full <?php echo $isFeatured ? 'h-full' : 'h-48'; ?> object-cover transition duration-500 group-hover:scale-[1.03]">
                    </div>
                    <!-- Content Area -->
                    <div class="<?php echo $isFeatured ? 'md:w-1/2' : ''; ?> p-6 flex flex-col justify-between <?php echo !$isFeatured ? 'flex-grow' : ''; ?>">
                        <div>
                            <span class="inline-block px-3 py-1 text-xs font-semibold uppercase tracking-wider <?php echo $categoryColor; ?> rounded-full mb-2">
                                <?php echo htmlspecialchars($source); ?>
                            </span>
                            <h2 class="<?php echo $isFeatured ? 'text-2xl' : 'text-xl'; ?> font-bold text-primary-dark group-hover:text-sky-600 transition duration-150">
                                <?php echo $title; ?>
                            </h2>
                            <p class="mt-<?php echo $isFeatured ? '3' : '2'; ?> text-gray-600 <?php echo $isFeatured ? 'leading-relaxed' : 'text-sm'; ?>">
                                <?php echo $description; ?>
                            </p>
                        </div>
                        <div class="mt-4 text-<?php echo $isFeatured ? 'sm' : 'xs'; ?> text-gray-400">
                            By <?php echo htmlspecialchars($author); ?> | <?php echo $publishedAt; ?>
                        </div>
                    </div>
                </a>
            <?php endforeach; ?>
        <?php else: ?>
            <div class="col-span-full text-center py-12">
                <i class="fas fa-newspaper text-6xl text-gray-300 mb-4"></i>
                <p class="text-gray-500">No news articles available at the moment. Please check back later.</p>
            </div>
        <?php endif; ?>
    </div>

    <!-- Pagination/Load More Section -->
    <div class="mt-12 flex justify-center">
        <button id="load-more-btn" class="px-8 py-3 bg-primary-dark text-white font-semibold rounded-full shadow-xl hover:bg-sky-600 transition duration-300 focus:outline-none focus:ring-4 focus:ring-sky-500 focus:ring-opacity-50" data-page="2">
            Load More News
        </button>
    </div>

    <script>
        document.getElementById('load-more-btn').addEventListener('click', function() {
            const btn = this;
            const page = parseInt(btn.getAttribute('data-page'));
            btn.textContent = 'Loading...';
            btn.disabled = true;

            fetch('api/news.php?page=' + page)
                .then(response => response.json())
                .then(data => {
                    if (data.articles && data.articles.length > 0) {
                        const grid = document.getElementById('news-grid');
                        data.articles.forEach((article, index) => {
                            const imageUrl = article.urlToImage || 'https://placehold.co/600x400/cccccc/ffffff?text=No+Image';
                            const title = article.title || 'No Title';
                            const description = article.description || 'No description available.';
                            const url = article.url || '#';
                            const author = article.author || article.source.name || 'Unknown';
                            const publishedAt = article.publishedAt ? new Date(article.publishedAt).toLocaleDateString('en-US', { year: 'numeric', month: 'short', day: 'numeric' }) : 'Unknown Date';
                            const source = article.source.name || 'Unknown Source';
                            const categoryColors = ['bg-sky-100 text-sky-800', 'bg-emerald-100 text-emerald-800', 'bg-amber-100 text-amber-800', 'bg-red-100 text-red-800', 'bg-violet-100 text-violet-800'];
                            const categoryColor = categoryColors[index % categoryColors.length];

                            const cardHtml = `
                                <a href="${url}" target="_blank" class="bg-white rounded-xl shadow-lg overflow-hidden transition duration-300 hover-lift group flex flex-col">
                                    <img src="${imageUrl}" alt="${title}" class="w-full h-48 object-cover transition duration-500 group-hover:scale-[1.03]">
                                    <div class="p-6 flex flex-col justify-between flex-grow">
                                        <div>
                                            <span class="inline-block px-3 py-1 text-xs font-semibold uppercase tracking-wider ${categoryColor} rounded-full mb-2">
                                                ${source}
                                            </span>
                                            <h2 class="text-xl font-bold text-primary-dark group-hover:text-sky-600 transition duration-150">
                                                ${title}
                                            </h2>
                                            <p class="mt-2 text-gray-600 text-sm">
                                                ${description}
                                            </p>
                                        </div>
                                        <div class="mt-4 text-xs text-gray-400">
                                            By ${author} | ${publishedAt}
                                        </div>
                                    </div>
                                </a>
                            `;
                            grid.insertAdjacentHTML('beforeend', cardHtml);
                        });
                        btn.setAttribute('data-page', page + 1);
                        btn.textContent = 'Load More News';
                        btn.disabled = false;
                    } else {
                        btn.textContent = 'No More News';
                        btn.disabled = true;
                    }
                })
                .catch(error => {
                    console.error('Error loading news:', error);
                    btn.textContent = 'Error Loading News';
                    btn.disabled = false;
                });
        });
    </script>

</div>
<?php else: ?>
<section class="category-posts">
    <div class="container">
        <h1 class="section-title"><?php echo htmlspecialchars($page_title); ?></h1>

        <?php if ($posts): ?>
            <div class="posts-grid">
                <?php foreach ($posts as $post): ?>
                    <article class="post-card">
                        <div class="post-header">
                            <span class="post-category"><?php echo htmlspecialchars($post['category_name']); ?></span>
                            <time class="post-date"><?php echo formatDate($post['created_at']); ?></time>
                        </div>
                        <h3 class="post-title">
                            <a href="<?php echo BASE_URL; ?>post.php?slug=<?php echo urlencode($post['slug']); ?>">
                                <?php echo htmlspecialchars($post['title']); ?>
                            </a>
                        </h3>
                        <p class="post-excerpt">
                            <?php echo htmlspecialchars(truncateText(strip_tags($post['content']))); ?>
                        </p>
                        <div class="post-footer">
                            <span class="post-author">By <?php echo htmlspecialchars($post['author_name']); ?></span>
                            <a href="<?php echo BASE_URL; ?>post.php?slug=<?php echo urlencode($post['slug']); ?>" class="read-more">
                                Read More <i class="fas fa-arrow-right"></i>
                            </a>
                        </div>
                    </article>
                <?php endforeach; ?>
            </div>
        <?php else: ?>
            <div class="no-posts">
                <i class="fas fa-newspaper"></i>
                <p>No posts found in this category. Check back soon!</p>
            </div>
        <?php endif; ?>
    </div>
</section>
<?php endif; ?>

<?php include 'includes/footer.php'; ?>