import { posts } from './post.js'

// ── Helpers ─────────────────────────────────────────────────────────────
const categoryColor = {
  homelab:       '#c8ff00',   // accent lime
  personal:      '#ff6b35',   // orange
  professional:  '#5b9cf6',   // blue
  entertainment: '#b47cff',   // purple
}

function formatDate(iso) {
  return new Date(iso).toLocaleDateString('en-US', {
    year: 'numeric', month: 'short', day: 'numeric',
  })
}

// ── Post card (list view) ────────────────────────────────────────────────
function renderPostCard(post, index) {
  const color = categoryColor[post.category] ?? '#c8ff00'
  return `
    <article class="blog-card reveal" data-post-id="${post.id}" style="transition-delay:${index * 0.08}s">
      <div class="blog-card-meta">
        <span class="blog-cat mono" style="color:${color}">● ${post.category}</span>
        <span class="blog-date mono">${formatDate(post.date)}</span>
      </div>
      <h3 class="blog-card-title">${post.title}</h3>
      <p class="blog-card-excerpt">${post.excerpt}</p>
      <button class="blog-read-btn mono" data-post-id="${post.id}">read →</button>
    </article>
  `
}

// ── Full post (detail view) ──────────────────────────────────────────────
function renderPostDetail(post) {
  const color = categoryColor[post.category] ?? '#c8ff00'
  return `
    <div class="blog-detail" id="blog-detail">
      <button class="blog-back mono" id="blog-back">← back to posts</button>
      <div class="blog-detail-meta">
        <span class="blog-cat mono" style="color:${color}">● ${post.category}</span>
        <span class="blog-date mono">${formatDate(post.date)}</span>
      </div>
      <h2 class="blog-detail-title">${post.title}</h2>
      <div class="blog-detail-body">
        ${post.content}
      </div>
    </div>
  `
}

