// dex-grid.jsx — Interactive 151-creature grid with filter + detail modal

const RARITIES = [
  {
    id: 'common',
    name: 'COMMON',
    swatch: '#f1e9d2',
    desc: 'The bulk of the dex. Foundation of every roster.',
    odds: '~60%',
    cardBg: 'var(--pd-paper)',
  },
  {
    id: 'uncommon',
    name: 'UNCOMMON',
    swatch: '#c8e6c9',
    desc: 'Mid-tier. Solid attackers, mild type advantages.',
    odds: '~25%',
    cardBg: '#c8e6c9',
  },
  {
    id: 'rare',
    name: 'RARE',
    swatch: '#bbdefb',
    desc: 'Pseudo-legendary stats. Tournament-tier picks.',
    odds: '~10%',
    cardBg: '#bbdefb',
  },
  {
    id: 'epic',
    name: 'EPIC',
    swatch: '#e1bee7',
    desc: 'Limited rolls. Powerful evolutions, high cap.',
    odds: '~4%',
    cardBg: '#e1bee7',
  },
  {
    id: 'legendary',
    name: 'LEGENDARY',
    swatch: 'linear-gradient(135deg, #fff3c4, #ffce3a)',
    desc: 'Mewtwo, Mew, Articuno, Zapdos, Moltres-tier.',
    odds: '~1%',
    cardBg: 'linear-gradient(135deg, #fff3c4, #ffce3a)',
    glow: true,
  },
];

