<?php
require_once 'includes/db.php';
require_once 'includes/functions.php';

$perPage = 12;
$page = max(1, (int)($_GET['page'] ?? 1));
$totalStmt = $pdo->query("SELECT COUNT(*) FROM posts WHERE status = 'published'");
$totalPosts = (int)$totalStmt->fetchColumn();
$totalPages = max(1, (int)ceil($totalPosts / $perPage));
if ($page > $totalPages) $page = $totalPages;
$offset = ($page - 1) * $perPage;

$stmt = $pdo->prepare("SELECT * FROM posts WHERE status = 'published' ORDER BY created_at DESC LIMIT :lim OFFSET :off");
$stmt->bindValue(':lim', $perPage, PDO::PARAM_INT);
$stmt->bindValue(':off', $offset, PDO::PARAM_INT);
$stmt->execute();
$posts = $stmt->fetchAll();

$featuredPost = ($page === 1 && !empty($posts)) ? array_shift($posts) : null;
?>
<!DOCTYPE html>
<html lang="pt-BR">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Notícias VGrão — Portal do Agronegócio e Mercado de Grãos</title>
    <meta name="description" content="Notícias, análises e tendências do mercado de soja, milho, algodão e comercialização agrícola na plataforma VGrão.">
    <link rel="canonical" href="https://vgrao.com/blog/<?php echo $page > 1 ? '?page=' . $page : ''; ?>">
    <meta property="og:type" content="website">
    <meta property="og:locale" content="pt_BR">
    <meta property="og:title" content="Notícias VGrão — O Portal do Agronegócio">
    <meta property="og:description" content="Análises, cotações e novidades do mercado de grãos.">
    <meta property="og:image" content="https://vgrao.com/imagens/vgraocapa.png">
    <link href="https://fonts.googleapis.com/css2?family=Outfit:wght@300;400;600;700;800&display=swap" rel="stylesheet">
    <style>
        :root {
            --bg-dark: #051F20;
            --surface: #153832;
            --card: #235347;
            --accent: #8EB69B;
            --text-light: #DAF1DD;
            --glass: rgba(255, 255, 255, 0.05);
            --glass-border: rgba(255, 255, 255, 0.1);
        }

        *, *::before, *::after { box-sizing: border-box; }
        body {
            margin: 0;
            font-family: 'Outfit', sans-serif;
            background-color: var(--bg-dark);
            color: var(--text-light);
            line-height: 1.6;
            overflow-x: hidden;
        }

        .navbar {
            position: fixed;
            top: 20px;
            left: 50%;
            transform: translateX(-50%);
            width: 95%;
            max-width: 1200px;
            z-index: 1000;
            padding: 15px 40px;
            border-radius: 100px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            background: rgba(5, 31, 32, 0.85);
            backdrop-filter: blur(15px);
            -webkit-backdrop-filter: blur(15px);
            border: 1px solid rgba(255, 255, 255, 0.1);
            transition: all 0.4s cubic-bezier(0.165, 0.84, 0.44, 1);
            box-shadow: 0 20px 50px rgba(0, 0, 0, 0.2);
        }

        .navbar.scrolled {
            top: 10px;
            background: rgba(5, 31, 32, 0.95);
            box-shadow: 0 10px 40px rgba(0, 0, 0, 0.3);
        }

        .nav-logo img {
            height: 45px;
        }

        .nav-menu {
            display: flex;
            gap: 30px;
            align-items: center;
        }

        .nav-link {
            color: #fff;
            text-decoration: none;
            font-weight: 500;
            font-size: 1rem;
            transition: 0.3s;
            opacity: 0.9;
        }

        .nav-link:hover {
            color: var(--accent);
            opacity: 1;
        }

        .btn-panel {
            background: var(--accent);
            color: var(--bg-dark);
            padding: 12px 28px;
            border-radius: 50px;
            text-decoration: none;
            font-weight: 700;
            display: inline-flex;
            align-items: center;
            gap: 10px;
            transition: 0.3s cubic-bezier(0.165, 0.84, 0.44, 1);
            box-shadow: 0 8px 20px rgba(142, 182, 155, 0.2);
        }

        .btn-panel:hover {
            background: #fff;
            transform: translateY(-2px);
            box-shadow: 0 12px 30px rgba(255, 255, 255, 0.2);
        }

        .mobile-toggle { display: none; background: transparent; border: 1px solid rgba(255,255,255,.25); color: #fff; border-radius: 12px; padding: 8px 14px; min-height: 44px; cursor: pointer; font-weight: 600; }
        @media(max-width: 900px) {
            .navbar { top: 10px; width: calc(100% - 20px); padding: 10px 16px; flex-wrap: wrap; gap: 10px; border-radius: 20px; }
            .nav-logo img { height: 32px; }
            .mobile-toggle { display: inline-flex; align-items: center; gap: 6px; }
            .nav-menu { display: none; width: 100%; flex-direction: column; align-items: stretch; gap: 10px; padding-top: 10px; border-top: 1px solid rgba(255,255,255,.1); }
            .nav-menu.open { display: flex; }
            .nav-menu .nav-link { padding: 8px 4px; }
            .navbar > .btn-panel { display: none; }
            .nav-menu .btn-panel-mobile { display: inline-flex; justify-content: center; margin-top: 4px; }
            .featured-content { padding: 1.5rem; }
            .featured-title { font-size: 1.75rem; }
        }
        .btn-panel-mobile { display: none; }
        .pagination { display: flex; justify-content: center; align-items: center; gap: 10px; margin-top: 3rem; flex-wrap: wrap; }
        .page-btn { padding: 10px 18px; border-radius: 999px; border: 1px solid var(--glass-border); background: var(--surface); color: var(--text-light); text-decoration: none; font-weight: 600; font-size: .9rem; }
        .page-btn.active { background: var(--accent); color: var(--bg-dark); border-color: var(--accent); }

        .container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 0 20px;
        }

        .logo-text {
            font-weight: 800;
            font-size: 1.5rem;
            color: var(--text-light);
            text-decoration: none;
            letter-spacing: -0.5px;
        }

        .logo-text span {
            color: var(--accent);
        }

        /* Hero / Featured Section */
        .featured-section {
            padding: 8.5rem 0 4rem;
            background: linear-gradient(180deg, var(--bg-dark) 0%, var(--surface) 100%);
        }

        .featured-card {
            display: grid;
            grid-template-columns: 1.5fr 1fr;
            background: var(--card);
            border-radius: 30px;
            overflow: hidden;
            box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.5);
            border: 1px solid var(--glass-border);
            transition: 0.3s;
        }

        .featured-image {
            height: 500px;
            background-size: cover;
            background-position: center;
        }

        .featured-content {
            padding: 3rem;
            display: flex;
            flex-direction: column;
            justify-content: center;
        }

        .badge {
            display: inline-block;
            background: var(--accent);
            color: var(--bg-dark);
            padding: 0.3rem 1rem;
            border-radius: 50px;
            font-size: 0.75rem;
            font-weight: 700;
            text-transform: uppercase;
            margin-bottom: 1.5rem;
        }

        .featured-title {
            font-size: 2.8rem;
            line-height: 1.1;
            font-weight: 800;
            margin-bottom: 1.5rem;
            color: #FFFFFF;
        }

        .featured-excerpt {
            font-size: 1.1rem;
            color: var(--accent);
            margin-bottom: 2rem;
            opacity: 0.9;
        }

        /* News Grid */
        .news-grid-section {
            padding: 5rem 0;
        }

        .section-header {
            display: flex;
            align-items: center;
            gap: 20px;
            margin-bottom: 3rem;
        }

        .section-header h2 {
            font-size: 2rem;
            font-weight: 700;
            white-space: nowrap;
        }

        .header-line {
            height: 2px;
            background: var(--surface);
            width: 100%;
        }

        .news-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(min(100%, 300px), 1fr));
            gap: 2rem;
        }

        .news-card {
            background: var(--surface);
            border: 1px solid var(--glass-border);
            border-radius: 24px;
            overflow: hidden;
            transition: all 0.4s cubic-bezier(0.175, 0.885, 0.32, 1.275);
            display: flex;
            flex-direction: column;
        }

        .news-card:hover {
            transform: translateY(-12px);
            background: var(--card);
            border-color: var(--accent);
            box-shadow: 0 20px 40px rgba(0, 0, 0, 0.3);
        }

        .news-image {
            height: 220px;
            background-size: cover;
            background-position: center;
            border-bottom: 2px solid var(--surface);
        }

        .news-content {
            padding: 2rem;
            flex-grow: 1;
        }

        .news-date {
            font-size: 0.8rem;
            color: var(--accent);
            margin-bottom: 1rem;
            font-weight: 600;
            display: block;
        }

        .news-title {
            font-size: 1.3rem;
            font-weight: 700;
            color: #FFFFFF;
            margin-bottom: 1rem;
            line-height: 1.4;
        }

        .news-excerpt {
            font-size: 0.95rem;
            color: var(--text-light);
            opacity: 0.7;
            margin-bottom: 1.5rem;
            display: -webkit-box;
            -webkit-line-clamp: 3;
            line-clamp: 3;
            -webkit-box-orient: vertical;
            overflow: hidden;
        }

        .btn-read {
            color: var(--accent);
            text-decoration: none;
            font-weight: 700;
            font-size: 0.9rem;
            display: flex;
            align-items: center;
            gap: 8px;
            transition: 0.3s;
        }

        .btn-read:hover {
            gap: 12px;
        }

        footer {
            padding: 4rem 0;
            background: #031516;
            border-top: 1px solid var(--surface);
            text-align: center;
            margin-top: 5rem;
        }

        .footer-logo {
            margin-bottom: 1rem;
        }

        .copyright {
            font-size: 0.85rem;
            opacity: 0.5;
        }

        @media (max-width: 992px) {
            .featured-card { grid-template-columns: 1fr; }
            .featured-image { height: 350px; }
            .featured-title { font-size: 2rem; }
        }

        @media (max-width: 768px) {
            .hero h1 { font-size: 2.2rem; }
        }
    </style>
