<?php
include 'includes/posts.php';

$rawCat      = $_GET['cat'] ?? 'All';
$selectedCat = cat_from_slug($rawCat, $posts);

$categories = ['All'];
foreach ($posts as $p) if (!in_array($p[0], $categories)) $categories[] = $p[0];

$totalCount = ($selectedCat === 'All')
  ? count($posts)
  : count(array_filter($posts, fn($p) => $p[0] === $selectedCat));

// SEO-friendly, category-specific page title
$pageTitle = ($selectedCat === 'All')
  ? "Finance & Investment Blog — SkResultt"
  : htmlspecialchars($selectedCat) . " Articles & Guides — SkResultt";

include 'includes/header.php';
?>

<section class="hero" style="padding:40px 24px;">
  <div class="hero-content">
    <h1><?php echo $selectedCat === 'All' ? 'Finance &amp; Investment Blog' : htmlspecialchars($selectedCat); ?></h1>
    <p><?php echo $selectedCat === 'All'
        ? count($posts) . '+ articles on stocks, mutual funds, crypto, real estate, tax saving &amp; more.'
        : $totalCount . ' articles in ' . htmlspecialchars($selectedCat) . '.'; ?></p>
  </div>
</section>

<section class="section" style="max-width:1560px;">

  <!-- Category Filter (SEO-friendly URLs) -->
  <div style="display:flex;gap:10px;flex-wrap:wrap;justify-content:center;margin-bottom:34px;">
    <?php foreach ($categories as $cat): ?>
      <a href="<?php echo cat_url($cat); ?>"
         class="btn cat-btn"
         style="padding:8px 18px;font-size:13px;<?php echo $selectedCat===$cat ? 'background:linear-gradient(135deg,#6366f1,#ec4899);color:#fff;' : 'background:#fff;color:#0f172a;'; ?>">
        <?php echo htmlspecialchars($cat); ?>
      </a>
    <?php endforeach; ?>
  </div>

  <!-- Three-column layout: left sidebar + articles + right sidebar -->
  <div class="home-layout">

    <!-- ===== LEFT SIDEBAR ===== -->
    <aside class="home-left">
      <!-- Left MGID Sidebar Ad -->
      <div class="side-ad" id="mgidBlogLeftAd"></div>
      <script>
      (function(w,q){
        if (window.innerWidth > 1024 && window.innerWidth <= 1280) return;
        document.getElementById('mgidBlogLeftAd').innerHTML =
          '<div data-type="_mgwidget" data-widget-id="2073723"></div>';
        w[q]=w[q]||[]; w[q].push(["_mgc.load"]);
      })(window,"_mgq");
      </script>

      <!-- Trending Now -->
      <div class="side-box">
        <div class="side-title"><i class="fas fa-bolt" style="color:#f59e0b;"></i> Trending Now</div>
        <?php $blogTrend = $posts; shuffle($blogTrend); foreach (array_slice($blogTrend, 0, 5) as $tp): ?>
          <div class="pop-item">
            <img src="<?php echo $tp[2]; ?>" alt="" loading="lazy">
            <div class="info">
              <div class="cat"><?php echo htmlspecialchars($tp[0]); ?></div>
              <h5><a href="<?php echo post_url($tp); ?>"><?php echo htmlspecialchars($tp[1]); ?></a></h5>
              <time><?php echo date('M d, Y', strtotime($tp[3])); ?></time>
            </div>
          </div>
        <?php endforeach; ?>
      </div>
    </aside>

    <!-- ===== MAIN: article grid ===== -->
    <div class="home-main">
      <div class="blog-grid" id="blogGrid"></div>

      <div id="loader" style="text-align:center;padding:40px 0;">
        <div class="spinner"></div>
        <p style="color:#64748b;margin-top:12px;">Loading more articles...</p>
      </div>

      <div id="endMsg" style="text-align:center;padding:40px 0;display:none;color:#64748b;">
        <i class="fas fa-check-circle" style="font-size:32px;color:#6366f1;"></i>
        <p style="margin-top:12px;">🎉 You've reached the end! No more articles.</p>
      </div>
    </div>

    <!-- ===== RIGHT SIDEBAR ===== -->
    <aside class="home-sidebar">
      <!-- Right MGID Sidebar Ad -->
      <div class="side-ad" id="mgidBlogRightAd"></div>
      <script>
      (function(w,q){
        document.getElementById('mgidBlogRightAd').innerHTML =
          '<div data-type="_mgwidget" data-widget-id="2070373"></div>';
        w[q]=w[q]||[]; w[q].push(["_mgc.load"]);
      })(window,"_mgq");
      </script>

      <!-- Popular Posts -->
      <div class="side-box">
        <div class="side-title"><i class="fas fa-fire" style="color:#ef4444;"></i> Popular Posts</div>
        <?php $blogPopular = $posts; shuffle($blogPopular); foreach (array_slice($blogPopular, 0, 5) as $sp): ?>
          <div class="pop-item">
            <img src="<?php echo $sp[2]; ?>" alt="" loading="lazy">
            <div class="info">
              <div class="cat"><?php echo htmlspecialchars($sp[0]); ?></div>
              <h5><a href="<?php echo post_url($sp); ?>"><?php echo htmlspecialchars($sp[1]); ?></a></h5>
              <time><?php echo date('M d, Y', strtotime($sp[3])); ?></time>
            </div>
          </div>
        <?php endforeach; ?>
      </div>

      <!-- Top Categories -->
      <div class="side-box">
        <div class="side-title"><i class="fas fa-layer-group" style="color:#6366f1;"></i> Top Categories</div>
        <?php
          $sideCats = [];
          foreach ($posts as $p) $sideCats[$p[0]] = ($sideCats[$p[0]] ?? 0) + 1;
          arsort($sideCats);
        ?>
        <div class="side-cats">
          <?php foreach (array_slice($sideCats, 0, 8, true) as $cName=>$cCnt): ?>
            <a href="<?php echo cat_url($cName); ?>">
              <span><?php echo htmlspecialchars($cName); ?></span>
              <b><?php echo $cCnt; ?></b>
            </a>
          <?php endforeach; ?>
        </div>
      </div>
    </aside>

  </div>
