(function () {
  async function loadPosts() {
    // Prefer global POSTS array when available (edit scripts/posts-data.js)
    if (window.POSTS && Array.isArray(window.POSTS)) {
      return window.POSTS;
    }
    try {
      const res = await fetch('posts.json');
      if (!res.ok) throw new Error('posts.json fetch failed');
      const data = await res.json();
      return data.posts || [];
    } catch (err) {
      console.error('Error loading posts.json', err);
      return [];
    }
  }

  function renderIndex(posts) {
    const container = document.querySelector('.posts-main-grid');
    if (!container) return;
    container.innerHTML = '';

    const MAX_HOME = 6;
    const homePosts = posts.slice(0, MAX_HOME);

    homePosts.slice(0, 2).forEach(p => {
      const article = document.createElement('article');
      article.className = 'post-card large-card';
      article.innerHTML = `
        <div class="post-img"><img src="${p.image}" alt="${escapeHtml(p.title)}"></div>
        <div class="post-info">
          <span class="post-meta">${escapeHtml(p.date)} • ${escapeHtml(p.category)}</span>
          <h3><a href="blogID.html" data-slug="${encodeURIComponent(p.slug)}">${escapeHtml(p.title)}</a></h3>
          <p>${escapeHtml(p.excerpt)}</p>
        </div>
      `;
      // attach click to store selected slug for client-side rendering
      const a = article.querySelector('a');
      if (a) a.addEventListener('click', () => sessionStorage.setItem('selectedPostSlug', p.slug));
      container.appendChild(article);
    });

    const side = document.createElement('div');
    side.className = 'side-feed';
    homePosts.slice(2).forEach(p => {
      const item = document.createElement('div');
      item.className = 'side-item';
      item.innerHTML = `
        <div class="side-img"><img src="${p.image}" alt="${escapeHtml(p.title)}"></div>
        <div class="side-info">
          <span class="post-meta">${escapeHtml(p.date)} • ${escapeHtml(p.category)}</span>
          <h4><a href="blogID.html" data-slug="${encodeURIComponent(p.slug)}">${escapeHtml(p.title)}</a></h4>
        </div>
      `;
      const a = item.querySelector('a');
      if (a) a.addEventListener('click', () => sessionStorage.setItem('selectedPostSlug', p.slug));
      side.appendChild(item);
    });
    container.appendChild(side);
  }

  function renderBlogList(posts) {
    const grid = document.querySelector('.post-grid');
    if (!grid) return;
    grid.innerHTML = '';
    posts.forEach(p => {
      const article = document.createElement('article');
      article.className = 'post-card';
      article.innerHTML = `
        <img src="${p.image}" class="post-img" alt="${escapeHtml(p.title)}">
        <div class="post-category">${escapeHtml(p.category)}</div>
        <h3 class="post-title"><a href="blogID.html" data-slug="${encodeURIComponent(p.slug)}">${escapeHtml(p.title)}</a></h3>
        <p class="post-excerpt">${escapeHtml(p.excerpt)}</p>
      `;
      const a = article.querySelector('a');
      if (a) a.addEventListener('click', () => sessionStorage.setItem('selectedPostSlug', p.slug));
      grid.appendChild(article);
    });
  }

  function getQueryParam(name) {
    const params = new URLSearchParams(window.location.search);
    return params.get(name);
  }

  function renderSinglePost(posts) {
    // prefer slug passed via sessionStorage on click; fall back to ?id param
    const id = sessionStorage.getItem('selectedPostSlug') || getQueryParam('id');
    if (!id) return;
    const post = posts.find(p => p.slug === id || p.id === id);
    if (!post) {
      const wrapper = document.querySelector('.content-wrapper') || document.body;
      wrapper.innerHTML = '<p>Post not found.</p>';
      return;
    }

    const wrapper = document.querySelector('.content-wrapper') || document.body;
    wrapper.innerHTML = `
      <div class="back-nav"><a href="blog.html" class="btn-back">  <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" 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>Back to Blog</a></div>
      <article>
        <header class="post-header">
          <span class="category-tag">${escapeHtml(post.category)}</span>
          <h1>${escapeHtml(post.title)}</h1>
          <div class="post-meta"><div class="meta-text"><span class="post-date">${escapeHtml(post.date)}</span></div></div>
        </header>
        <img src="${post.image}" alt="${escapeHtml(post.title)}" class="main-image">
        <div class="article-body">${post.content}</div>

        <footer class="footer-cta">
          <p style="color: var(--text-muted); margin-bottom: 20px;">Enjoyed this article? Share it with your team.</p>
          <div style="display: flex; justify-content: center; gap: 15px;">
            <div style="width: 40px; height: 40px; border-radius: 50%; border: 1px solid var(--border-color); display: flex; align-items: center; justify-content: center; cursor: pointer;">𝕏</div>
            <div style="width: 40px; height: 40px; border-radius: 50%; border: 1px solid var(--border-color); display: flex; align-items: center; justify-content: center; cursor: pointer;">in</div>
          </div>
        </footer>

      </article>
    `;
    // clear sessionStorage so subsequent loads don't reuse stale selection
    sessionStorage.removeItem('selectedPostSlug');
  }

  function escapeHtml(str) {
    if (!str) return '';
    return String(str)
      .replace(/&/g, '&amp;')
      .replace(/</g, '&lt;')
      .replace(/>/g, '&gt;')
      .replace(/"/g, '&quot;')
      .replace(/'/g, '&#39;');
  }

  document.addEventListener('DOMContentLoaded', async () => {
    const posts = await loadPosts();
    if (document.querySelector('.posts-main-grid')) renderIndex(posts);
    if (document.querySelector('.post-grid')) renderBlogList(posts);
    if (document.querySelector('.content-wrapper')) renderSinglePost(posts);
  });

})();
