// gallery.jsx
function VideoFace({ src, label }) {
  const ref = React.useRef(null);
  React.useEffect(() => {
    const v = ref.current;
    if (!v) return;
    v.muted = true; v.defaultMuted = true; v.playsInline = true;
    const tryPlay = () => { const p = v.play(); if (p && p.catch) p.catch(() => {}); };
    tryPlay();
    v.addEventListener('canplay', tryPlay);
    v.addEventListener('loadeddata', tryPlay);
    return () => {
      v.removeEventListener('canplay', tryPlay);
      v.removeEventListener('loadeddata', tryPlay);
    };
  }, [src]);
  return (
    <video ref={ref} autoPlay muted loop playsInline preload="auto" aria-label={label}>
      <source src={src} type="video/mp4" />
    </video>
  );
}

function getSeries(c) {
  const n = parseInt(c.no, 10);
  if (c.no === '002') return { key: 'promo', label: 'プロモーション' };
  if (n >= 1 && n <= 13) return { key: 'starter', label: 'スターター' };
  if (n >= 14 && n <= 44) return { key: 'v1', label: '第1弾' };
  if (n >= 45 && n <= 88) return { key: 'v2', label: '第2弾' };
  if (n >= 89 && n <= 132) return { key: 'v3', label: '第3弾' };
  return null;
}

function FlipCard({ c }) {
  const [flipped, setFlipped] = React.useState(false);
  const rarity = (parseInt(c.no, 10) % 3) + 2;
  const tag = ['C', 'R', 'SR', 'UR'][rarity - 1];
  const series = getSeries(c);
  return (
    <div className="flip-card" onClick={() => setFlipped(!flipped)}>
      <div className="flip-inner" style={{ transform: flipped ? 'rotateY(180deg)' : 'rotateY(0)' }}>
        <div className="flip-face">
          {c.video ? (
            <div className="hero-card-real card-video-face" style={{ width: '100%', height: '100%', boxShadow: 'none', border: 'none', borderRadius: 10 }}>
              <VideoFace src={c.video} label={`${c.name} No.${c.no}`} />
              {c.class === 'special' && (
                <div className="card-video-frame" aria-hidden="true">
                  <div className="card-video-no">No.{c.no}</div>
                  <div className="card-video-tag">SP</div>
                  <div className="card-video-name">{c.name}</div>
                </div>
              )}
            </div>
          ) : c.img ? (
            <div className="hero-card-real" style={{ width: '100%', height: '100%', boxShadow: 'none', border: 'none', borderRadius: 10 }}>
              <img src={c.img} alt={`${c.name} No.${c.no}`} />
            </div>
          ) : (
            <CreatureCard c={c} rarity={rarity} tag={tag} />
          )}
        </div>
        <div className="flip-face flip-back">
          {series && <div className={`series-badge series-${series.key}`}>{series.label}</div>}
          <h4>{c.name}</h4>
          <div className="meta" style={{ fontSize: 10, fontFamily: 'DotGothic16, monospace' }}>{c.status} ｜ {c.region}</div>
          <div className="desc-body" style={{ fontSize: 10, lineHeight: 1.45, marginTop: 6, fontFamily: 'Zen Kaku Gothic New' }}>{c.desc}</div>
          <div className="flip-hint" style={{ marginTop: 'auto' }}>クリックで戻る ↺</div>
        </div>
      </div>
    </div>
  );
}

function Gallery() {
  const [filter, setFilter] = React.useState('all');
  const classFilters = [
    { id: 'all', label: 'すべて' },
    { id: 'bird', label: '鳥類' },
    { id: 'mammal', label: '哺乳類' },
    { id: 'amphibian', label: '両生類' },
    { id: 'reptile', label: '爬虫類' },
    { id: 'insect', label: '昆虫類' },
    { id: 'spider', label: 'クモ類' },
    { id: 'fish', label: '魚類' },
    { id: 'shellfish', label: '貝類' },
    { id: 'plant', label: '植物' },
    { id: 'fungus', label: '菌類' },
    { id: 'annelid', label: '環形動物' },
    { id: 'flatworm', label: '扁形動物' },
    { id: 'boost', label: 'ブースト' },
  ];
  const seriesFilters = [
    { id: 'series_starter', label: 'スターター', key: 'starter' },
    { id: 'series_promo', label: 'プロモーション', key: 'promo' },
    { id: 'series_v1', label: '第1弾', key: 'v1' },
    { id: 'series_v2', label: '第2弾', key: 'v2' },
    { id: 'series_v3', label: '第3弾', key: 'v3' },
  ];
  const galleryAll = (window.CREATURES || []).filter(c => c.class !== 'special');
  let shown;
  if (filter === 'all') shown = galleryAll;
  else if (filter.startsWith('series_')) {
    const key = filter.replace('series_', '');
    shown = galleryAll.filter(c => { const s = getSeries(c); return s && s.key === key; });
  } else {
    shown = galleryAll.filter(c => c.class === filter);
  }
  const HEAD = 10;
  const TAIL = 5;
  const isAll = filter === 'all';
  const headCards = isAll ? shown.slice(0, HEAD) : shown;
  const tailCards = isAll ? shown.slice(HEAD, HEAD + TAIL) : [];
  const hiddenCount = isAll ? Math.max(0, shown.length - HEAD) : 0;
  return (
    <section className="section" id="gallery" style={{ paddingTop: 120 }}>
      <div className="container">
        <SectionHeader label="◤ CARD GALLERY" title={<>カードギャラリー</>} subtitle="クリックでカードがフリップし、生態や保全ステータスが見られます。公式データベースには212種すべての詳細がアップされます。" />
        <div className="gallery-filter">
          {classFilters.map(f => (
            <button key={f.id} className={filter === f.id ? 'active' : ''} onClick={() => setFilter(f.id)}>{f.label}</button>
          ))}
        </div>
        <div className="gallery-filter gallery-filter-series">
          {seriesFilters.map(f => (
            <button key={f.id} className={`series-pill series-pill-${f.key} ${filter === f.id ? 'active' : ''}`} onClick={() => setFilter(f.id)}>{f.label}</button>
          ))}
        </div>
        <div className="gallery-grid-wrap">
          <div className="gallery-grid">
            {headCards.map((c) => (
              <div key={c.id} className="gallery-cell"><FlipCard c={c} /></div>
            ))}
            {tailCards.map((c) => (
              <div key={c.id} className="gallery-cell is-faded" aria-hidden="true">
                <FlipCard c={c} />
              </div>
            ))}
          </div>
          {tailCards.length > 0 && (
            <React.Fragment>
              <div className="gallery-fade" aria-hidden="true"></div>
              <div className="gallery-more">
                <div className="gallery-more-meta">
                  <span className="gallery-more-count">+{hiddenCount}種</span>
                  <span className="gallery-more-sub">No.11 以降は公式データベースで全種を閲覧できます</span>
                </div>
                <a href="Card Database.html" className="pop-btn dark gallery-more-btn">もっと見る →</a>
              </div>
            </React.Fragment>
          )}
        </div>
        {tailCards.length === 0 && (
          <div style={{ marginTop: 64, textAlign: 'center' }}>
            <a href="Card Database.html" className="pop-btn dark">全212種のデータベースへ →</a>
          </div>
        )}
      </div>
    </section>
  );
}
Object.assign(window, { Gallery, FlipCard, VideoFace });
