<?php
require_once 'config.php';

$posts = [];
if (file_exists(POSTS_DB_FILE)) {
    $posts = json_decode(file_get_contents(POSTS_DB_FILE), true) ?? [];
}

// Helper: extract first image from HTML content
function extractFirstImage($html) {
    if (preg_match('/<img[^>]+src=["\']([^"\']+)["\']/', $html, $m)) {
        return $m[1];
    }
    return null;
}

// Helper: generate text excerpt from HTML
function generateExcerpt($html, $maxLen = 140) {
    $text = strip_tags($html);
    $text = trim(preg_replace('/\s+/', ' ', $text));
    if (mb_strlen($text) > $maxLen) {
        $text = mb_substr($text, 0, $maxLen);
        $text = preg_replace('/\s+\S*$/', '', $text) . '…';
    }
    return $text;
}

// Helper: estimate reading time
function readingTime($html) {
    $words = str_word_count(strip_tags($html));
    $mins = max(1, ceil($words / 200));
    return $mins . ' min de lectura';
}
?>
<!DOCTYPE html>
<html lang="es">

<head>
    <meta charset="UTF-8">
    <link rel="icon" type="image/svg+xml" href="favicon.svg">
    <link rel="alternate icon" href="favicon.ico">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Blog - InmovillaToWordPress</title>

    <meta name="description"
        content="Blog de InmovillaToWordPress. Noticias, guías y novedades sobre sincronización de propiedades Inmovilla con WordPress.">

    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=SF+Pro+Display:wght@300;400;500;600;700&display=swap"
        rel="stylesheet">
    <link rel="stylesheet" href="mobile-responsive.css">

    <style>
        :root {
            --primary: #1d1d1f;
            --secondary: #667eea;
            --accent: #06c;
            --text: #1d1d1f;
            --text-light: #86868b;
            --bg: #fbfbfd;
            --card-bg: #fff;
        }

        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'SF Pro Display', 'Segoe UI', sans-serif;
            background: var(--bg);
            color: var(--text);
            -webkit-font-smoothing: antialiased;
            line-height: 1.5;
        }

        /* ===== Navigation ===== */
        nav {
            position: fixed;
            top: 0;
            width: 100%;
            background: rgba(251, 251, 253, 0.8);
            backdrop-filter: saturate(180%) blur(20px);
            z-index: 1000;
            border-bottom: 1px solid rgba(0, 0, 0, 0.05);
            transition: all 0.3s ease;
        }

        nav.scrolled {
            background: rgba(251, 251, 253, 0.95);
            box-shadow: 0 2px 20px rgba(0, 0, 0, 0.08);
        }

        .nav-content {
            max-width: 1400px;
            margin: 0 auto;
            padding: 0 50px;
            height: 70px;
            display: flex;
            align-items: center;
            justify-content: space-between;
        }

        .logo {
            font-size: 21px;
            font-weight: 600;
            letter-spacing: -0.5px;
            color: var(--primary);
            text-decoration: none;
        }

        .nav-links {
            display: flex;
            gap: 32px;
            align-items: center;
        }

        .nav-links a {
            color: var(--text);
            text-decoration: none;
            font-size: 14px;
            font-weight: 400;
            transition: opacity 0.2s;
        }

        .nav-links a:hover {
            opacity: 0.7;
        }

        .cta-button {
            background: var(--accent);
            color: white;
            padding: 8px 18px;
            border-radius: 980px;
            font-size: 14px;
            font-weight: 500;
            text-decoration: none;
            transition: all 0.2s;
        }

        .cta-button:hover {
            background: #0077ed;
            transform: scale(1.02);
        }

        /* ===== Mobile Menu ===== */
        .desktop-only { display: flex; }
        .mobile-menu-btn {
            display: none;
            background: none;
            border: none;
            cursor: pointer;
            padding: 8px;
            color: var(--text);
        }

        .mobile-menu {
            display: none;
            position: fixed;
            top: 0; left: 0;
            width: 100%; height: 100%;
            background: white;
            z-index: 10000;
            flex-direction: column;
        }

        .mobile-menu.active { display: flex; }

        .mobile-menu-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 12px 20px;
            border-bottom: 1px solid rgba(0,0,0,0.05);
        }

        .mobile-menu-close {
            background: none;
            border: none;
            cursor: pointer;
            padding: 8px;
            color: var(--text);
        }

        .mobile-menu-links {
            display: flex;
            flex-direction: column;
            padding: 20px;
        }

        .mobile-menu-links a {
            padding: 16px 0;
            font-size: 18px;
            font-weight: 500;
            color: var(--text);
            text-decoration: none;
            border-bottom: 1px solid rgba(0,0,0,0.05);
        }

        .mobile-menu-links .mobile-cta {
            background: var(--accent);
            color: white !important;
            text-align: center;
            border-radius: 12px;
            margin-top: 20px;
            border: none;
            padding: 16px;
        }

        /* ===== Blog Layout ===== */
        .blog-wrapper {
            max-width: 1200px;
            margin: 0 auto;
            padding: 120px 40px 80px;
        }

        .blog-header {
            text-align: center;
            margin-bottom: 60px;
        }

        .blog-header h1 {
            font-size: 52px;
            font-weight: 700;
            letter-spacing: -1.5px;
            color: var(--primary);
            margin-bottom: 14px;
        }

        .blog-header p {
            color: var(--text-light);
            font-size: 19px;
            font-weight: 400;
        }

        .refresh-btn {
            display: inline-flex;
            align-items: center;
            gap: 6px;
            margin-top: 24px;
            padding: 10px 22px;
            background: white;
            border: 1px solid #e0e0e0;
            border-radius: 980px;
            color: var(--text);
            cursor: pointer;
            font-size: 14px;
            font-weight: 500;
            transition: all 0.2s;
        }

        .refresh-btn:hover {
            background: #f5f5f7;
            border-color: #ccc;
        }

        /* ===== Grid de Tarjetas ===== */
        .posts-grid {
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            gap: 28px;
        }

        .card {
            background: var(--card-bg);
            border-radius: 18px;
            overflow: hidden;
            box-shadow: 0 1px 3px rgba(0,0,0,0.04), 0 4px 16px rgba(0,0,0,0.04);
            cursor: pointer;
            transition: transform 0.35s cubic-bezier(.2,.8,.4,1), box-shadow 0.35s ease;
            display: flex;
            flex-direction: column;
        }

        .card:hover {
            transform: translateY(-6px);
            box-shadow: 0 8px 30px rgba(0,0,0,0.1);
        }

        .card-thumb {
            width: 100%;
            aspect-ratio: 16 / 9;
            overflow: hidden;
            background: linear-gradient(135deg, #f0f0f3 0%, #e8e8ed 100%);
            position: relative;
        }

        .card-thumb img {
            width: 100%;
            height: 100%;
            object-fit: cover;
            transition: transform 0.5s cubic-bezier(.2,.8,.4,1);
        }

        .card:hover .card-thumb img {
            transform: scale(1.05);
        }

        .card-thumb-placeholder {
            width: 100%;
            height: 100%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 40px;
            color: #c4c4c8;
            background: linear-gradient(160deg, #f5f5f7 0%, #ececf0 100%);
        }

        .card-body {
            padding: 24px 24px 28px;
            display: flex;
            flex-direction: column;
            flex: 1;
        }

        .card-meta {
            display: flex;
            align-items: center;
            gap: 10px;
            margin-bottom: 12px;
        }

        .card-date {
            font-size: 13px;
            font-weight: 600;
            color: var(--accent);
            text-transform: uppercase;
            letter-spacing: 0.6px;
        }

        .card-reading {
            font-size: 12px;
            color: var(--text-light);
            font-weight: 400;
        }

        .card-meta-dot {
            width: 3px;
            height: 3px;
            border-radius: 50%;
            background: var(--text-light);
            flex-shrink: 0;
        }

        .card-title {
            font-size: 20px;
            font-weight: 700;
            line-height: 1.3;
            margin-bottom: 12px;
            color: var(--primary);
            letter-spacing: -0.3px;
        }

        .card-excerpt {
            font-size: 15px;
            color: #6e6e73;
            line-height: 1.6;
            flex: 1;
        }

        .card-read-more {
            display: inline-flex;
            align-items: center;
            gap: 6px;
            margin-top: 18px;
            font-size: 14px;
            font-weight: 600;
            color: var(--accent);
            transition: gap 0.2s ease;
        }

        .card:hover .card-read-more {
            gap: 10px;
        }

        .card-read-more svg {
            transition: transform 0.2s ease;
        }

        .card:hover .card-read-more svg {
            transform: translateX(2px);
        }

        /* ===== Vista Detalle del Artículo ===== */
        .article-view {
            display: none;
            max-width: 780px;
            margin: 0 auto;
            padding: 120px 40px 80px;
            animation: fadeInUp 0.4s ease;
        }

        .article-view.active {
            display: block;
        }

        @keyframes fadeInUp {
            from { opacity: 0; transform: translateY(24px); }
            to   { opacity: 1; transform: translateY(0); }
        }

        .article-back {
            display: inline-flex;
            align-items: center;
            gap: 8px;
            font-size: 15px;
            font-weight: 500;
            color: var(--accent);
            text-decoration: none;
            margin-bottom: 36px;
            cursor: pointer;
            transition: gap 0.2s;
            background: none;
            border: none;
            padding: 0;
            font-family: inherit;
        }

        .article-back:hover {
            gap: 12px;
        }

        .article-back svg {
            transition: transform 0.2s;
        }

        .article-back:hover svg {
            transform: translateX(-3px);
        }

        .article-meta {
            display: flex;
            align-items: center;
            gap: 10px;
            margin-bottom: 18px;
        }

        .article-meta .card-date {
            font-size: 14px;
        }

        .article-title {
            font-size: 44px;
            font-weight: 700;
            line-height: 1.15;
            letter-spacing: -1.2px;
            color: var(--primary);
            margin-bottom: 36px;
        }

        .article-content {
            font-size: 18px;
            color: #333;
            line-height: 1.85;
        }

        .article-content img {
            width: 100%;
            border-radius: 14px;
            margin: 30px 0;
            box-shadow: 0 4px 20px rgba(0,0,0,0.06);
        }

        .article-content h2 {
            font-size: 28px;
            font-weight: 700;
            margin: 40px 0 16px;
            color: var(--primary);
            letter-spacing: -0.5px;
        }

        .article-content h3 {
            font-size: 22px;
            font-weight: 600;
            margin: 32px 0 12px;
            color: var(--primary);
        }

        .article-content p {
            margin-bottom: 20px;
        }

        .article-content a {
            color: var(--accent);
            text-decoration: none;
            border-bottom: 1px solid transparent;
            transition: border-color 0.2s;
        }

        .article-content a:hover {
            border-bottom-color: var(--accent);
        }

        .article-content strong {
            font-weight: 600;
            color: var(--primary);
        }

        /* ===== Empty State ===== */
        .empty-state {
            text-align: center;
            padding: 80px 40px;
            background: white;
            border-radius: 20px;
            box-shadow: 0 1px 3px rgba(0,0,0,0.04), 0 4px 16px rgba(0,0,0,0.04);
        }

        .empty-state-icon {
            font-size: 48px;
            margin-bottom: 20px;
        }

        .empty-state h3 {
            font-size: 22px;
            font-weight: 600;
            margin-bottom: 10px;
            color: var(--primary);
        }

        .empty-state p {
            color: var(--text-light);
            font-size: 16px;
        }

        /* ===== Loading ===== */
        #loading {
            position: fixed;
            top: 0; left: 0;
            width: 100%; height: 100%;
            background: rgba(255,255,255,0.85);
            backdrop-filter: blur(6px);
            display: none;
            justify-content: center;
            align-items: center;
            z-index: 2000;
            font-weight: 600;
            font-size: 16px;
            color: var(--text);
        }

        /* ===== Responsive ===== */
        @media (max-width: 1024px) {
            .posts-grid {
                grid-template-columns: repeat(2, 1fr);
            }
        }

        @media (max-width: 768px) {
            .desktop-only { display: none !important; }
            .mobile-menu-btn { display: block; }
            .nav-content { padding: 0 20px; }

            .blog-wrapper { padding: 100px 20px 60px; }
            .blog-header h1 { font-size: 34px; }
            .blog-header p { font-size: 16px; }

            .posts-grid {
                grid-template-columns: 1fr;
                gap: 20px;
            }

            .article-view { padding: 100px 20px 60px; }
            .article-title { font-size: 30px; }
            .article-content { font-size: 16px; }
            .article-content h2 { font-size: 22px; }
            .article-content h3 { font-size: 19px; }
        }

        @media (max-width: 480px) {
            .card-body { padding: 18px 18px 22px; }
            .card-title { font-size: 18px; }
        }

        /* ===== WhatsApp Float ===== */
        .whatsapp-float {
            position: fixed;
            bottom: 30px; right: 30px;
            background-color: #25D366;
            border-radius: 50%;
            width: 62px; height: 62px;
            display: flex;
            align-items: center;
            justify-content: center;
            box-shadow: 0 4px 18px rgba(37,211,102,0.45);
            z-index: 9999;
            transition: transform 0.25s ease, box-shadow 0.25s ease;
            text-decoration: none;
            animation: wa-pulse 2.5s infinite;
        }

        .whatsapp-float:hover {
            transform: scale(1.12);
            box-shadow: 0 6px 24px rgba(37,211,102,0.65);
            animation: none;
        }

        @keyframes wa-pulse {
            0%, 100% { box-shadow: 0 4px 18px rgba(37,211,102,0.45); }
            50% { box-shadow: 0 4px 28px rgba(37,211,102,0.75); }
        }
    </style>
</head>

<body>

    <!-- ===== Navigation ===== -->
    <nav id="navbar">
        <div class="nav-content">
            <div class="logo">
                <a href="index.html" style="display: block; line-height: 0; text-decoration: none;">
                    <img src="ITW_Logo.webp" alt="InmovillaToWordPress"
                        style="height: 65px; width: auto; cursor: pointer;">
                </a>
            </div>

            <!-- Desktop Menu -->
            <div class="nav-links desktop-only">
                <a href="funcionalidades.html">Funcionalidades</a>
                <a href="blog.php">Blog</a>
                <a href="precios.html">Precios</a>
                <a href="comprar.html" class="cta-button" style="color: white !important;">Comprar Plugin</a>
            </div>

            <!-- Mobile Menu Button -->
            <button class="mobile-menu-btn" id="mobileMenuBtn" aria-label="Menú">
                <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"
                    stroke-linecap="round">
                    <line x1="3" y1="12" x2="21" y2="12"></line>
                    <line x1="3" y1="6" x2="21" y2="6"></line>
                    <line x1="3" y1="18" x2="21" y2="18"></line>
                </svg>
            </button>
        </div>

        <!-- Mobile Menu Overlay -->
        <div class="mobile-menu" id="mobileMenu">
            <div class="mobile-menu-header">
                <img src="ITW_Logo.webp" alt="InmovillaToWordPress" style="height: 45px;">
                <button class="mobile-menu-close" id="mobileMenuClose" aria-label="Cerrar">
                    <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"
                        stroke-linecap="round">
                        <line x1="18" y1="6" x2="6" y2="18"></line>
                        <line x1="6" y1="6" x2="18" y2="18"></line>
                    </svg>
                </button>
            </div>
            <div class="mobile-menu-links">
                <a href="index.html">Inicio</a>
                <a href="funcionalidades.html">Funcionalidades</a>
                <a href="blog.php">Blog</a>
                <a href="precios.html">Precios</a>
                <a href="comprar.html" class="mobile-cta">Comprar Plugin</a>
                <a href="https://wa.me/34711246658?text=Hola%2C%20quiero%20información%20sobre%20InmovillaToWordPress"
                    target="_blank" class="mobile-whatsapp"
                    style="background: #25D366; color: white; margin: 20px 0; padding: 16px; border-radius: 10px; text-align: center; font-weight: 600; text-decoration: none; display: flex; align-items: center; justify-content: center; gap: 10px;">
                    <svg width="24" height="24" viewBox="0 0 24 24" fill="white">
                        <path
                            d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 01-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 01-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 012.893 6.994c-.003 5.45-4.437 9.884-9.885 9.884m8.413-18.297A11.815 11.815 0 0012.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.882 11.882 0 005.683 1.448h.005c6.554 0 11.89-5.335 11.893-11.893a11.821 11.821 0 00-3.48-8.413Z" />
                    </svg>
                    WhatsApp
                </a>
            </div>
        </div>
    </nav>

    <!-- ===== Loading Overlay ===== -->
    <div id="loading">Buscando nuevos correos...</div>

    <!-- ===== Grid View ===== -->
    <div class="blog-wrapper" id="blogGrid">
        <div class="blog-header">
            <h1>Blog</h1>
            <p>Guías, novedades y consejos sobre sincronización Inmovilla + WordPress</p>
            <button onclick="checkForEmails()" class="refresh-btn">
                <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round">
                    <polyline points="23 4 23 10 17 10"></polyline>
                    <path d="M20.49 15a9 9 0 1 1-2.12-9.36L23 10"></path>
                </svg>
                Buscar nuevos posts
            </button>
        </div>

        <?php if (empty($posts)): ?>
            <div class="empty-state">
                <div class="empty-state-icon">📝</div>
                <h3>Aún no hay publicaciones</h3>
                <p>Próximamente publicaremos novedades y guías aquí.</p>
            </div>
        <?php else: ?>
            <div class="posts-grid">
                <?php foreach ($posts as $idx => $post):
                    $thumb = extractFirstImage($post['content']);
                    $excerpt = generateExcerpt($post['content']);
                    $reading = readingTime($post['content']);
                ?>
                    <article class="card" onclick="openArticle(<?php echo $idx; ?>)">
                        <div class="card-thumb">
                            <?php if ($thumb): ?>
                                <img src="<?php echo htmlspecialchars($thumb); ?>" alt="<?php echo htmlspecialchars($post['title']); ?>" loading="lazy">
                            <?php else: ?>
                                <div class="card-thumb-placeholder">📄</div>
                            <?php endif; ?>
                        </div>
                        <div class="card-body">
                            <div class="card-meta">
                                <span class="card-date"><?php echo date('d M Y', strtotime($post['date'])); ?></span>
                                <span class="card-meta-dot"></span>
                                <span class="card-reading"><?php echo $reading; ?></span>
                            </div>
                            <h2 class="card-title"><?php echo htmlspecialchars($post['title']); ?></h2>
                            <p class="card-excerpt"><?php echo htmlspecialchars($excerpt); ?></p>
                            <span class="card-read-more">
                                Leer artículo
                                <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round">
                                    <line x1="5" y1="12" x2="19" y2="12"></line>
                                    <polyline points="12 5 19 12 12 19"></polyline>
                                </svg>
                            </span>
                        </div>
                    </article>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>
    </div>

    <!-- ===== Article Detail View ===== -->
    <div class="article-view" id="articleView">
        <button class="article-back" onclick="closeArticle()">
            <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round">
                <line x1="19" y1="12" x2="5" y2="12"></line>
                <polyline points="12 19 5 12 12 5"></polyline>
            </svg>
            Volver al blog
        </button>
        <div class="article-meta">
            <span class="card-date" id="articleDate"></span>
            <span class="card-meta-dot"></span>
            <span class="card-reading" id="articleReading"></span>
        </div>
        <h1 class="article-title" id="articleTitle"></h1>
        <div class="article-content" id="articleContent"></div>
    </div>

    <!-- ===== WhatsApp Float Button ===== -->
    <a href="https://wa.me/34711246658?text=Hola%2C%20quiero%20información%20sobre%20InmovillaToWordPress"
        class="whatsapp-float" target="_blank" rel="noopener" aria-label="Contactar por WhatsApp">
        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="white" width="30" height="30">
            <path
                d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 01-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 01-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 012.893 6.994c-.003 5.45-4.437 9.884-9.885 9.884m8.413-18.297A11.815 11.815 0 0012.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.882 11.882 0 005.683 1.448h.005c6.554 0 11.89-5.335 11.893-11.893a11.821 11.821 0 00-3.48-8.413z" />
        </svg>
    </a>

    <script>
        // ===== Posts data from PHP =====
        var postsData = <?php echo json_encode($posts, JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT); ?>;

        // ===== Article View =====
        function openArticle(idx) {
            var post = postsData[idx];
            if (!post) return;

            document.getElementById('articleDate').textContent = formatDate(post.date);
            document.getElementById('articleReading').textContent = readingTime(post.content);
            document.getElementById('articleTitle').textContent = post.title;
            document.getElementById('articleContent').innerHTML = post.content;

            document.getElementById('blogGrid').style.display = 'none';
            var articleView = document.getElementById('articleView');
            articleView.classList.add('active');

            window.scrollTo({ top: 0, behavior: 'smooth' });

            // Update URL without reload
            history.pushState({ article: idx }, post.title, '?post=' + idx);
        }

        function closeArticle() {
            document.getElementById('articleView').classList.remove('active');
            document.getElementById('blogGrid').style.display = 'block';

            window.scrollTo({ top: 0, behavior: 'smooth' });
            history.pushState({}, 'Blog', 'blog.php');
        }

        // Handle browser back button
        window.addEventListener('popstate', function(e) {
            if (e.state && typeof e.state.article !== 'undefined') {
                openArticle(e.state.article);
            } else {
                document.getElementById('articleView').classList.remove('active');
                document.getElementById('blogGrid').style.display = 'block';
            }
        });

        // Open article if URL has ?post=N on load
        (function() {
            var params = new URLSearchParams(window.location.search);
            var postIdx = params.get('post');
            if (postIdx !== null && postsData[parseInt(postIdx)]) {
                openArticle(parseInt(postIdx));
            }
        })();

        // ===== Helpers =====
        function formatDate(dateStr) {
            var months = ['Ene','Feb','Mar','Abr','May','Jun','Jul','Ago','Sep','Oct','Nov','Dic'];
            var d = new Date(dateStr + 'T00:00:00');
            return d.getDate().toString().padStart(2, '0') + ' ' + months[d.getMonth()] + ' ' + d.getFullYear();
        }

        function readingTime(html) {
            var tmp = document.createElement('div');
            tmp.innerHTML = html;
            var text = tmp.textContent || tmp.innerText || '';
            var words = text.trim().split(/\s+/).length;
            var mins = Math.max(1, Math.ceil(words / 200));
            return mins + ' min de lectura';
        }

        // ===== Mobile Menu =====
        var mobileMenuBtn = document.getElementById('mobileMenuBtn');
        var mobileMenuClose = document.getElementById('mobileMenuClose');
        var mobileMenu = document.getElementById('mobileMenu');

        if (mobileMenuBtn) {
            mobileMenuBtn.addEventListener('click', function() {
                mobileMenu.classList.add('active');
                document.body.style.overflow = 'hidden';
            });
        }
        if (mobileMenuClose) {
            mobileMenuClose.addEventListener('click', function() {
                mobileMenu.classList.remove('active');
                document.body.style.overflow = '';
            });
        }

        document.querySelectorAll('.mobile-menu-links a').forEach(function(link) {
            link.addEventListener('click', function() {
                mobileMenu.classList.remove('active');
                document.body.style.overflow = '';
            });
        });

        // ===== Nav Scroll Effect =====
        window.addEventListener('scroll', function() {
            var nav = document.getElementById('navbar');
            if (nav) {
                nav.classList.toggle('scrolled', window.scrollY > 20);
            }
        });

        // ===== Check Emails =====
        async function checkForEmails() {
            var btn = document.querySelector('.refresh-btn');
            var loading = document.getElementById('loading');

            btn.disabled = true;
            loading.style.display = 'flex';

            try {
                var response = await fetch('fetch_emails.php');
                var data = await response.json();

                if (data.success) {
                    if (data.message.includes('No hay nuevos')) {
                        alert('No se encontraron nuevos emails con el prefijo BLOG:');
                    } else {
                        alert(data.message);
                        location.reload();
                    }
                } else {
                    alert('Error: ' + data.message);
                }
            } catch (e) {
                alert('Error de conexión o servidor.');
                console.error(e);
            } finally {
                btn.disabled = false;
                loading.style.display = 'none';
            }
        }
    </script>

</body>

</html>