function RarityLegend() {
  const counts = React.useMemo(() => {
    const m = {};
    POKEDEX.forEach(p => { m[p.rarity] = (m[p.rarity] || 0) + 1; });
    return m;
  }, []);

  return (
    <div className="pd-card pd-card--dark" style={{
      padding: 20, marginBottom: 32, overflow: 'hidden',
    }}>
      <div className="row between" style={{ alignItems: 'baseline', marginBottom: 16, flexWrap: 'wrap', gap: 10 }}>
        <div className="pixel" style={{ fontSize: 12, color: 'var(--pd-yellow)', letterSpacing: '.14em' }}>
          ▼ RARITY TIERS ▼
        </div>
        <span className="mono" style={{ fontSize: 13, color: 'rgba(241,233,210,.55)' }}>
          Rarity affects stats, gacha odds, and tournament rewards
        </span>
      </div>

      <div style={{
        display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: 10,
      }}>
        {RARITIES.map(r => (
          <div key={r.id} className="pd-card" style={{
            padding: 14,
            background: r.cardBg,
            position: 'relative',
            boxShadow: r.glow ? '3px 3px 0 0 var(--pd-line), 0 0 18px rgba(255,206,58,.35)' : '3px 3px 0 0 var(--pd-line)',
          }}>
            <div className="row between" style={{ marginBottom: 8, alignItems: 'baseline' }}>
              <span className="pixel" style={{ fontSize: 10, color: '#14172b' }}>{r.name}</span>
              <span className="mono" style={{ fontSize: 14, color: '#14172b' }}>
                {counts[r.id] || 0}
              </span>
            </div>
            <div style={{
              fontSize: 12, color: 'rgba(20,23,43,.7)', lineHeight: 1.4, marginBottom: 10,
              minHeight: 50,
            }}>{r.desc}</div>
            <div className="row between" style={{ alignItems: 'baseline' }}>
              <span className="pixel" style={{ fontSize: 8, color: 'rgba(20,23,43,.55)', letterSpacing: '.12em' }}>BASE ODDS</span>
              <span className="mono" style={{ fontSize: 14, color: '#14172b' }}>{r.odds}</span>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

function DexFilterChip({ active, label, onClick, color }) {
  return (
    <button
      onClick={onClick}
      className="pd-chip"
      style={{
        cursor: 'pointer',
        background: active ? color : 'transparent',
        color: active ? '#14172b' : color,
        borderColor: color,
        fontWeight: 600,
      }}
    >
      {label}
    </button>
  );
}

function DexGridSection({ caught, onCatch }) {
  const [filter, setFilter] = React.useState('all');
  const [rarity, setRarity] = React.useState('all');
  const [hide, setHide] = React.useState(false);
  const [active, setActive] = React.useState(null);

  const filtered = POKEDEX.filter(e => {
    if (filter !== 'all' && !e.types.some(t => t.id === filter)) return false;
    if (rarity !== 'all' && e.rarity !== rarity) return false;
    return true;
  });

  return (
    <section id="dex" className="section">
      <div className="pd-wrap">
        <Reveal>
          <div className="row between" style={{ alignItems: 'flex-end', marginBottom: 24, flexWrap: 'wrap', gap: 20 }}>
          <div>
            <div className="section-label">The Pokedex</div>
            <h2 className="pd-h2" style={{ margin: 0, color: 'var(--pd-paper)' }}>
              151 CREATURES. <span style={{ color: 'var(--pd-yellow)' }}>{caught.size} CAUGHT.</span>
            </h2>
            <p style={{ fontSize: 16, color: 'rgba(241,233,210,.65)', marginTop: 10, maxWidth: 600 }}>
              Each tile is a live token on Solana. Hover for stats, click to inspect, buy on pump.fun.
            </p>
          </div>
          <div className="col" style={{ gap: 10, alignItems: 'flex-end' }}>
            <div className="row" style={{ gap: 8, alignItems: 'center' }}>
              <span className="pixel" style={{ fontSize: 9, color: 'rgba(241,233,210,.55)', letterSpacing: '.14em' }}>HIDE LOCKED</span>
              <button onClick={() => setHide(h => !h)} style={{
                width: 44, height: 24, padding: 0, borderRadius: 12,
                background: hide ? 'var(--pd-yellow)' : 'rgba(241,233,210,.18)',
                border: '2px solid var(--pd-line)', cursor: 'pointer', position: 'relative',
              }}>
                <span style={{
                  position: 'absolute', top: 2, left: hide ? 22 : 2, transition: 'left .15s',
                  width: 16, height: 16, background: 'var(--pd-paper)', borderRadius: '50%', border: '2px solid var(--pd-line)',
                }}/>
              </button>
            </div>
            <div className="row" style={{ gap: 6, flexWrap: 'wrap', justifyContent: 'flex-end', maxWidth: 600 }}>
              <DexFilterChip active={filter === 'all'} label="ALL" color="#f1e9d2" onClick={() => setFilter('all')} />
              {TYPES.map(t => (
                <DexFilterChip key={t.id} active={filter === t.id} label={t.name.toUpperCase()} color={t.color} onClick={() => setFilter(filter === t.id ? 'all' : t.id)} />
              ))}
            </div>
            <div className="row" style={{ gap: 6 }}>
              {['all', 'common', 'uncommon', 'rare', 'epic', 'legendary'].map(r => (
                <button key={r} className="pd-chip" onClick={() => setRarity(r)} style={{
                  background: rarity === r ? 'var(--pd-yellow)' : 'transparent',
                  color: rarity === r ? '#14172b' : 'var(--pd-paper)',
                  borderColor: rarity === r ? 'var(--pd-yellow)' : 'var(--pd-paper)',
                  cursor: 'pointer',
                }}>{r.toUpperCase()}</button>
              ))}
            </div>
          </div>
        </div>
        </Reveal>

        <RarityLegend />

        <div className="dex-grid">
          {filtered.map(e => {
            const locked = !caught.has(e.n);
            if (hide && locked) return null;
            const primary = e.types[0].color;
            const secondary = e.types[1] && e.types[1].color;
            return (
              <div
                key={e.n}
                className={`dex-card ${active && active.n === e.n ? 'is-active' : ''} ${locked ? 'dex-card--locked' : ''}`}
                data-rarity={locked ? 'locked' : e.rarity}
                onClick={() => setActive(e)}
              >
                <div className="row between" style={{ alignItems: 'center' }}>
                  <span className="dex-card__num">#{String(e.n).padStart(3, '0')}</span>
                  {!locked && (
                    <span style={{ width: 8, height: 8, borderRadius: '50%', background: primary, border: '1px solid #14172b' }} />
                  )}
                </div>
                <div style={{ flex: 1, display: 'grid', placeItems: 'center', minHeight: 0 }}>
                  <Sprite seed={e.seed} n={e.n} primary={primary} secondary={secondary} size={42} locked={locked} />
                </div>
                <div className="dex-card__name">{locked ? '???' : e.name.toUpperCase()}</div>
                <div className="row between" style={{ alignItems: 'baseline' }}>
                  <span className="dex-card__price">{locked ? '◎ ???' : `◎${fmtPrice(e.price)}`}</span>
                  {!locked && (
                    <span className="dex-card__delta" style={{ color: e.delta >= 0 ? '#1c8c44' : '#c92a2a' }}>
                      {e.delta >= 0 ? '▲' : '▼'}{Math.abs(e.delta).toFixed(1)}%
                    </span>
                  )}
                </div>
              </div>
            );
          })}
        </div>

        <div className="row center" style={{ marginTop: 28, gap: 14 }}>
          <button className="pd-btn pd-btn--yellow" onClick={() => {
            const next = POKEDEX.find(e => !caught.has(e.n));
            if (next) onCatch(next);
          }}>+ CATCH A RANDOM CREATURE</button>
          <button className="pd-btn pd-btn--ghost">EXPORT MY DEX (PNG)</button>
        </div>
      </div>

      {active && <DexDetail entry={active} onClose={() => setActive(null)} caught={caught.has(active.n)} onCatch={() => onCatch(active)} />}
    </section>
  );
}

function DexDetail({ entry, onClose, caught, onCatch }) {
  const primary = entry.types[0].color;
  const secondary = entry.types[1] && entry.types[1].color;
  // Mini price chart
  const points = React.useMemo(() => {
    const r = srand(entry.seed * 31);
    const pts = [];
    let v = 50;
    for (let i = 0; i < 50; i++) {
      v += (r() - 0.48) * 14;
      v = Math.max(8, Math.min(92, v));
      pts.push(v);
    }
    return pts;
  }, [entry]);
  const path = points.map((p, i) => `${i === 0 ? 'M' : 'L'} ${(i / (points.length - 1)) * 300} ${100 - p}`).join(' ');

  const stats = [
    { k: 'HP',  v: 30 + (entry.seed * 7) % 70 },
    { k: 'ATK', v: 30 + (entry.seed * 11) % 70 },
    { k: 'DEF', v: 30 + (entry.seed * 13) % 70 },
    { k: 'SPD', v: 30 + (entry.seed * 17) % 70 },
    { k: 'SP',  v: 30 + (entry.seed * 19) % 70 },
  ];

  return (
    <div onClick={onClose} style={{
      position: 'fixed', inset: 0, background: 'rgba(0,0,0,.7)', zIndex: 100,
      display: 'grid', placeItems: 'center', padding: 20,
    }}>
      <div className="pd-card pd-card--dark" onClick={e => e.stopPropagation()} style={{
        width: 'min(820px, 100%)', padding: 28, position: 'relative',
      }}>
        <button onClick={onClose} className="pd-btn pd-btn--sm" style={{
          position: 'absolute', top: 14, right: 14, background: 'transparent',
          color: 'var(--pd-paper)', borderColor: 'var(--pd-paper)',
        }}>✕ CLOSE</button>

        <div className="row" style={{ gap: 36, alignItems: 'flex-start', marginTop: 8 }}>
          {/* Left: sprite + buy panel */}
          <div className="col" style={{ gap: 16, width: 280, flexShrink: 0 }}>
            <div className="pd-card center" style={{
              background: `linear-gradient(135deg, ${primary}, ${secondary || primary})`,
              padding: 30, minHeight: 220,
            }}>
              <Sprite seed={entry.seed} n={entry.n} primary={primary} secondary={secondary} size={100} />
            </div>
            <button className="pd-btn" style={{ width: '100%' }} onClick={onCatch} disabled={caught}>
              {caught ? '✓ CAUGHT' : `▶ BUY ON PUMP.FUN`}
            </button>
            <button className="pd-btn pd-btn--ghost pd-btn--sm" style={{ width: '100%' }}>⚔ SEND TO BATTLE</button>
          </div>

          {/* Right: info */}
          <div className="col" style={{ flex: 1, gap: 14 }}>
            <div className="row between" style={{ alignItems: 'flex-start' }}>
              <div>
                <div className="mono" style={{ fontSize: 18, color: 'var(--pd-yellow)' }}>
                  #{String(entry.n).padStart(3, '0')}
                </div>
                <div className="pixel" style={{ fontSize: 26, color: 'var(--pd-paper)', marginTop: 4 }}>
                  {entry.name.toUpperCase()}
                </div>
                <div className="row" style={{ gap: 8, marginTop: 10 }}>
                  {entry.types.map(t => (
                    <span key={t.id} className="pd-chip" style={{ color: t.color, borderColor: t.color }}>{t.name}</span>
                  ))}
                  <span className="pd-chip" style={{
                    color: '#14172b',
                    background: entry.rarity === 'legendary' ? 'var(--pd-yellow)' : 'var(--pd-paper)',
                    borderColor: 'var(--pd-paper)',
                  }}>{entry.rarity.toUpperCase()}</span>
                </div>
              </div>
              <div className="col" style={{ alignItems: 'flex-end' }}>
                <div className="mono" style={{ fontSize: 32, color: 'var(--pd-paper)' }}>
                  ◎{fmtPrice(entry.price)}
                </div>
                <div className="mono" style={{
                  fontSize: 16,
                  color: entry.delta >= 0 ? 'var(--pd-up)' : 'var(--pd-down)'
                }}>
                  {entry.delta >= 0 ? '▲' : '▼'} {Math.abs(entry.delta).toFixed(2)}% · 24h
                </div>
              </div>
            </div>

            {/* Chart */}
            <div style={{
              background: '#0a0d1c', border: '3px solid var(--pd-line)',
              padding: 12, borderRadius: 4,
            }}>
              <svg viewBox="0 0 300 100" width="100%" height="120">
                <defs>
                  <linearGradient id={`g${entry.n}`} x1="0" x2="0" y1="0" y2="1">
                    <stop offset="0%" stopColor={primary} stopOpacity=".4" />
                    <stop offset="100%" stopColor={primary} stopOpacity="0" />
                  </linearGradient>
                </defs>
                <path d={`${path} L 300 100 L 0 100 Z`} fill={`url(#g${entry.n})`} />
                <path d={path} fill="none" stroke={primary} strokeWidth="2" />
              </svg>
            </div>

            {/* Stats */}
            <div className="col" style={{ gap: 8 }}>
              {stats.map(s => (
                <div key={s.k} className="row" style={{ gap: 12, alignItems: 'center' }}>
                  <span className="pixel" style={{ fontSize: 10, color: 'var(--pd-yellow)', width: 36 }}>{s.k}</span>
                  <div style={{
                    flex: 1, height: 10, background: '#1a1d3a', border: '2px solid var(--pd-line)', borderRadius: 2, overflow: 'hidden',
                  }}>
                    <div style={{ height: '100%', width: `${s.v}%`, background: primary }} />
                  </div>
                  <span className="mono" style={{ fontSize: 14, color: 'var(--pd-paper)', width: 36, textAlign: 'right' }}>{s.v}</span>
                </div>
              ))}
            </div>

            <div className="row" style={{ gap: 14, marginTop: 6 }}>
              <Stat k="HOLDERS"   v={entry.holders.toLocaleString()} />
              <Stat k="MARKET CAP" v={`$${(entry.price * entry.supply / 1e3).toFixed(0)}K`} />
              <Stat k="LEVEL CAP" v={`L${entry.level}`} />
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

function Stat({ k, v }) {
  return (
    <div className="col" style={{ gap: 2 }}>
      <span className="pixel" style={{ fontSize: 9, color: 'rgba(241,233,210,.5)', letterSpacing: '.12em' }}>{k}</span>
      <span className="mono" style={{ fontSize: 18, color: 'var(--pd-paper)' }}>{v}</span>
    </div>
  );
}

Object.assign(window, { DexGridSection });
