// ─── Blog section (LP埋め込み & REST API取得) ─────────────────────

function BlogSection() {
  const [posts, setPosts] = React.useState([]);
  const [categories, setCategories] = React.useState([]);
  const [filter, setFilter] = React.useState(0); // 0 = all
  const [loading, setLoading] = React.useState(true);
  const [error, setError] = React.useState(false);

  React.useEffect(() => {
    const base = "/wp-json/wp/v2";
    Promise.all([
      fetch(`${base}/posts?per_page=8&orderby=date&order=desc&_embed=true`).then(r => r.json()),
      fetch(`${base}/categories?hide_empty=true&per_page=100&orderby=count&order=desc`).then(r => r.json()),
    ])
      .then(([p, c]) => {
        setPosts(Array.isArray(p) ? p : []);
        setCategories(Array.isArray(c) ? c.filter(cat => cat.slug !== "uncategorized") : []);
        setLoading(false);
      })
      .catch(() => { setError(true); setLoading(false); });
  }, []);

  const filtered = filter === 0 ? posts : posts.filter(p =>
    p.categories && p.categories.includes(filter)
  );

  return (
    <section className="section blog-section" style={{ background: "var(--bg-alt)" }}>
      <div className="wrap">
        <div className="blog-section__head">
          <SectionHeader
            eyebrowNum="08"
            eyebrow="BLOG"
            title="最新の記事"
            lead="WordPressやWeb制作・SEOに関する知識・事例を発信しています。"
          />
          {categories.length > 0 && (
            <div className="blog-filter-bar">
              <button
                onClick={() => setFilter(0)}
                className={`blog-filter-btn ${filter === 0 ? "blog-filter-btn--active" : "blog-filter-btn--inactive"}`}
              >すべて</button>
              {categories.map(cat => (
                <button
                  key={cat.id}
                  onClick={() => setFilter(cat.id)}
                  className={`blog-filter-btn ${filter === cat.id ? "blog-filter-btn--active" : "blog-filter-btn--inactive"}`}
                >{cat.name}</button>
              ))}
            </div>
          )}
        </div>

        {loading && (
          <div className="blog-loading">
            <span className="en blog-loading__text">LOADING...</span>
          </div>
        )}

        {error && (
          <div className="blog-error">記事の取得に失敗しました。</div>
        )}

        {!loading && !error && filtered.length === 0 && (
          <div className="blog-empty">該当する記事がありません。</div>
        )}

        {!loading && !error && filtered.length > 0 && (
          <div className="blog-grid">
            {filtered.map((post, i) => (
              <BlogCard key={post.id} post={post} index={i} />
            ))}
          </div>
        )}

        <div className="blog-section__footer">
          <a href="/blog" className="btn btn-ghost">
            すべての記事を見る <Arrow />
          </a>
        </div>
      </div>
    </section>
  );
}

function BlogCard({ post, index }) {
  const thumb = post._embedded?.["wp:featuredmedia"]?.[0]?.source_url;
  const cat = post._embedded?.["wp:term"]?.[0]?.[0];
  const dateStr = new Date(post.date).toLocaleDateString("ja-JP", {
    year: "numeric", month: "long", day: "numeric"
  });
  const rawExcerpt = post.excerpt?.rendered?.replace(/<[^>]+>/g, "").replace(/\s+/g, " ").trim();
  const excerpt = rawExcerpt && rawExcerpt.length > 72 ? rawExcerpt.slice(0, 72) + "…" : rawExcerpt;
  const hue = (post.id * 47 + index * 19) % 360;

  return (
    <article className="blog-card" onClick={() => { window.location.href = post.link; }}>
      <div className="blog-card__thumb">
        {thumb
          ? <img src={thumb} alt={post.title?.rendered?.replace(/<[^>]+>/g, "") || ""} className="blog-card__thumb-img" loading="lazy" />
          : <div className="blog-card__thumb-placeholder" style={{ background: `linear-gradient(135deg, oklch(0.92 0.06 ${hue}), oklch(0.82 0.1 ${hue}))` }} />
        }
        {cat && <span className="blog-card__cat-badge chip chip-accent">{cat.name}</span>}
      </div>
      <div className="blog-card__body">
        <div className="en blog-card__date">{dateStr}</div>
        <h3 className="serif blog-card__title"
          dangerouslySetInnerHTML={{ __html: post.title?.rendered || "" }}
        />
        {excerpt && <p className="blog-card__excerpt">{excerpt}</p>}
      </div>
    </article>
  );
}

