// Instagram feed block for moja_run run
// お客様が Instagram に投稿するだけで「お知らせ」が更新される仕組み。
//
// 設定は index.html の「お知らせ（Instagram）設定」ブロックだけで完結します:
//   window.INSTAGRAM_PROFILE … プロフィールURL
//   window.INSTAGRAM_EMBED   … 連携ウィジェットの貼り付けコード（空ならサンプル表示）
//
// 詳しい手順は「お知らせ更新マニュアル.md」を参照してください。

const IG_FALLBACK = ['g1', 'g2', 'g3', 'g4', 'g5', 'g6'];

const IgGlyph = ({ size = 20 }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
    <rect x="3" y="3" width="18" height="18" rx="5"/>
    <circle cx="12" cy="12" r="4"/>
    <circle cx="17" cy="7" r="1" fill="currentColor"/>
  </svg>
);

const Instagram = () => {
  const mountRef = React.useRef(null);
  const [hasWidget, setHasWidget] = React.useState(false);
  const profile = window.INSTAGRAM_PROFILE || 'https://www.instagram.com/moja_runrun/';
  const handle = '@' + (profile.replace(/\/+$/,'').split('/').pop() || 'moja_runrun');

  React.useEffect(() => {
    const embed = (window.INSTAGRAM_EMBED || '').trim();
    if (embed && mountRef.current) {
      mountRef.current.innerHTML = embed;
      // re-create <script> tags so widget JS actually executes
      mountRef.current.querySelectorAll('script').forEach((old) => {
        const s = document.createElement('script');
        [...old.attributes].forEach((a) => s.setAttribute(a.name, a.value));
        s.textContent = old.textContent;
        old.replaceWith(s);
      });
      setHasWidget(true);
    }
  }, []);

  return (
    <div className="ig-block">
      <div className="ig-profile">
        <a className="ig-avatar" href={profile} target="_blank" rel="noopener noreferrer">
          <img src="assets/logo-circle.png" alt="もじゃるんるん"/>
        </a>
        <div className="ig-id">
          <a className="ig-handle en" href={profile} target="_blank" rel="noopener noreferrer">{handle}</a>
          <div className="ig-sub">日々のわんちゃんと、お休みのお知らせを発信中</div>
        </div>
        <a className="ig-follow" href={profile} target="_blank" rel="noopener noreferrer">
          <IgGlyph size={16}/>
          フォローする
        </a>
      </div>

      <div ref={mountRef} className="ig-embed-mount"></div>

      {!hasWidget && (
        <div className="ig-grid">
          {IG_FALLBACK.map((g) => (
            <a key={g} className="ig-tile" href={profile} target="_blank" rel="noopener noreferrer">
              <img src={`assets/gallery/${g}.jpg`} alt="" loading="lazy"/>
              <span className="ig-tile-ov"><IgGlyph size={26}/></span>
            </a>
          ))}
        </div>
      )}
    </div>
  );
};

Object.assign(window, { Instagram, IgGlyph });
