// Section 2 — How do you win?
// Animated hand reveal. Shows 13+1 tiles resolving into 4 melds + 1 pair.
// Also includes a scoring rundown with example hands.

const WINNING_HANDS = [
  {
    id: 'basic',
    name: 'Standard hand',
    zh: '平胡',
    melds: [
      { type: 'chow', tiles: ['wan-2', 'wan-3', 'wan-4'], label: 'Chow · 2-3-4 Characters' },
      { type: 'pung', tiles: ['tiao-5', 'tiao-5', 'tiao-5'], label: 'Pung · 5 Bamboo' },
      { type: 'chow', tiles: ['bing-7', 'bing-8', 'bing-9'], label: 'Chow · 7-8-9 Circles' },
      { type: 'pung', tiles: ['east', 'east', 'east'], label: 'Pung · East Wind' },
      { type: 'pair', tiles: ['red', 'red'], label: 'Pair · Red Dragon' },
    ],
    points: '10 points',
    desc: 'Four sets + one pair. The pair is the "eyes". Any combination of chows and pungs works.',
  },
  {
    id: 'allpungs',
    name: 'All Pungs',
    zh: '对对胡',
    melds: [
      { type: 'pung', tiles: ['wan-3', 'wan-3', 'wan-3'], label: 'Pung · 3 Characters' },
      { type: 'pung', tiles: ['tiao-7', 'tiao-7', 'tiao-7'], label: 'Pung · 7 Bamboo' },
      { type: 'pung', tiles: ['bing-2', 'bing-2', 'bing-2'], label: 'Pung · 2 Circles' },
      { type: 'pung', tiles: ['south', 'south', 'south'], label: 'Pung · South Wind' },
      { type: 'pair', tiles: ['green', 'green'], label: 'Pair · Green Dragon' },
    ],
    points: '30 points',
    desc: 'Every set is a triplet — no runs allowed. A fan/yaku in most rulesets.',
  },
  {
    id: 'purity',
    name: 'All Same Suit',
    zh: '清一色',
    melds: [
      { type: 'chow', tiles: ['bing-1', 'bing-2', 'bing-3'], label: 'Chow · 1-2-3 Circles' },
      { type: 'chow', tiles: ['bing-4', 'bing-5', 'bing-6'], label: 'Chow · 4-5-6 Circles' },
      { type: 'chow', tiles: ['bing-7', 'bing-8', 'bing-9'], label: 'Chow · 7-8-9 Circles' },
      { type: 'pung', tiles: ['bing-2', 'bing-2', 'bing-2'], label: 'Pung · 2 Circles' },
      { type: 'pair', tiles: ['bing-5', 'bing-5'], label: 'Pair · 5 Circles' },
    ],
    points: '80 points',
    desc: 'The entire hand is one suit. No honors, no winds, no dragons. Rare and beautiful.',
  },
  {
    id: 'thirteen',
    name: 'Thirteen Orphans',
    zh: '十三幺',
    melds: [
      { type: 'special', tiles: ['wan-1', 'wan-9', 'tiao-1', 'tiao-9', 'bing-1', 'bing-9', 'east'], label: 'Terminals & honors' },
      { type: 'special', tiles: ['south', 'west', 'north', 'red', 'green', 'white', 'wan-1'], label: 'Plus any duplicate' },
    ],
    points: 'Limit hand',
    desc: 'One of each terminal (1s and 9s) and each honor tile, plus any one of those duplicated. A special hand.',
  },
];

