/* Section 8 — Blog (WordPress REST API 連動) */

const FALLBACK_POSTS = [
  { cat: '助成金',       ttl: '【2026年度版】中小企業が使いたい助成金ベスト10', date: '2026.04.12', link:'https://roumunews.jp/blog/' },
  { cat: '法改正',       ttl: '2026年10月施行 社会保険適用拡大への実務対応',     date: '2026.04.05', link:'https://roumunews.jp/blog/' },
  { cat: '労務トラブル', ttl: '退職代行サービス経由の退職 ― 押さえるべき3点',    date: '2026.03.28', link:'https://roumunews.jp/blog/' }
];

const Blog = () => {
  const [posts, setPosts] = React.useState(null);

  React.useEffect(() => {
    let aborted = false;
    fetch('https://roumunews.jp/wp-json/wp/v2/posts?per_page=3&_embed', { mode: 'cors' })
      .then(r => { if (!r.ok) throw new Error('http ' + r.status); return r.json(); })
      .then(data => {
        if (aborted || !Array.isArray(data) || !data.length) return;
        const mapped = data.map(p => {
          const media = p._embedded && p._embedded['wp:featuredmedia'] && p._embedded['wp:featuredmedia'][0];
          const thumb = (media && (media.media_details?.sizes?.medium_large?.source_url || media.source_url)) || null;
          const cats = (p._embedded && p._embedded['wp:term'] && p._embedded['wp:term'][0] || []).map(t => t.name);
          const d = new Date(p.date);
          const date = `${d.getFullYear()}.${String(d.getMonth()+1).padStart(2,'0')}.${String(d.getDate()).padStart(2,'0')}`;
          return {
            cat: cats[0] || 'お役立ち',
            ttl: (p.title && p.title.rendered) || '',
            date,
            link: p.link,
            thumb
          };
        });
        setPosts(mapped);
      })
      .catch(() => { if (!aborted) setPosts(FALLBACK_POSTS); });
    return () => { aborted = true; };
  }, []);

  const list = posts || FALLBACK_POSTS;
  const isLoading = posts === null;

  return (
    <section className="blog" id="blog" data-screen-label="08 Blog">
      <div className="container">
        <div className="section-head" style={{display:'flex',flexDirection:'row',alignItems:'flex-end',justifyContent:'space-between',flexWrap:'wrap',gap:20}}>
          <div>
            <Eyebrow>JOURNAL</Eyebrow>
            <h2 style={{marginTop:14}}>お役立ち情報</h2>
          </div>
          <a className="btn btn--ghost btn--sm" href="https://roumunews.jp/blog/" target="_blank" rel="noopener">すべての記事を見る <Arrow/></a>
        </div>
        <div className="blog__grid" style={isLoading ? {opacity:.6} : {}}>
          {list.map((p,i) => (
            <a className="blog__card" key={i} href={p.link} target="_blank" rel="noopener">
              <div className="blog__thumb">
                {p.thumb
                  ? <img src={p.thumb} alt="" style={{width:'100%',height:'100%',objectFit:'cover'}} loading="lazy"/>
                  : <Placeholder tag={`記事アイキャッチ ${String(i+1).padStart(3,'0')}`} style={{height:'100%'}}/>}
              </div>
              <div className="blog__body">
                <div className="blog__cat">{p.cat}</div>
                <div className="blog__title" dangerouslySetInnerHTML={{__html: p.ttl}}/>
                <div className="blog__date">{p.date}</div>
              </div>
            </a>
          ))}
        </div>
      </div>
    </section>
  );
};

window.Blog = Blog;