// ── Section shell ────────────────────────────────────────────────────────
export function renderBlog() {
  // Sort newest first
  const sorted = [...posts].sort((a, b) => new Date(b.date) - new Date(a.date))

  return `
    <section class="blog" id="blog">
      <div class="container">
        <div class="section-head reveal">
          <div class="accent-line"></div>
          <h2 class="section-title">Blog</h2>
          <p class="blog-intro">
            Notes on homelab builds, things I'm working on, and whatever I'm into.
          </p>
        </div>

        <!-- Category filter -->
        <div class="blog-filters reveal">
          <button class="filter-btn mono active" data-filter="all">all</button>
          <button class="filter-btn mono" data-filter="homelab">homelab</button>
          <button class="filter-btn mono" data-filter="personal">personal</button>
          <button class="filter-btn mono" data-filter="professional">professional</button>
          <button class="filter-btn mono" data-filter="entertainment">entertainment</button>
        </div>

        <!-- Post list -->
        <div class="blog-list" id="blog-list">
          ${sorted.map((p, i) => renderPostCard(p, i)).join('')}
        </div>

        <!-- Post detail (hidden by default) -->
        <div class="blog-detail-wrapper" id="blog-detail-wrapper" style="display:none"></div>
      </div>
    </section>

    <style>
      /* ── Section layout ── */
      .blog { padding: 100px 0; border-top: 1px solid var(--border); }
      .blog-intro {
        font-size: 0.95rem;
        color: var(--muted);
        margin-top: 8px;
        max-width: 480px;
      }

      /* ── Filters ── */
      .blog-filters {
        display: flex;
        flex-wrap: wrap;
        gap: 8px;
        margin: 32px 0 40px;
      }
      .filter-btn {
        background: transparent;
        border: 1px solid var(--border);
        color: var(--muted);
        font-size: 0.7rem;
        padding: 4px 14px;
        border-radius: 2px;
        cursor: pointer;
        letter-spacing: 0.05em;
        transition: all 0.18s;
      }
      .filter-btn:hover,
      .filter-btn.active {
        border-color: var(--accent);
        color: var(--accent);
      }

      /* ── Post list ── */
      .blog-list {
        display: grid;
        grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
        gap: 1px;
        background: var(--border);
        border: 1px solid var(--border);
      }

      /* ── Card ── */
      .blog-card {
        background: var(--bg-card);
        padding: 28px 32px;
        display: flex;
        flex-direction: column;
        gap: 10px;
        transition: background 0.18s;
        cursor: default;
      }
      .blog-card:hover { background: #161616; }
      .blog-card[style*="display: none"] { display: none !important; }

      .blog-card-meta {
        display: flex;
        justify-content: space-between;
        align-items: center;
      }
      .blog-cat  { font-size: 0.68rem; letter-spacing: 0.06em; }
      .blog-date { font-size: 0.68rem; color: var(--muted); }

      .blog-card-title {
        font-size: 1.15rem;
        font-weight: 800;
        letter-spacing: -0.02em;
        line-height: 1.25;
      }
      .blog-card-excerpt {
        font-size: 0.88rem;
        color: var(--muted);
        line-height: 1.65;
        flex: 1;
      }
      .blog-read-btn {
        background: transparent;
        border: none;
        color: var(--accent);
        font-size: 0.78rem;
        padding: 0;
        cursor: pointer;
        letter-spacing: 0.04em;
        align-self: flex-start;
        transition: letter-spacing 0.2s;
      }
      .blog-read-btn:hover { letter-spacing: 0.1em; }

      /* ── Detail view ── */
      .blog-detail {
        max-width: 720px;
        padding: 0 0 48px;
        animation: fadeUp 0.4s ease both;
      }
      .blog-back {
        background: transparent;
        border: 1px solid var(--border);
        color: var(--muted);
        font-size: 0.75rem;
        padding: 6px 16px;
        cursor: pointer;
        border-radius: 2px;
        margin-bottom: 32px;
        letter-spacing: 0.04em;
        transition: all 0.18s;
      }
      .blog-back:hover { border-color: var(--accent); color: var(--accent); }

      .blog-detail-meta {
        display: flex;
        gap: 16px;
        margin-bottom: 12px;
      }
      .blog-detail-title {
        font-size: clamp(1.8rem, 4vw, 2.8rem);
        letter-spacing: -0.03em;
        line-height: 1.1;
        margin-bottom: 40px;
      }

      /* Post body typography */
      .blog-detail-body { font-size: 1rem; line-height: 1.8; color: var(--text); }
      .blog-detail-body p  { margin-bottom: 20px; }
      .blog-detail-body h4 {
        font-size: 1rem;
        font-weight: 700;
        color: var(--accent);
        font-family: var(--font-mono);
        letter-spacing: 0.04em;
        margin: 28px 0 10px;
      }
      .blog-detail-body ul {
        padding-left: 20px;
        margin-bottom: 20px;
        color: var(--muted);
      }
      .blog-detail-body li  { margin-bottom: 6px; }
      .blog-detail-body code {
        background: #1a1a1a;
        border: 1px solid var(--border);
        padding: 1px 6px;
        border-radius: 2px;
        font-family: var(--font-mono);
        font-size: 0.85em;
        color: var(--accent);
      }
      .blog-detail-body strong { color: var(--text); font-weight: 700; }
    </style>
  `
}

// ── Wire up interactivity (call after DOM insertion) ─────────────────────
export function initBlog() {
  const listEl   = document.getElementById('blog-list')
  const detailEl = document.getElementById('blog-detail-wrapper')

  // ── Filter buttons ──
  document.querySelectorAll('.filter-btn').forEach(btn => {
    btn.addEventListener('click', () => {
      document.querySelectorAll('.filter-btn').forEach(b => b.classList.remove('active'))
      btn.classList.add('active')

      const filter = btn.dataset.filter
      document.querySelectorAll('.blog-card').forEach(card => {
        const match = filter === 'all' || card.dataset.postId &&
          posts.find(p => p.id === card.dataset.postId)?.category === filter
        card.style.display = match ? '' : 'none'
      })
    })
  })

  // ── Open post ──
  document.querySelectorAll('.blog-read-btn').forEach(btn => {
    btn.addEventListener('click', () => {
      const post = posts.find(p => p.id === btn.dataset.postId)
      if (!post) return
      listEl.style.display = 'none'
      document.querySelector('.blog-filters').style.display = 'none'
      detailEl.style.display = 'block'
      detailEl.innerHTML = renderPostDetail(post)
      detailEl.scrollIntoView({ behavior: 'smooth', block: 'start' })

      // Back button
      document.getElementById('blog-back').addEventListener('click', () => {
        detailEl.style.display = 'none'
        listEl.style.display = ''
        document.querySelector('.blog-filters').style.display = ''
      })
    })
  })
}