const WINNING_HANDS_TAIWAN = [
  {
    id: 'basic',
    name: 'Standard hand',
    zh: '平胡',
    melds: [
      { type: 'chow', tiles: ['wan-2', 'wan-3', 'wan-4'], label: 'Chow · 2-3-4 Characters' },
      { type: 'chow', tiles: ['tiao-3', 'tiao-4', 'tiao-5'], label: 'Chow · 3-4-5 Bamboo' },
      { type: 'chow', tiles: ['bing-6', 'bing-7', 'bing-8'], label: 'Chow · 6-7-8 Circles' },
      { type: 'pung', tiles: ['east', 'east', 'east'], label: 'Pung · East Wind' },
      { type: 'chow', tiles: ['wan-6', 'wan-7', 'wan-8'], label: 'Chow · 6-7-8 Characters' },
      { type: 'pair', tiles: ['red', 'red'], label: 'Pair · Red Dragon' },
    ],
    points: '1 台',
    desc: 'Five sets + one pair — 17 tiles total. Taiwan hands have one extra meld compared to Hong Kong. You need at least 1 台 to declare a valid win.',
  },
  {
    id: 'allpungs',
    name: 'All Pungs',
    zh: '對對胡',
    melds: [
      { type: 'pung', tiles: ['wan-3', 'wan-3', 'wan-3'], label: 'Pung · 3 Characters' },
      { type: 'pung', tiles: ['tiao-7', 'tiao-7', 'tiao-7'], label: 'Pung · 7 Bamboo' },
      { type: 'pung', tiles: ['bing-2', 'bing-2', 'bing-2'], label: 'Pung · 2 Circles' },
      { type: 'pung', tiles: ['south', 'south', 'south'], label: 'Pung · South Wind' },
      { type: 'pung', tiles: ['wan-9', 'wan-9', 'wan-9'], label: 'Pung · 9 Characters' },
      { type: 'pair', tiles: ['green', 'green'], label: 'Pair · Green Dragon' },
    ],
    points: '3 台',
    desc: 'All five sets are triplets — no runs at all. Worth 3 台 in Taiwan scoring.',
  },
  {
    id: 'purity',
    name: 'All Same Suit',
    zh: '清一色',
    melds: [
      { type: 'chow', tiles: ['bing-1', 'bing-2', 'bing-3'], label: 'Chow · 1-2-3 Circles' },
      { type: 'chow', tiles: ['bing-2', 'bing-3', 'bing-4'], label: 'Chow · 2-3-4 Circles' },
      { type: 'chow', tiles: ['bing-5', 'bing-6', 'bing-7'], label: 'Chow · 5-6-7 Circles' },
      { type: 'pung', tiles: ['bing-8', 'bing-8', 'bing-8'], label: 'Pung · 8 Circles' },
      { type: 'chow', tiles: ['bing-7', 'bing-8', 'bing-9'], label: 'Chow · 7-8-9 Circles' },
      { type: 'pair', tiles: ['bing-5', 'bing-5'], label: 'Pair · 5 Circles' },
    ],
    points: '8 台',
    desc: 'All five sets and the pair are the same suit — no honors, no winds, no dragons. One of the biggest regular hands in Taiwan rules.',
  },
  {
    id: 'halfflush',
    name: 'Half Flush',
    zh: '混一色',
    melds: [
      { type: 'chow', tiles: ['wan-1', 'wan-2', 'wan-3'], label: 'Chow · 1-2-3 Characters' },
      { type: 'chow', tiles: ['wan-4', 'wan-5', 'wan-6'], label: 'Chow · 4-5-6 Characters' },
      { type: 'pung', tiles: ['wan-9', 'wan-9', 'wan-9'], label: 'Pung · 9 Characters' },
      { type: 'pung', tiles: ['east', 'east', 'east'], label: 'Pung · East Wind' },
      { type: 'pung', tiles: ['red', 'red', 'red'], label: 'Pung · Red Dragon' },
      { type: 'pair', tiles: ['wan-7', 'wan-7'], label: 'Pair · 7 Characters' },
    ],
    points: '3 台',
    desc: 'One suit plus honor tiles (winds or dragons). Mixing honors with a single suit earns 3 台.',
  },
];

