/* Aifit — News & SNS section
 * 新着情報/ブログ/コラムを WordPress REST API からブラウザfetchで自動表示
 * ＋ 本日の訃報バンド（外部リンク）＋ Facebook ページプラグイン ＋ Instagram 導線
 */
(function () {
  const { useState, useEffect, useRef } = React;
  const Icon = window.Icon;

  const API = "https://saiki-sousai.com/wp-json/wp/v2/";
  const FEEDS = [
    { key: "news",   base: "news",   label: "新着情報", all: "https://saiki-sousai.com/news/" },
    { key: "blog",   base: "posts",  label: "ブログ",   all: "https://saiki-sousai.com/blog/" },
    { key: "column", base: "column", label: "コラム",   all: "https://saiki-sousai.com/column/" },
  ];
  const FUHO = "https://www.27900.jp/funeral/Top?access_key=455873795032376e434e6733572b6434746668626e6f6378634a533077396574594b53554c2b416b312f6f3d";
  // Behold(無料) で @saiki_group を連携後、発行されたフィードIDをここに入れるだけで自動フィードが有効化される。
  // 空文字の間は Instagram 公式プロフィールへの導線を表示する。
  const BEHOLD_FEED_ID = "EnZkB2RP82JverKyuj6G";

  function decode(html) {
    const t = document.createElement("textarea");
    t.innerHTML = html || "";
    return t.value;
  }
  function fmtDate(d) {
    try {
      const x = new Date(d);
      return x.getFullYear() + "." + String(x.getMonth() + 1).padStart(2, "0") + "." + String(x.getDate()).padStart(2, "0");
    } catch (e) { return ""; }
  }
  // アイキャッチ（the_thumb 相当）→ 本文/抜粋中の最初の画像、の順で取得
  function pickImage(p) {
    const m = p._embedded && p._embedded["wp:featuredmedia"] && p._embedded["wp:featuredmedia"][0];
    if (m && m.source_url) return m.source_url;
    const html = (p.content && p.content.rendered) || (p.excerpt && p.excerpt.rendered) || "";
    const mm = html.match(/<img[^>]+src=["']([^"']+)["']/i);
    return mm ? mm[1] : null;
  }

  function Feed({ base, label, all }) {
    const [posts, setPosts] = useState(null); // null=loading, []=empty/error
    useEffect(() => {
      let alive = true;
      fetch(API + base + "?_embed&per_page=4")
        .then((r) => (r.ok ? r.json() : Promise.reject(r.status)))
        .then((d) => { if (alive) setPosts(Array.isArray(d) ? d : []); })
        .catch(() => { if (alive) setPosts([]); });
      return () => { alive = false; };
    }, [base]);

    return (
      <div className="nfeed reveal">
        <h3 className="nfeed-h">
          <span>{label}</span>
          <a href={all} target="_blank" rel="noopener">一覧を見る<Icon name="arrow" strokeWidth={1.7} /></a>
        </h3>
        <div className="nfeed-list">
          {posts === null && <p className="nfeed-load">読み込み中…</p>}
          {posts && posts.length === 0 && (
            <a className="nfeed-empty" href={all} target="_blank" rel="noopener">{label}の一覧を見る →</a>
          )}
          {posts && posts.map((p, i) => {
            const img = pickImage(p);
            return (
              <a className="ncard" key={i} href={p.link} target="_blank" rel="noopener">
                <span className={"ncard-thumb" + (img ? "" : " is-ph")}>
                  {img ? <img src={img} alt="" loading="lazy" /> : <Icon name="lotus" className="ncard-phic" strokeWidth={1.4} />}
                </span>
                <span className="ncard-body">
                  <time>{fmtDate(p.date)}</time>
                  <span className="ncard-title">{decode(p.title && p.title.rendered)}</span>
                </span>
              </a>
            );
          })}
        </div>
      </div>
    );
  }

  function NewsSnsSection() {
    useEffect(() => {
      // Facebook SDK（1回だけ読み込む）
      if (!document.getElementById("fb-root")) {
        const root = document.createElement("div");
        root.id = "fb-root";
        document.body.appendChild(root);
      }
      if (!document.getElementById("facebook-jssdk")) {
        const s = document.createElement("script");
        s.id = "facebook-jssdk";
        s.async = true; s.defer = true; s.crossOrigin = "anonymous";
        s.src = "https://connect.facebook.net/ja_JP/sdk.js#xfbml=1&version=v19.0";
        document.body.appendChild(s);
      } else if (window.FB && window.FB.XFBML) {
        window.FB.XFBML.parse();
      }
      // Instagram（Behold 無料ウィジェット）— フィードID設定時のみ読み込む
      if (BEHOLD_FEED_ID && !document.getElementById("behold-widget-js")) {
        const b = document.createElement("script");
        b.id = "behold-widget-js"; b.type = "module";
        b.src = "https://w.behold.so/widget.js";
        document.body.appendChild(b);
      }
    }, []);

    return (
      <section className="newsblock" id="news" aria-label="お知らせ・SNS">
        <div className="wrap">
          <div className="nb-head reveal">
            <span className="eyebrow">News &amp; Topics</span>
            <h2 className="nb-title">お知らせ・ブログ</h2>
          </div>

          <a className="fuho-band reveal" href={FUHO} target="_blank" rel="noopener">
            <span className="fuho-ic"><Icon name="lotus" strokeWidth={1.5} /></span>
            <span className="fuho-tx"><b>本日の訃報</b><em>ご訃報・ご会葬のご案内はこちら（外部サイト）</em></span>
            <Icon name="arrow" className="fuho-arr" strokeWidth={1.8} />
          </a>

          <div className="nfeeds">
            {FEEDS.map((f) => <Feed key={f.key} base={f.base} label={f.label} all={f.all} />)}
          </div>

          <div className="nb-head reveal" style={{ marginTop: "2.6rem" }}>
            <span className="eyebrow">Follow us</span>
            <h2 className="nb-title">SNS</h2>
          </div>
          <div className="sns-grid">
            <div className="sns-col reveal">
              <h3 className="sns-h">Facebook</h3>
              <div className="fb-page"
                   data-href="https://www.facebook.com/aifitgroup/"
                   data-tabs="timeline" data-width="500" data-height="500"
                   data-small-header="false" data-adapt-container-width="true"
                   data-hide-cover="false" data-show-facepile="true">
                <blockquote cite="https://www.facebook.com/aifitgroup/" className="fb-xfbml-parse-ignore">
                  <a href="https://www.facebook.com/aifitgroup/">アイフィットさいき葬祭</a>
                </blockquote>
              </div>
              <a className="sns-fallback" href="https://www.facebook.com/aifitgroup/" target="_blank" rel="noopener">Facebookページを見る →</a>
            </div>
            <div className="sns-col reveal">
              <h3 className="sns-h">Instagram</h3>
              {BEHOLD_FEED_ID
                ? <behold-widget feed-id={BEHOLD_FEED_ID}></behold-widget>
                : (
                  <a className="ig-cta" href="https://www.instagram.com/saiki_group/" target="_blank" rel="noopener">
                    <span className="ig-tx"><b>@saiki_group</b><em>最新の様子は Instagram で公開中</em></span>
                    <Icon name="arrow" strokeWidth={1.8} />
                  </a>
                )}
              <a className="sns-fallback" href="https://www.instagram.com/saiki_group/" target="_blank" rel="noopener">Instagramを見る →</a>
            </div>
          </div>
        </div>
      </section>
    );
  }

  window.NewsSnsSection = NewsSnsSection;
})();
