<!DOCTYPE html>
<html lang="en">
<?php
$pagetitle = "Blogs & Insights | Nesvra";
include 'components/head.php';
require_once 'includes/blog-service.php';

// Category count aggregation
$categoryCounts = get_blog_categories();
$blog_categories = array_keys($categoryCounts);

// Filter & Pagination parameters
$current_filter = isset($_GET['category']) ? $_GET['category'] : 'All Blog';
$current_page   = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;
$search_query   = isset($_GET['q']) ? trim($_GET['q']) : '';
$posts_per_page = 12;

$filteredPosts = search_blogs($search_query, $current_filter);
$allPosts      = get_all_blogs('all');

$totalPosts = count($filteredPosts);
$pageCount  = max(1, (int) ceil($totalPosts / $posts_per_page));
if ($current_page > $pageCount) {
    $current_page = $pageCount;
}

$startIndex   = ($current_page - 1) * $posts_per_page;
$showingStart = $totalPosts > 0 ? $startIndex + 1 : 0;
$showingEnd   = min($totalPosts, $startIndex + $posts_per_page);
$visiblePosts = array_slice($filteredPosts, $startIndex, $posts_per_page);

// Featured spotlight stories
$featuredList   = array_values(array_filter($allPosts, function($p) { return ($p['featured'] ?? 'no') === 'yes'; }));
$spotlightPost  = $featuredList[0] ?? ($allPosts[0] ?? null);
$spotlightCards = count($featuredList) > 1 ? array_slice($featuredList, 1, 2) : array_slice($allPosts, 1, 2);
?>