function SectionWin() {
  const variant = React.useContext(VariantContext);
  const hands = variant === 'taiwan' ? WINNING_HANDS_TAIWAN : WINNING_HANDS;
  const [handIdx, setHandIdx] = React.useState(0);
  const [stage, setStage] = React.useState(0);
  const [playing, setPlaying] = React.useState(false);
  const hand = hands[handIdx];
  const allTiles = hand.melds.flatMap((m) => m.tiles);

  // Reset hand selection when switching variants
  React.useEffect(() => { setHandIdx(0); }, [variant]);

  // Auto-play the reveal when a hand is selected
  React.useEffect(() => {
    setStage(0);
    const t1 = setTimeout(() => setStage(1), 400);
    const t2 = setTimeout(() => setStage(2), 1300);
    return () => { clearTimeout(t1); clearTimeout(t2); };
  }, [handIdx]);

  const replay = () => {
    setStage(0);
    setTimeout(() => setStage(1), 400);
    setTimeout(() => setStage(2), 1300);
  };

  return (
    <section id="section-win" className="mj-section" data-screen-label="02 Win">
      <div className="mj-section-head">
        <div className="mj-kicker">Section 02 · The goal</div>
        <h2 className="mj-h2">How do you win?</h2>
        <p className="mj-lede">
          {variant === 'taiwan' ? (
            <>A winning hand is <strong>5 sets + 1 pair</strong> — 17 tiles total (you hold 16, draw 1 to win). A "set" is a <em>chow</em> (three in a row, same suit), a <em>pung</em> (three of a kind), or a <em>kong</em> (four of a kind). You must reach at least <strong>1 台</strong> to declare — a bare hand with no scoring combination is not allowed.</>
          ) : (
            <>A winning hand is <strong>4 sets + 1 pair</strong> — 14 tiles total. A "set" is either a <em>chow</em> (three in a row, same suit), a <em>pung</em> (three of a kind), or a <em>kong</em> (four of a kind). The pair is called the <em>eyes</em>.</>
          )}
        </p>
      </div>

      <div className="mj-hand-reveal">
        <div className="mj-hand-tabs">
          {hands.map((h, i) => (
            <button
              key={h.id}
              className={`mj-tab ${handIdx === i ? 'is-active' : ''}`}
              onClick={() => setHandIdx(i)}
            >
              <div className="mj-tab-zh">{h.zh}</div>
              <div className="mj-tab-name">{h.name}</div>
              <div className="mj-tab-pts">{h.points}</div>
            </button>
          ))}
        </div>

        <div className="mj-hand-stage">
          {/* Stage header */}
          <div className="mj-stage-header">
            <div>
              <div className="mj-stage-name">{hand.name} <span className="mj-stage-zh">· {hand.zh}</span></div>
              <div className="mj-stage-desc">{hand.desc}</div>
            </div>
            <button className="mj-btn" onClick={replay}>
              <svg width="14" height="14" viewBox="0 0 14 14" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round">
                <path d="M1 2v4h4M13 12v-4h-4"/>
                <path d="M11 5A5 5 0 0 0 2 6M3 9a5 5 0 0 0 9-1"/>
              </svg>
              Replay
            </button>
          </div>

          {/* The animated tile display */}
          {hand.id === 'thirteen' ? (
            <div className="mj-hand-flat">
              {hand.melds[0].tiles.concat(hand.melds[1].tiles).map((t, i) => (
                <div
                  key={i}
                  style={{
                    opacity: stage >= 1 ? 1 : 0.2,
                    transform: stage >= 1 ? 'translateY(0)' : `translateY(${(i % 3) * 4 - 4}px) rotate(${(i * 7) % 5 - 2}deg)`,
                    transition: `all 400ms cubic-bezier(.3,.7,.3,1) ${i * 40}ms`,
                  }}
                >
                  <Tile id={t} size="md" />
                </div>
              ))}
            </div>
          ) : (
            <div className={`mj-hand-sets stage-${stage}`}>
              {hand.melds.map((meld, mi) => (
                <div
                  key={mi}
                  className={`mj-meld meld-${meld.type}`}
                  style={{
                    opacity: stage >= 1 ? 1 : 0,
                    transform: stage >= 1 ? 'translateY(0)' : 'translateY(12px)',
                    transition: `all 500ms cubic-bezier(.3,.7,.3,1) ${mi * 140}ms`,
                  }}
                >
                  <div className="mj-meld-tiles">
                    {meld.tiles.map((t, ti) => (
                      <div
                        key={ti}
                        style={{
                          opacity: stage >= 2 ? 1 : stage >= 1 ? 0.85 : 0,
                          transform: stage >= 2 ? 'translateY(0)' : 'translateY(-4px)',
                          transition: `all 400ms cubic-bezier(.3,.7,.3,1) ${mi * 140 + ti * 80 + 200}ms`,
                        }}
                      >
                        <Tile id={t} size="lg" />
                      </div>
                    ))}
                  </div>
                  <div
                    className="mj-meld-label"
                    style={{
                      opacity: stage >= 2 ? 1 : 0,
                      transition: `opacity 300ms ${mi * 140 + 500}ms`,
                    }}
                  >
                    {meld.label}
                  </div>
                </div>
              ))}
            </div>
          )}

          <div className="mj-stage-footer">
            <div className="mj-stage-count">
              <div className="mj-count-big">{allTiles.length}</div>
              <div className="mj-count-lbl">tiles total</div>
            </div>
            <div className="mj-stage-arrow">→</div>
            <div className="mj-stage-formula">
              <span><strong>{hand.melds.filter(m => m.type !== 'pair').length}</strong> sets + <strong>1</strong> pair</span>
            </div>
            <div className="mj-stage-arrow">=</div>
            <div className="mj-stage-pts">{hand.points}</div>
          </div>
        </div>

        {/* Scoring aside */}
        {variant === 'taiwan' ? (
          <div className="mj-scoring">
            <div className="mj-scoring-h">Scoring in a nutshell · Taiwan</div>
            <div className="mj-scoring-fan">
              <strong>台</strong> (tái) = scoring unit. Each 台 doubles your base payout — same exponential logic as fan, different name. Minimum <strong>1 台</strong> to win; a hand with zero 台 is an illegal win (烏龍) and earns a penalty.
            </div>
            <div className="mj-scoring-grid">
              <div className="mj-score-row">
                <div className="mj-score-name">Self-draw (自摸)</div>
                <div className="mj-score-desc">You drew your own winning tile</div>
                <div className="mj-score-val">1 台</div>
              </div>
              <div className="mj-score-row">
                <div className="mj-score-name">Pung of dragons</div>
                <div className="mj-score-desc">Three of any dragon tile</div>
                <div className="mj-score-val">1 台</div>
              </div>
              <div className="mj-score-row">
                <div className="mj-score-name">Pung of seat/round wind</div>
                <div className="mj-score-desc">Your wind, or the prevailing wind</div>
                <div className="mj-score-val">1 台</div>
              </div>
              <div className="mj-score-row">
                <div className="mj-score-name">Matching flower or season</div>
                <div className="mj-score-desc">Flower/season number = your seat number</div>
                <div className="mj-score-val">1 台 each</div>
              </div>
              <div className="mj-score-row">
                <div className="mj-score-name">All Pungs (對對胡)</div>
                <div className="mj-score-desc">Every set a triplet</div>
                <div className="mj-score-val">3 台</div>
              </div>
              <div className="mj-score-row">
                <div className="mj-score-name">Mixed one suit (混一色)</div>
                <div className="mj-score-desc">One suit + honors</div>
                <div className="mj-score-val">3 台</div>
              </div>
              <div className="mj-score-row">
                <div className="mj-score-name">Pure one suit (清一色)</div>
                <div className="mj-score-desc">One suit, no honors</div>
                <div className="mj-score-val">8 台</div>
              </div>
              <div className="mj-score-row mj-score-limit">
                <div className="mj-score-name">Limit hand</div>
                <div className="mj-score-desc">13 Orphans, etc.</div>
                <div className="mj-score-val">Max</div>
              </div>
            </div>
            <div className="mj-scoring-note">
              Self-draw (自摸): all three opponents pay you directly. On a discard win, only the discarder pays. Dealer pays or receives double.
            </div>
          </div>
        ) : (
          <div className="mj-scoring">
            <div className="mj-scoring-h">Scoring in a nutshell</div>
            <div className="mj-scoring-fan">
              <strong>Fan</strong> (番 · fān) = scoring doubles. Every fan <em>doubles</em> your base points — so 3 fan = 2³ = 8× base, 6 fan = 64×. More fan, exponentially more payout.
            </div>
            <div className="mj-scoring-grid">
              <div className="mj-score-row">
                <div className="mj-score-name">Pung of dragons</div>
                <div className="mj-score-desc">Three of any dragon tile</div>
                <div className="mj-score-val">1 fan</div>
              </div>
              <div className="mj-score-row">
                <div className="mj-score-name">Pung of seat/round wind</div>
                <div className="mj-score-desc">Your wind, or the prevailing wind</div>
                <div className="mj-score-val">1 fan</div>
              </div>
              <div className="mj-score-row">
                <div className="mj-score-name">All chows (Ping Wu)</div>
                <div className="mj-score-desc">No triplets, pair isn't a scoring tile</div>
                <div className="mj-score-val">1 fan</div>
              </div>
              <div className="mj-score-row">
                <div className="mj-score-name">All Pungs (对对胡)</div>
                <div className="mj-score-desc">Every set a triplet</div>
                <div className="mj-score-val">3 fan</div>
              </div>
              <div className="mj-score-row">
                <div className="mj-score-name">Mixed one suit (混一色)</div>
                <div className="mj-score-desc">One suit + honors</div>
                <div className="mj-score-val">3 fan</div>
              </div>
              <div className="mj-score-row">
                <div className="mj-score-name">Pure one suit (清一色)</div>
                <div className="mj-score-desc">One suit, no honors</div>
                <div className="mj-score-val">6 fan</div>
              </div>
              <div className="mj-score-row">
                <div className="mj-score-name">Self-drawn winning tile</div>
                <div className="mj-score-desc">You drew your own winner</div>
                <div className="mj-score-val">+1 fan</div>
              </div>
              <div className="mj-score-row mj-score-limit">
                <div className="mj-score-name">Limit hand (番满)</div>
                <div className="mj-score-desc">13 Orphans, Big Four Winds, etc.</div>
                <div className="mj-score-val">Max</div>
              </div>
            </div>
            <div className="mj-scoring-note">
              Final score ≈ base points × 2<sup>fan</sup>. More fan = exponentially more points. The loser(s) pay the winner; self-draw means everyone pays.
            </div>
          </div>
        )}
      </div>
    </section>
  );
}

Object.assign(window, { SectionWin, WINNING_HANDS });