// ── Blog archive page ───────────────────────────────────────────
const BLOG_PER_PAGE = 12;

function BlogPage({ go }) {
  const [posts, setPosts]           = React.useState([]);
  const [categories, setCategories] = React.useState([]);
  const [filter, setFilter]         = React.useState(0);
  const [page, setPage]             = React.useState(1);
  const [totalPages, setTotalPages] = React.useState(1);
  const [loading, setLoading]       = React.useState(true);
  const [error, setError]           = React.useState(false);

  React.useEffect(() => {
    fetch("/wp-json/wp/v2/categories?hide_empty=true&per_page=100&orderby=count&order=desc")
      .then(r => r.json())
      .then(c => setCategories(Array.isArray(c) ? c.filter(cat => cat.slug !== "uncategorized") : []))
      .catch(() => {});
  }, []);

  React.useEffect(() => {
    setLoading(true);
    setError(false);
    const catParam = filter !== 0 ? `&categories=${filter}` : "";
    fetch(`/wp-json/wp/v2/posts?per_page=${BLOG_PER_PAGE}&page=${page}&orderby=date&order=desc&_embed=true${catParam}`)
      .then(r => {
        setTotalPages(parseInt(r.headers.get("X-WP-TotalPages") || "1", 10));
        return r.json();
      })
      .then(p => { setPosts(Array.isArray(p) ? p : []); setLoading(false); })
      .catch(() => { setError(true); setLoading(false); });
  }, [filter, page]);

  const changeFilter = (catId) => { setFilter(catId); setPage(1); };
  const changePage   = (p)     => { setPage(p); window.scrollTo({ top: 0, behavior: "smooth" }); };

  return (
    <div className="page">
      <PageHeader
        eyebrow="BLOG"
        num="→"
        title={<>Web制作・<span style={{ color: "var(--accent-strong)" }}>保守の知識</span>。</>}
        lead="WordPress保守・セキュリティ・SEO対策・Web制作に関する知識・事例を発信しています。"
      />

      <section className="section" style={{ paddingTop: 40 }}>
        <div className="wrap">
          {categories.length > 0 && (
            <div className="blog-filter-bar" style={{ marginBottom: 40 }}>
              <button onClick={() => changeFilter(0)}
                className={`blog-filter-btn ${filter === 0 ? "blog-filter-btn--active" : "blog-filter-btn--inactive"}`}>
                すべて
              </button>
              {categories.map(cat => (
                <button key={cat.id} onClick={() => changeFilter(cat.id)}
                  className={`blog-filter-btn ${filter === cat.id ? "blog-filter-btn--active" : "blog-filter-btn--inactive"}`}>
                  {cat.name}
                </button>
              ))}
            </div>
          )}

          {loading && <div className="blog-loading"><span className="en blog-loading__text">LOADING...</span></div>}
          {error   && <div className="blog-error">記事の取得に失敗しました。</div>}
          {!loading && !error && posts.length === 0 && <div className="blog-empty">該当する記事がありません。</div>}

          {!loading && !error && posts.length > 0 && (
            <div className="blog-grid">
              {posts.map((post, i) => <BlogCard key={post.id} post={post} index={i} />)}
            </div>
          )}

          {totalPages > 1 && (
            <div className="blog-pagination">
              {page > 1 && (
                <button onClick={() => changePage(page - 1)} className="blog-page-btn blog-page-btn--nav">
                  ← 前へ
                </button>
              )}
              {Array.from({ length: totalPages }, (_, i) => i + 1).map(p => (
                <button key={p} onClick={() => changePage(p)}
                  className={`blog-page-btn ${p === page ? "blog-page-btn--active" : "blog-page-btn--inactive"}`}>
                  {p}
                </button>
              ))}
              {page < totalPages && (
                <button onClick={() => changePage(page + 1)} className="blog-page-btn blog-page-btn--nav">
                  次へ →
                </button>
              )}
            </div>
          )}
        </div>
      </section>
    </div>
  );
}

Object.assign(window, { BlogSection, BlogCard, BlogPage });