<body class="bg-white">
    <?php include 'components/navbar.php'; ?>

    <!-- HERO HEADER -->
    <section class="relative min-h-[55dvh] lg:min-h-[65dvh] w-full overflow-hidden flex items-end">
        <div class="absolute inset-0 z-0">
            <div class="absolute inset-0 bg-dark/60 z-10"></div>
            <img src="Asset/home-v3.webp"
                class="w-full h-full object-cover bg-fixed"
                style="background-attachment: fixed; background-position: center;" alt="Nesvra Blog" />
        </div>

        <div class="relative z-20 h-full w-full max-w-8xl mx-auto px-6 md:px-16 pt-36 pb-16 flex flex-col items-start text-left">
            <span class="font-mono text-[11px] font-bold tracking-[0.4em] text-brandOrange uppercase mb-3" data-aos="fade-right">
                Knowledge & Insights
            </span>
            <h1 data-aos="fade-right" data-aos-delay="200"
                class="max-w-4xl text-4xl md:text-6xl font-[400] tracking-[-0.05em] leading-[1.05] text-white">
                Fintech, Software & <span class="italic font-serif text-brandOrange">Ecosystem Insights</span>
            </h1>
            <p data-aos="fade-right" data-aos-delay="400"
                class="mt-4 max-w-2xl text-sm md:text-base text-white/70 font-mono leading-relaxed">
                Practical blueprints, market analyses, and engineering guides for founders, executives, and product leaders.
            </p>
        </div>
    </section>

    <!-- FEATURED / LATEST STORIES (Shown on page 1 with no active search) -->
    <?php if ($current_page === 1 && empty($search_query) && $current_filter === 'All Blog'): ?>
        <section class="py-20 px-6 md:px-[4%] max-w-[1300px] bg-white mx-auto border-b border-zinc-100" id="featured-blogs">
            <div class="mb-12" data-aos="fade-up">
                <span class="font-mono text-[11px] font-bold tracking-[0.4em] text-electric uppercase block mb-3">
                    {01} SPOTLIGHT
                </span>
                <h2 class="text-3xl md:text-5xl font-[400] tracking-tighter text-dark leading-tight max-w-3xl">
                    Bold ideas on vision, strategy, and infrastructure built for <span class="italic font-serif text-electric">business scale</span>
                </h2>
            </div>

            <div class="grid grid-cols-1 lg:grid-cols-12 gap-6 w-full" data-aos="fade-up" data-aos-delay="100">
                <?php if ($spotlightPost):
                    $spotlightSlug = $spotlightPost['slug'] ?? basename($spotlightPost['path'], '.php');
                    $spotlightUrl  = "blog-details.php?slug=" . urlencode($spotlightSlug);
                ?>
                    <a href="<?= htmlspecialchars($spotlightUrl) ?>" class="relative rounded-[28px] overflow-hidden lg:col-span-7 min-h-[440px] group cursor-pointer shadow-lg flex flex-col justify-end p-8 md:p-12">
                        <img
                            src="<?= htmlspecialchars($spotlightPost['image']) ?>"
                            alt="<?= htmlspecialchars($spotlightPost['title']) ?>"
                            class="w-full h-full object-cover absolute inset-0 transition-transform duration-1000 group-hover:scale-105" />
                        <div class="absolute inset-0 bg-gradient-to-t from-dark/90 via-dark/40 to-transparent"></div>

                        <div class="relative z-10 space-y-3">
                            <div class="flex items-center gap-3">
                                <span class="bg-brandOrange text-white text-[10px] font-bold uppercase tracking-widest px-4 py-1.5 rounded-full">
                                    <?= htmlspecialchars($spotlightPost['category']) ?>
                                </span>
                                <span class="text-white/70 font-mono text-xs">
                                    <?= htmlspecialchars($spotlightPost['readTime'] ?? '8 min read') ?>
                                </span>
                            </div>

                            <h3 class="text-white text-2xl md:text-3xl lg:text-4xl font-[400] tracking-tighter leading-[1.15]">
                                <?= htmlspecialchars($spotlightPost['title']) ?>
                            </h3>
                            <p class="text-white/80 text-sm line-clamp-2 max-w-2xl font-light">
                                <?= htmlspecialchars($spotlightPost['description']) ?>
                            </p>
                        </div>
                    </a>
                <?php endif; ?>

                <div class="lg:col-span-5 flex flex-col gap-6">
                    <?php foreach ($spotlightCards as $post):
                        $cardSlug = $post['slug'] ?? basename($post['path'], '.php');
                        $cardUrl  = "blog-details.php?slug=" . urlencode($cardSlug);
                    ?>
                        <a href="<?= htmlspecialchars($cardUrl) ?>" class="flex flex-col sm:flex-row items-stretch border border-zinc-100 rounded-[24px] overflow-hidden bg-white p-3 group cursor-pointer hover:bg-zinc-50 hover:border-royal/20 transition-all duration-300 flex-1 shadow-sm">
                            <div class="relative w-full sm:w-44 flex-shrink-0 aspect-[4/3] sm:aspect-auto rounded-[18px] overflow-hidden">
                                <img
                                    src="<?= htmlspecialchars($post['image']) ?>"
                                    alt="<?= htmlspecialchars($post['title']) ?>"
                                    class="w-full h-full object-cover transition-transform duration-700 group-hover:scale-105" />
                                <span class="absolute top-3 left-3 bg-white/90 text-dark text-[9px] font-bold uppercase tracking-widest px-3 py-1 rounded-full shadow-sm backdrop-blur-sm">
                                    <?= htmlspecialchars($post['category']) ?>
                                </span>
                            </div>

                            <div class="flex flex-col justify-between p-4 flex-1">
                                <div>
                                    <span class="text-soft font-mono text-[10px] uppercase tracking-wider block mb-1">
                                        <?= htmlspecialchars($post['readTime'] ?? '6 min read') ?>
                                    </span>
                                    <h4 class="text-base font-semibold text-dark tracking-tight leading-snug group-hover:text-electric transition-colors line-clamp-2">
                                        <?= htmlspecialchars($post['title']) ?>
                                    </h4>
                                </div>

                                <div class="flex items-center gap-2 mt-4 text-royal font-bold text-[11px] uppercase tracking-widest">
                                    <span>Read Article</span>
                                    <i class="ri-arrow-right-up-line text-xs group-hover:translate-x-0.5 group-hover:-translate-y-0.5 transition-transform"></i>
                                </div>
                            </div>
                        </a>
                    <?php endforeach; ?>
                </div>
            </div>
        </section>
    <?php endif; ?>

    <!-- MAIN CATALOG & SEARCH CONTROLS -->
    <section class="pt-16 pb-8 px-6 md:px-[4%] max-w-[1300px] bg-white mx-auto" id="all-blogs">
        <div class="flex flex-col md:flex-row md:items-center justify-between gap-6 mb-8" data-aos="fade-up">
            <div>
                <span class="font-mono text-[11px] font-bold tracking-[0.4em] text-brandOrange uppercase block mb-2">
                    {02} EXPLORE ARTICLES
                </span>
                <h2 class="text-3xl md:text-4xl font-[400] tracking-tighter text-dark leading-tight">
                    All <span class="italic font-serif text-electric">Publications</span>
                </h2>
            </div>

            <!-- Instant Search Bar -->
            <form action="blog.php#all-blogs" method="GET" class="relative w-full md:w-80">
                <input type="hidden" name="category" value="<?= htmlspecialchars($current_filter) ?>">
                <div class="relative flex items-center">
                    <i class="ri-search-2-line absolute left-4 text-zinc-400 text-sm pointer-events-none"></i>
                    <input
                        type="text"
                        name="q"
                        id="blogSearchInput"
                        value="<?= htmlspecialchars($search_query) ?>"
                        placeholder="Search topics, keywords..."
                        class="w-full bg-[#F8F9FA] border border-zinc-200 rounded-full pl-11 pr-10 py-3 text-xs font-sans text-dark focus:outline-none focus:border-royal focus:bg-white transition-all shadow-inner placeholder:text-zinc-400" />
                    <?php if (!empty($search_query)): ?>
                        <a href="?category=<?= urlencode($current_filter) ?>#all-blogs" class="absolute right-3 text-zinc-400 hover:text-dark">
                            <i class="ri-close-circle-fill text-base"></i>
                        </a>
                    <?php endif; ?>
                </div>
            </form>
        </div>

        <!-- Category Pills -->
        <div class="flex items-center gap-2.5 overflow-x-auto pb-4 no-scrollbar flex-nowrap md:flex-wrap" data-aos="fade-up" data-aos-delay="100">
            <?php foreach ($blog_categories as $category):
                $isActive = ($current_filter === $category);
                $btnClass = $isActive
                    ? "bg-royal text-white border-royal shadow-md shadow-royal/10"
                    : "bg-[#F8F9FA] text-soft border-zinc-200 hover:border-royal/30 hover:text-dark hover:bg-white";
                $count = $categoryCounts[$category] ?? 0;
            ?>
                <a href="?category=<?= urlencode($category) ?>&q=<?= urlencode($search_query) ?>#all-blogs"
                    class="whitespace-nowrap px-6 py-2.5 rounded-full border font-medium text-xs tracking-tight transition-all duration-300 flex items-center gap-2 <?= $btnClass ?>">
                    <span><?= htmlspecialchars($category) ?></span>
                    <span class="text-[10px] font-mono opacity-60 bg-black/10 px-2 py-0.5 rounded-full"><?= $count ?></span>
                </a>
            <?php endforeach; ?>
        </div>
    </section>

    <!-- POST GRID -->
    <section class="px-6 md:px-[4%] max-w-[1300px] mx-auto pb-20">
        <?php if ($totalPosts === 0): ?>
            <div class="col-span-full rounded-[28px] border border-zinc-200 bg-[#F8F9FA] p-16 text-center text-dark my-12" data-aos="fade-up">
                <i class="ri-article-line text-4xl text-zinc-300 block mb-3"></i>
                <h3 class="text-xl font-semibold text-royal mb-2">No articles found</h3>
                <p class="text-soft text-sm mb-6 max-w-md mx-auto">
                    We couldn't find any articles matching "<strong><?= htmlspecialchars($search_query ?: $current_filter) ?></strong>".
                </p>
                <a href="blog.php#all-blogs" class="inline-flex items-center gap-2 px-6 py-2.5 bg-royal text-white rounded-full text-xs font-semibold hover:bg-electric transition-colors">
                    <i class="ri-refresh-line"></i> Reset Filters
                </a>
            </div>
        <?php else: ?>
            <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6" data-aos="fade-up">
                <?php foreach ($visiblePosts as $post):
                    $postSlug = $post['slug'] ?? basename($post['path'], '.php');
                    $postUrl  = "blog-details.php?slug=" . urlencode($postSlug);
                ?>
                    <a href="<?= htmlspecialchars($postUrl) ?>" class="border border-zinc-100 rounded-[24px] overflow-hidden bg-white flex flex-col p-3.5 group cursor-pointer hover:border-royal/20 hover:shadow-xl hover:shadow-royal/5 transition-all duration-500">
                        <!-- Card Thumbnail -->
                        <div class="relative overflow-hidden rounded-[18px] aspect-[16/10] bg-zinc-100">
                            <img
                                src="<?= htmlspecialchars($post['image']) ?>"
                                alt="<?= htmlspecialchars($post['title']) ?>"
                                loading="lazy"
                                class="w-full h-full object-cover transition-transform duration-700 group-hover:scale-105" />
                            <span class="absolute top-3.5 left-3.5 bg-white/90 backdrop-blur-md text-dark text-[10px] font-bold uppercase tracking-wider px-3 py-1 rounded-full shadow-sm">
                                <?= htmlspecialchars($post['category']) ?>
                            </span>
                        </div>

                        <!-- Card Body -->
                        <div class="flex flex-col flex-1 justify-between p-3.5 pt-5">
                            <div>
                                <div class="flex items-center justify-between text-zinc-400 font-mono text-[10px] uppercase tracking-wider mb-2">
                                    <span><?= htmlspecialchars($post['publishDate'] ?? 'May 2026') ?></span>
                                    <span><?= htmlspecialchars($post['readTime'] ?? '6 min read') ?></span>
                                </div>
                                <h3 class="text-lg font-semibold text-dark leading-snug group-hover:text-electric transition-colors line-clamp-2 mb-2">
                                    <?= htmlspecialchars($post['title']) ?>
                                </h3>
                                <p class="text-xs text-soft leading-relaxed line-clamp-3">
                                    <?= htmlspecialchars($post['description']) ?>
                                </p>
                            </div>

                            <div class="mt-6 pt-4 border-t border-zinc-100 flex items-center justify-between text-dark font-semibold text-xs">
                                <span class="group-hover:text-royal transition-colors">Read Article</span>
                                <div class="w-7 h-7 rounded-full bg-zinc-50 border border-zinc-200 flex items-center justify-center group-hover:bg-royal group-hover:text-white group-hover:border-royal transition-all duration-300">
                                    <i class="ri-arrow-right-line text-xs"></i>
                                </div>
                            </div>
                        </div>
                    </a>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>

        <!-- PAGINATION CONTROLS -->
        <?php if ($pageCount > 1): ?>
            <div class="flex flex-col sm:flex-row items-center justify-between gap-4 mt-16 pt-8 border-t border-zinc-100">
                <p class="text-xs font-mono text-soft">
                    Showing <strong class="text-dark"><?= $showingStart ?>-<?= $showingEnd ?></strong> of <strong class="text-dark"><?= $totalPosts ?></strong> articles
                </p>

                <div class="flex items-center gap-2">
                    <?php if ($current_page > 1): ?>
                        <a href="?category=<?= urlencode($current_filter) ?>&q=<?= urlencode($search_query) ?>&page=<?= $current_page - 1 ?>#all-blogs"
                            class="px-4 py-2 rounded-xl border border-zinc-200 text-xs font-semibold text-dark hover:bg-zinc-50 transition-all flex items-center gap-1.5">
                            <i class="ri-arrow-left-s-line text-sm"></i> Previous
                        </a>
                    <?php endif; ?>

                    <span class="text-xs font-mono px-3 py-2 text-soft">
                        Page <?= $current_page ?> of <?= $pageCount ?>
                    </span>

                    <?php if ($current_page < $pageCount): ?>
                        <a href="?category=<?= urlencode($current_filter) ?>&q=<?= urlencode($search_query) ?>&page=<?= $current_page + 1 ?>#all-blogs"
                            class="px-5 py-2 rounded-xl bg-royal text-white text-xs font-semibold hover:bg-electric transition-all shadow-sm flex items-center gap-1.5">
                            Next <i class="ri-arrow-right-s-line text-sm"></i>
                        </a>
                    <?php endif; ?>
                </div>
            </div>
        <?php endif; ?>
    </section>

    <?php include 'components/Scroll-to-top.php'; ?>
    <?php include 'components/footer.php'; ?>

</body>

</html>