// ===========================================================
// 現場ハック転職ブログ - 記事データローダー
// posts.json を fetch して window に注入する
// ===========================================================

(function() {
  // posts.json が読み込まれるまでReactの描画を待つ
  window.__postsReady = false;

  fetch('/posts.json')
    .then(r => r.json())
    .then(data => {
      window.ARTICLES   = data.articles   || [];
      window.CATEGORIES = data.categories || [{ name: "すべての記事", count: window.ARTICLES.length }];
      window.POPULAR    = (data.articles || [])
        .slice()
        .sort((a, b) => (b.views || 0) - (a.views || 0))
        .slice(0, 5)
        .map((a, i) => ({ rank: i + 1, title: a.title, views: a.views || 0 }));
      window.TAGS = data.tags || [];
      window.__postsReady = true;
      // カスタムイベントでAppに通知
      document.dispatchEvent(new Event('postsLoaded'));
    })
    .catch(() => {
      // フォールバック（記事なし）
      window.ARTICLES   = [];
      window.CATEGORIES = [{ name: "すべての記事", count: 0 }];
      window.POPULAR    = [];
      window.TAGS       = [];
      window.__postsReady = true;
      document.dispatchEvent(new Event('postsLoaded'));
    });
})();