</section>

<style>
.spinner{ width:44px;height:44px;border-radius:50%;border:4px solid #e2e8f0;border-top-color:#6366f1;animation:spin .8s linear infinite;margin:0 auto; }
@keyframes spin{ to{ transform:rotate(360deg); } }
.fade-in{ animation:fadeIn .5s ease; }
@keyframes fadeIn{ from{opacity:0;transform:translateY(20px);} to{opacity:1;transform:translateY(0);} }
.blog-grid > .mgid-feed-ad{ grid-column:1 / -1; margin:10px 0; min-height:400px; }

/* ---------- Three-column layout ---------- */
.home-layout{ display:grid; grid-template-columns:280px minmax(0,1fr) 320px; gap:32px; align-items:start; }
.home-left, .home-sidebar{ position:sticky; top:100px; }
.side-ad{ min-height:560px; margin-bottom:24px; }
.side-box{ background:#fff; border-radius:16px; padding:24px; box-shadow:0 8px 25px rgba(0,0,0,.06); margin-bottom:24px; }
.side-title{ font-size:14px; font-weight:700; color:#0f172a; text-transform:uppercase; letter-spacing:1px; margin-bottom:16px; padding-bottom:12px; border-bottom:2px solid #f1f5f9; display:flex; align-items:center; gap:8px; }
.pop-item{ display:flex; gap:12px; align-items:flex-start; padding:12px 0; border-bottom:1px solid #f1f5f9; }
.pop-item:last-child{ border:none; padding-bottom:0; }
.pop-item img{ width:70px; height:70px; border-radius:10px; object-fit:cover; flex-shrink:0; }
.pop-item .info{ flex:1; }
.pop-item .cat{ font-size:11px; color:#6366f1; font-weight:600; text-transform:uppercase; }
.pop-item h5{ font-size:14px; line-height:1.4; margin:4px 0; font-weight:600; }
.pop-item h5 a{ color:#0f172a; }
.pop-item h5 a:hover{ color:#6366f1; }
.pop-item time{ font-size:12px; color:#94a3b8; }
.side-cats a{ display:flex; justify-content:space-between; align-items:center; padding:10px 0; border-bottom:1px solid #f1f5f9; font-size:14px; color:#475569; transition:color .2s; }
.side-cats a:last-child{ border:none; }
.side-cats a:hover{ color:#6366f1; }
.side-cats b{ background:#f1f5f9; color:#6366f1; font-size:11px; font-weight:700; padding:3px 9px; border-radius:20px; }

@media (max-width:1280px){
  .home-layout{ grid-template-columns:minmax(0,1fr) 320px; }
  .home-left{ display:none; }
}
@media (max-width:1024px){
  .home-layout{ display:flex; flex-direction:column; gap:0; }
  .home-main{ order:1; }
  .home-left{ display:block; order:2; position:static; margin-top:30px; }
  .home-sidebar{ order:3; position:static; margin-top:30px; }
  .side-ad{ min-height:0; }
}
</style>

<script>
(function(){
  const grid    = document.getElementById('blogGrid');
  const loader  = document.getElementById('loader');
  const endMsg  = document.getElementById('endMsg');
  const cat     = <?php echo json_encode($selectedCat); ?>;
  let page      = 1;
  let loading   = false;
  let hasMore   = true;
  let adInserted = false;
  const SEED    = Math.floor(Math.random() * 1e9);

  // MGID in-feed Smart widget (once, after first batch)
  function insertFeedAd(before){
    if (adInserted) return; adInserted = true;
    const slot = document.createElement('div');
    slot.className = 'mgid-feed-ad';
    if (before) grid.insertBefore(slot, before); else grid.appendChild(slot);
    let done = false;
    const load = () => { if (done) return; done = true;
      slot.innerHTML = '<div data-type="_mgwidget" data-widget-id="2070010"></div>';
      window._mgq = window._mgq || []; window._mgq.push(['_mgc.load']);
    };
    if ('IntersectionObserver' in window){
      const io = new IntersectionObserver(e => { if (e[0].isIntersecting){ io.disconnect(); load(); } }, { rootMargin:'600px 0px' });
      io.observe(slot);
    } else { load(); }
  }

  async function loadMore(){
    if (loading || !hasMore) return;
    loading = true;
    loader.style.display = 'block';
    try {
      const res  = await fetch(`load_posts.php?cat=${encodeURIComponent(cat)}&page=${page}&seed=${SEED}`);
      const html = await res.text();
      hasMore    = res.headers.get('X-Has-More') === '1';
      if (html.trim()){
        const tmp = document.createElement('div');
        tmp.innerHTML = html;
        const kids = Array.from(tmp.children);
        kids.forEach(el => { el.classList.add('fade-in'); grid.appendChild(el); });
        if (page === 1 && grid.children.length > 8) insertFeedAd(grid.children[8]);
        page++;
      }
      if (!hasMore){ loader.style.display = 'none'; endMsg.style.display = 'block'; }
    } catch(e){
      console.error(e);
      loader.innerHTML = '<p style="color:#ef4444;">Failed to load. <a href="#" onclick="location.reload()">Retry</a></p>';
    } finally {
      loading = false;
      if (hasMore) loader.style.display = 'none';
    }
  }

  const io = new IntersectionObserver(entries => { if (entries[0].isIntersecting) loadMore(); }, { rootMargin: '300px' });
  io.observe(loader);
  loadMore();
})();
</script>

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