</head>
<body>
    <!-- SVG Gradient Definition -->
    <svg width="0" height="0" style="position:absolute;">
        <defs>
            <linearGradient id="vgrao-gradient" x1="0%" y1="0%" x2="100%" y2="100%">
                <stop offset="0%" style="stop-color:#051F20;stop-opacity:1" />
                <stop offset="100%" style="stop-color:#235347;stop-opacity:1" />
            </linearGradient>
        </defs>
    </svg>

    <nav class="navbar" id="navbar">
        <div class="nav-logo">
            <a href="../index.html"><img src="../imagens/vgraologobranca.png" alt="VGrão"></a>
        </div>
        <button type="button" class="mobile-toggle" id="blog-menu-toggle" aria-label="Abrir menu" aria-expanded="false">Menu ☰</button>
        <div class="nav-menu" id="blog-nav-menu">
            <a href="../index.html#solucoes" class="nav-link">Soluções</a>
            <a href="../index.html#inteligencia" class="nav-link">IAGrão</a>
            <a href="../index.html#cadastro" class="nav-link">Cadastrar</a>
            <a href="index.php" class="nav-link">Notícias</a>
            <a href="https://app.vgrao.com/auth" class="btn-panel btn-panel-mobile">
                <i data-lucide="user"></i> Área do Cliente
            </a>
        </div>
        <a href="https://app.vgrao.com/auth" class="btn-panel">
            <i data-lucide="user"></i> Área do Cliente
        </a>
    </nav>

    <?php if ($featuredPost): ?>
    <section class="featured-section">
        <div class="container">
            <a href="post.php?slug=<?php echo rawurlencode($featuredPost['slug']); ?>" style="text-decoration: none; color: inherit;">
                <div class="featured-card">
                    <div class="featured-image" style="background-image: url('<?php echo htmlspecialchars($featuredPost['image_path'] ? $featuredPost['image_path'] : 'https://images.unsplash.com/photo-1500382017468-9049fee74a62?ixlib=rb-1.2.1&auto=format&fit=crop&w=1350&q=80', ENT_QUOTES, 'UTF-8'); ?>')"></div>
                    <div class="featured-content">
                        <span class="badge">Destaque do Dia</span>
                        <h2 class="featured-title"><?php echo htmlspecialchars($featuredPost['title'], ENT_QUOTES, 'UTF-8'); ?></h2>
                        <p class="featured-excerpt"><?php echo htmlspecialchars(mb_substr(trim(strip_tags($featuredPost['content'] ?? '')), 0, 180, 'UTF-8'), ENT_QUOTES, 'UTF-8'); ?>...</p>
                        <div class="btn-read">LER NOTÍCIA COMPLETA →</div>
                    </div>
                </div>
            </a>
        </div>
    </section>
    <?php endif; ?>

    <section class="news-grid-section" id="noticias">
        <div class="container">
            <div class="section-header">
                <h2>Últimas Notícias</h2>
                <div class="header-line"></div>
            </div>

            <div class="news-grid">
                <?php foreach ($posts as $post): ?>
                <div class="news-card">
                    <div class="news-image" style="background-image: url('<?php echo htmlspecialchars($post['image_path'] ? $post['image_path'] : 'https://images.unsplash.com/photo-1464226184884-fa280b87c399?ixlib=rb-1.2.1&auto=format&fit=crop&w=1350&q=80', ENT_QUOTES, 'UTF-8'); ?>')"></div>
                    <div class="news-content">
                        <span class="news-date"><?php echo formatarDataPortuguês($post['created_at'])['completa']; ?></span>
                        <h3 class="news-title"><?php echo htmlspecialchars($post['title'], ENT_QUOTES, 'UTF-8'); ?></h3>
                        <div class="news-excerpt"><?php echo htmlspecialchars(strip_tags($post['content'] ?? ''), ENT_QUOTES, 'UTF-8'); ?></div>
                        <a href="post.php?slug=<?php echo rawurlencode($post['slug']); ?>" class="btn-read">CONTINUAR LENDO →</a>
                    </div>
                </div>
                <?php endforeach; ?>
                
                <?php if (empty($posts) && !$featuredPost): ?>
                    <div style="grid-column: 1/-1; text-align: center; padding: 5rem; background: var(--surface); border-radius: 30px;">
                        <h3 style="font-size: 1.5rem; opacity: 0.7;">Estamos preparando as melhores notícias para você. Volte em breve!</h3>
                    </div>
                <?php endif; ?>
            </div>

            <?php if ($totalPages > 1): ?>
            <nav class="pagination" aria-label="Paginação de notícias">
                <?php if ($page > 1): ?>
                    <a class="page-btn" href="?page=<?php echo $page - 1; ?>">← Anterior</a>
                <?php endif; ?>
                <?php for ($p = 1; $p <= $totalPages; $p++): ?>
                    <a class="page-btn <?php echo $p === $page ? 'active' : ''; ?>" href="?page=<?php echo $p; ?>"><?php echo $p; ?></a>
                <?php endfor; ?>
                <?php if ($page < $totalPages): ?>
                    <a class="page-btn" href="?page=<?php echo $page + 1; ?>">Próxima →</a>
                <?php endif; ?>
            </nav>
            <?php endif; ?>
        </div>
    </section>

    <footer>
        <div class="container">
            <div class="footer-logo logo-text">VGRÃO <span>NEWS</span></div>
            <p class="copyright">&copy; <?php echo date('Y'); ?> VGRÃO. Todos os direitos reservados.</p>
        </div>
    </footer>
    <script src="https://unpkg.com/lucide@latest"></script>
    <script>
        lucide.createIcons();

        const toggleBtn = document.getElementById('blog-menu-toggle');
        const navMenu = document.getElementById('blog-nav-menu');
        if (toggleBtn && navMenu) {
            toggleBtn.addEventListener('click', () => {
                const open = navMenu.classList.toggle('open');
                toggleBtn.setAttribute('aria-expanded', open ? 'true' : 'false');
            });
        }

        window.addEventListener('scroll', () => {
            const nav = document.getElementById('navbar');
            if (window.scrollY > 50) {
                nav.classList.add('scrolled');
            } else {
                nav.classList.remove('scrolled');
            }
        });
    </script>
</body>
</html>
