// Section 1 — What are the tiles?
// Interactive: hover/click tiles to see name + cultural meaning.
// Filter by suit pill.

function SectionTiles() {
  const variant = React.useContext(VariantContext);
  const [hovered, setHovered] = React.useState(null);
  const [selected, setSelected] = React.useState(null);
  const [suit, setSuit] = React.useState('all');
  const [isTouch, setIsTouch] = React.useState(false);

  React.useEffect(() => {
    setIsTouch(window.matchMedia('(hover: none) and (pointer: coarse)').matches);
  }, []);

  React.useEffect(() => {
    setSuit('all');
    setSelected(null);
  }, [variant]);

  const allTiles = [];
  const groups = suit === 'all' ? Object.keys(TILES) : [suit];
  for (const g of groups) {
    for (const t of TILES[g]) allTiles.push({ ...t, suit: g });
  }
  // flower tiles are always shown separately, not in the filtered grid
  const allFlowerTiles = variant === 'taiwan'
    ? [...FLOWER_TILES.flower.map(t => ({...t, suit: 'flower'})), ...FLOWER_TILES.season.map(t => ({...t, suit: 'season'}))]
    : [];

  const activeId = hovered || selected;
  const info = activeId
    ? allTiles.find((t) => t.id === activeId)
      || allFlowerTiles.find((t) => t.id === activeId)
      || Object.values(TILES).flat().find(t => t.id === activeId)
    : null;

  const suits = [
    { id: 'all', label: 'All 34', count: 34 },
    { id: 'wan', label: 'Characters', count: 9 },
    { id: 'tiao', label: 'Bamboo', count: 9 },
    { id: 'bing', label: 'Dots', count: 9 },
    { id: 'wind', label: 'Winds', count: 4 },
    { id: 'dragon', label: 'Dragons', count: 3 },
    ...(variant === 'taiwan' ? [{ id: 'flower', label: 'Bonus', count: 8 }] : []),
  ];

  return (
    <section id="section-tiles" className="mj-section" data-screen-label="01 Tiles">
      <div className="mj-section-head">
        <div className="mj-kicker">Section 01 · The deck</div>
        <h2 className="mj-h2">What are the tiles?</h2>
        <p className="mj-lede">
          {variant === 'taiwan' ? (
            <>A mahjong set in Taiwan rules has <strong>144 tiles</strong>: the same 34 unique designs × 4, plus <strong>8 bonus tiles</strong> — four Flowers and four Seasons. These are never part of a winning hand; they score separately.</>
          ) : (
            <>A mahjong set has <strong>136 tiles</strong>: 34 unique designs, four of each. Three suits run 1–9 (Characters, Bamboo, Dots), plus the honor tiles — four Winds and three Dragons.</>
          )}
          {' '}Hover or tap any tile to learn its name.
        </p>
      </div>

      <div className="mj-tile-explorer">
        {/* Filter pills */}
        <div className="mj-pills">
          {suits.map((s) => (
            <button
              key={s.id}
              className={`mj-pill ${suit === s.id ? 'is-active' : ''}`}
              onClick={() => { setSuit(s.id); setSelected(null); }}
            >
              {s.label}
              <span className="mj-pill-count">{s.count}</span>
            </button>
          ))}
        </div>


        <div className="mj-tile-grid-wrap" onClick={() => setSelected(null)}>
          <div className="mj-tile-grid">
            {suit === 'flower' ? (
              Object.keys(FLOWER_TILES).map((group) => (
                <div key={group} className="mj-suit-row">
                  <div className="mj-suit-label">
                    <div className="mj-suit-title">{FLOWER_META[group].label}</div>
                    <div className="mj-suit-sub">{FLOWER_META[group].sub}</div>
                    <div className="mj-suit-desc">{FLOWER_META[group].desc}</div>
                    <div className="mj-suit-count">4 tiles · each 1 of a kind</div>
                  </div>
                  <div className="mj-suit-tiles mj-suit-tiles-honors">
                    {FLOWER_TILES[group].map((t) => (
                      <div
                        key={t.id}
                        onMouseEnter={isTouch ? undefined : () => setHovered(t.id)}
                        onMouseLeave={isTouch ? undefined : () => setHovered((h) => (h === t.id ? null : h))}
                        onClick={(e) => {
                          e.stopPropagation();
                          setSelected((s) => (s === t.id ? null : t.id));
                        }}
                      >
                        <Tile
                          id={t.id}
                          size="md"
                          selected={activeId === t.id}
                          dimmed={activeId && activeId !== t.id}
                        />
                      </div>
                    ))}
                  </div>
                </div>
              ))
            ) : (
              groups.map((g) => (
                <div key={g} className="mj-suit-row">
                  <div className="mj-suit-label">
                    <div className="mj-suit-title">{SUIT_META[g].label}</div>
                    <div className="mj-suit-sub">{SUIT_META[g].sub}</div>
                    <div className="mj-suit-desc">{SUIT_META[g].desc}</div>
                    <div className="mj-suit-count">{TILES[g].length} × 4 = {TILES[g].length * 4} tiles</div>
                  </div>
                  <div className={`mj-suit-tiles ${g === 'wind' || g === 'dragon' ? 'mj-suit-tiles-honors' : ''}`}>
                    {TILES[g].map((t) => (
                      <div
                        key={t.id}
                        onMouseEnter={isTouch ? undefined : () => setHovered(t.id)}
                        onMouseLeave={isTouch ? undefined : () => setHovered((h) => (h === t.id ? null : h))}
                        onClick={(e) => {
                          e.stopPropagation();
                          setSelected((s) => (s === t.id ? null : t.id));
                        }}
                      >
                        <Tile
                          id={t.id}
                          size="md"
                          selected={activeId === t.id}
                          dimmed={activeId && activeId !== t.id}
                        />
                      </div>
                    ))}
                  </div>
                </div>
              ))
            )}
          </div>

          {/* Info card — sticky on desktop */}
          <aside className="mj-info-card">
            {info ? (
              <>
                <div className="mj-info-big">
                  <Tile id={info.id} size="xl" />
                </div>
                <div className="mj-info-zh">{info.zh}</div>
                <div className="mj-info-en">{info.en}</div>
                <div className="mj-info-meta">
                  {info.suit === 'wan' && 'Suit · Characters (万). Read the top symbol as the number, bottom as the suit.'}
                  {info.suit === 'tiao' && 'Suit · Bamboo (条). The 1-bamboo shows a bird — a classical flourish.'}
                  {info.suit === 'bing' && 'Suit · Dots (饼). Each circle is a stack of coins.'}
                  {info.suit === 'wind' && 'Honor tile · one of four winds. Your seat wind and the round wind both matter for scoring.'}
                  {info.suit === 'dragon' && 'Honor tile · one of three dragons. A pung of dragons is always worth points.'}
                  {info.suit === 'flower' && `Bonus tile · Taiwan only. Reveal immediately when drawn, then draw a replacement. Tile #${info.num} matches seat ${info.num} — worth 1 台 if the number matches your seat.`}
                  {info.suit === 'season' && `Bonus tile · Taiwan only. Reveal immediately when drawn, then draw a replacement. Tile #${info.num} matches seat ${info.num} — worth 1 台 if the number matches your seat.`}
                </div>
              </>
            ) : (
              <div className="mj-info-empty">
                <div className="mj-info-empty-h">Hover or tap a tile</div>
                <div className="mj-info-empty-p">
                  Each appears four times in the wall. The numbered suits behave like three independent decks; the honors can't form runs.
                </div>
              </div>
            )}
          </aside>
        </div>

        {ReactDOM.createPortal(
          <div
            className={`mj-tile-popup ${selected ? 'is-active' : ''}`}
            onClick={() => setSelected(null)}
          >
            <div className="mj-tile-popup-sheet" onClick={e => e.stopPropagation()}>
              <button className="mj-tile-popup-close" onClick={() => setSelected(null)}>✕</button>
              {info && (
                <>
                  <div className="mj-info-big"><Tile id={info.id} size="xl" /></div>
                  <div className="mj-info-zh">{info.zh}</div>
                  <div className="mj-info-en">{info.en}</div>
                  <div className="mj-info-meta">
                    {info.suit === 'wan' && 'Suit · Characters (万). Read the top symbol as the number, bottom as the suit.'}
                    {info.suit === 'tiao' && 'Suit · Bamboo (条). The 1-bamboo shows a bird — a classical flourish.'}
                    {info.suit === 'bing' && 'Suit · Dots (饼). Each circle is a stack of coins.'}
                    {info.suit === 'wind' && 'Honor tile · one of four winds. Your seat wind and the round wind both matter for scoring.'}
                    {info.suit === 'dragon' && 'Honor tile · one of three dragons. A pung of dragons is always worth points.'}
                    {info.suit === 'flower' && `Bonus tile · Taiwan only. Reveal immediately when drawn, then draw a replacement. Tile #${info.num} matches seat ${info.num} — worth 1 台 if the number matches your seat.`}
                    {info.suit === 'season' && `Bonus tile · Taiwan only. Reveal immediately when drawn, then draw a replacement. Tile #${info.num} matches seat ${info.num} — worth 1 台 if the number matches your seat.`}
                  </div>
                </>
              )}
            </div>
          </div>,
          document.body
        )}

        {variant === 'taiwan' && suit !== 'flower' && (
          <div className="mj-flower-section">
            <div className="mj-kicker" style={{marginBottom: 28}}>Bonus tiles · Taiwan only</div>
            <div className="mj-tile-grid">
            {Object.keys(FLOWER_TILES).map((group) => (
              <div key={group} className="mj-suit-row">
                <div className="mj-suit-label">
                  <div className="mj-suit-title">{FLOWER_META[group].label}</div>
                  <div className="mj-suit-sub">{FLOWER_META[group].sub}</div>
                  <div className="mj-suit-desc">{FLOWER_META[group].desc}</div>
                  <div className="mj-suit-count">4 tiles · each 1 of a kind</div>
                </div>
                <div className="mj-suit-tiles mj-suit-tiles-honors">
                  {FLOWER_TILES[group].map((t) => (
                    <div
                      key={t.id}
                      onMouseEnter={isTouch ? undefined : () => setHovered(t.id)}
                      onMouseLeave={isTouch ? undefined : () => setHovered((h) => (h === t.id ? null : h))}
                      onClick={(e) => {
                        e.stopPropagation();
                        setSelected((s) => (s === t.id ? null : t.id));
                      }}
                    >
                      <Tile
                        id={t.id}
                        size="md"
                        selected={activeId === t.id}
                        dimmed={activeId && activeId !== t.id}
                      />
                    </div>
                  ))}
                </div>
              </div>
            ))}
            </div>
          </div>
        )}
      </div>
    </section>
  );
}

Object.assign(window, { SectionTiles });
