// Section 4 — How do you draw cards?
// Interactive wall. All 4 steps visible at once; wall shown for each.

function SectionDraw() {
  const variant = React.useContext(VariantContext);
  const MAX_HAND = variant === 'taiwan' ? 17 : 14;

  const [hand, setHand] = React.useState([]);
  const [drawing, setDrawing] = React.useState(false);
  const [sorted, setSorted] = React.useState(false);

  const DRAW_POOL = [
    'wan-3', 'bing-7', 'tiao-5', 'east', 'wan-8', 'bing-2',
    'tiao-2', 'red', 'wan-5', 'bing-5', 'south', 'tiao-9',
    'green', 'wan-1', 'bing-9', 'tiao-4', 'west', 'wan-6',
  ];

  const SUIT_ORDER = { wan: 0, bing: 1, tiao: 2 };
  const WIND_ORDER = { east: 0, south: 1, west: 2, north: 3 };
  const DRAGON_ORDER = { red: 0, green: 1, white: 2 };
  const WINDS = new Set(['east', 'south', 'west', 'north']);
  const DRAGONS = new Set(['red', 'green', 'white']);

  const sortHand = (tiles) => [...tiles].sort((a, b) => {
    const getSuit = t => t.includes('-') ? t.split('-')[0] : t;
    const getNum = t => t.includes('-') ? parseInt(t.split('-')[1]) : 0;
    const suitA = getSuit(a), suitB = getSuit(b);
    const groupA = WINDS.has(a) ? 1 : DRAGONS.has(a) ? 2 : 0;
    const groupB = WINDS.has(b) ? 1 : DRAGONS.has(b) ? 2 : 0;
    if (groupA !== groupB) return groupA - groupB;
    if (groupA === 0) {
      if (suitA !== suitB) return SUIT_ORDER[suitA] - SUIT_ORDER[suitB];
      return getNum(a) - getNum(b);
    }
    if (groupA === 1) return WIND_ORDER[a] - WIND_ORDER[b];
    return DRAGON_ORDER[a] - DRAGON_ORDER[b];
  });

  // Dice-driven break logic (classical Hong Kong / Chinese rules):
  //   total mod 4: 1→E, 2→S, 3→W, 0→N (treating 4/8/12 as N)
  //   then count that many stacks from the RIGHT end of that player's wall.
  const [d1, setD1] = React.useState(3);
  const [d2, setD2] = React.useState(5);
  const [rolling, setRolling] = React.useState(false);
  const total = d1 + d2;
  const SEATS = ['east', 'south', 'west', 'north'];
  const SEAT_META = {
    east:  { zh: '东', en: 'East',  label: '东 E',  wallSide: 'right',  nums: [1, 5, 9] },
    south: { zh: '南', en: 'South', label: '南 S',  wallSide: 'bottom', nums: [2, 6, 10] },
    west:  { zh: '西', en: 'West',  label: '西 W',  wallSide: 'left',   nums: [3, 7, 11] },
    north: { zh: '北', en: 'North', label: '北 N',  wallSide: 'top',    nums: [4, 8, 12] },
  };
  const seatFor = (t) => SEATS[(t - 1) % 4];
  const breakSeat = seatFor(total);
  // Count `total` stacks from the right end of that wall (0-indexed from right):
  const breakStackFromRight = total - 1;

  const rollDice = () => {
    if (rolling) return;
    setRolling(true);
    let ticks = 0;
    const iv = setInterval(() => {
      setD1(1 + Math.floor(Math.random() * 6));
      setD2(1 + Math.floor(Math.random() * 6));
      ticks++;
      if (ticks >= 10) {
        clearInterval(iv);
        setRolling(false);
      }
    }, 60);
  };

  const DiceFace = ({ v }) => {
    const faces = ['⚀','⚁','⚂','⚃','⚄','⚅'];
    return <span className="mj-die-face">{faces[v - 1]}</span>;
  };

  const doDraw = () => {
    if (drawing || hand.length >= MAX_HAND) return;
    setDrawing(true);
    const next = DRAW_POOL[hand.length % DRAW_POOL.length];
    setTimeout(() => {
      setHand((h) => {
        const newHand = [...h, next];
        if (newHand.length === MAX_HAND) {
          setSorted(true);
          return sortHand(newHand);
        }
        return newHand;
      });
      setDrawing(false);
    }, 280);
  };

  const resetHand = () => {
    setHand([]);
    setSorted(false);
  };

  const discardTile = (idx) => {
    if (hand.length !== MAX_HAND) return;
    setHand(h => h.filter((_, i) => i !== idx));
    setSorted(false);
  };

  const wallSides = ['top', 'right', 'bottom', 'left'];

  const SmallWall = ({ variant, showDirection, breakSeat: bSeat, breakIdx }) => (
    <div className={`mj-wall-mini variant-${variant}`}>
      <div className="mj-wall-inner">
        {wallSides.map((side) => {
          // Map side → seat for dynamic break highlighting
          const sideToSeat = { top: 'north', right: 'east', bottom: 'south', left: 'west' };
          const isBreakSide = variant === 'break' && bSeat && sideToSeat[side] === bSeat;
          return (
          <div key={side} className={`mj-wall-side mj-wall-${side} ${isBreakSide ? 'is-break-side' : ''}`}>
            {Array.from({ length: 17 }).map((_, i) => {
              // For the break: count breakIdx stacks from the RIGHT end of the side.
              // In the DOM each .mj-wall-side goes left→right; "right end" = last stack (i=16).
              const isBroken = isBreakSide && i === 16 - breakIdx;
              const isBreakDead = isBreakSide && i > 16 - breakIdx;
              const isDealt = variant === 'deal' && side === 'top' && i >= 10;
              return (
                <div
                  key={i}
                  className={`mj-wall-stack ${isBroken ? 'is-break' : ''} ${isBreakDead ? 'is-dim' : ''} ${isDealt ? 'is-drawn' : ''}`}
                >
                  <div className="mj-wall-tile mj-wall-top-tile" />
                  <div className="mj-wall-tile mj-wall-bot-tile" />
                </div>
              );
            })}
          </div>
          );
        })}
        {variant === 'break' && showDirection !== false && (
          <>
            <div className="mj-dir-arrow mj-dir-arrow-top"><span className="mj-dir-arrow-label">北 N</span></div>
            <div className="mj-dir-arrow mj-dir-arrow-left"><span className="mj-dir-arrow-label">西 W</span></div>
            <div className="mj-dir-arrow mj-dir-arrow-bottom"><span className="mj-dir-arrow-label">南 S</span></div>
            <div className="mj-dir-arrow mj-dir-arrow-right"><span className="mj-dir-arrow-label">东 E</span></div>
          </>
        )}
        {showDirection && variant !== 'break' && (
          <>
            <div className="mj-dir-arrow mj-dir-arrow-top"><span className="mj-dir-arrow-label">北 N</span><span className="mj-dir-arrow-glyph">←</span></div>
            <div className="mj-dir-arrow mj-dir-arrow-left"><span className="mj-dir-arrow-glyph">↓</span><span className="mj-dir-arrow-label">西 W</span></div>
            <div className="mj-dir-arrow mj-dir-arrow-bottom"><span className="mj-dir-arrow-glyph">→</span><span className="mj-dir-arrow-label">南 S</span></div>
            <div className="mj-dir-arrow mj-dir-arrow-right"><span className="mj-dir-arrow-label">东 E</span><span className="mj-dir-arrow-glyph">↑</span></div>
          </>
        )}
      </div>
    </div>
  );

  const handFull = hand.length === MAX_HAND;

  return (
    <section id="section-draw" className="mj-section" data-screen-label="04 Draw">
      <div className="mj-section-head">
        <div className="mj-kicker">Section 03 · Opening the game</div>
        <h2 className="mj-h2">How do you draw tiles?</h2>
        <p className="mj-lede">
          Before the first turn, the 136 tiles become a <strong>square wall</strong> that shrinks as players draw from it. Here's the opening ritual — in four steps.
        </p>
      </div>

      {/* Dealer selection callout */}
      <div className="mj-dealer-card">
        <div className="mj-dealer-item">
          <div className="mj-dealer-item-h">Choosing the first dealer</div>
          <p>Each player rolls two dice. The highest total takes the <strong>East seat</strong> and becomes the first dealer. Ties re-roll between the tied players.</p>
        </div>
        <div className="mj-dealer-divider" />
        <div className="mj-dealer-item">
          <div className="mj-dealer-item-h">Dealer rotation</div>
          {variant === 'taiwan' ? (
            <p>Same as Hong Kong rules — the dealer keeps the East seat as long as they win. When any <em>other</em> player wins, the deal passes <strong>counter-clockwise</strong>. A drawn hand also keeps the dealer in place.</p>
          ) : (
            <p>The dealer keeps the East seat for as long as they keep winning. The moment any <em>other</em> player wins, the deal passes <strong>counter-clockwise</strong> — South becomes East, West becomes South, and so on. A drawn hand (荒庄) also keeps the dealer in place.</p>
          )}
        </div>
      </div>

      {/* 4-step walkthrough — all visible at once */}
      <div className="mj-draw-steps">
        <div className="mj-draw-step">
          <div className="mj-draw-step-num">1</div>
          <div className="mj-draw-step-content">
            <div className="mj-draw-step-title">Build the wall</div>
            <p>All 136 tiles are shuffled face-down and stacked two-high in a square. Each side is 17 stacks long — 17 × 2 × 4 = 136.</p>
          </div>
          <SmallWall variant="build" />
        </div>

        <div className="mj-draw-step">
          <div className="mj-draw-step-num">2</div>
          <div className="mj-draw-step-content">
            <div className="mj-draw-step-title">Break the wall</div>
            <p>The dealer rolls two dice. The <strong>total</strong> does two things at once — it picks whose wall to break, and how many stacks in from the right to break it.</p>

            <div className="mj-break-rules">
              <div className="mj-break-rule">
                <div className="mj-break-rule-h">① Whose wall?</div>
                <div className="mj-break-rule-p">Count the total <em>counter-clockwise</em> starting from the dealer (East = 1).</div>
                <div className="mj-break-map">
                  <div className={`mj-break-map-row ${breakSeat==='east'?'is-on':''}`}><span className="mj-break-map-seat"><em>东</em> East</span><span className="mj-break-map-nums">1 · 5 · 9</span></div>
                  <div className={`mj-break-map-row ${breakSeat==='south'?'is-on':''}`}><span className="mj-break-map-seat"><em>南</em> South</span><span className="mj-break-map-nums">2 · 6 · 10</span></div>
                  <div className={`mj-break-map-row ${breakSeat==='west'?'is-on':''}`}><span className="mj-break-map-seat"><em>西</em> West</span><span className="mj-break-map-nums">3 · 7 · 11</span></div>
                  <div className={`mj-break-map-row ${breakSeat==='north'?'is-on':''}`}><span className="mj-break-map-seat"><em>北</em> North</span><span className="mj-break-map-nums">4 · 8 · 12</span></div>
                </div>
              </div>
              <div className="mj-break-rule">
                <div className="mj-break-rule-h">② Where on it?</div>
                <div className="mj-break-rule-p">On that player's wall, count the same total in stacks from the <em>right end</em>. That's your break point. Tiles to the left are the live wall; to the right, the dead wall (kongs &amp; replacements).</div>
              </div>
            </div>

            <div className="mj-dice-row">
              <button className="mj-dice-btn" onClick={rollDice} disabled={rolling}>
                <DiceFace v={d1} /><DiceFace v={d2} />
                <span className="mj-dice-total">= {total}</span>
                <span className="mj-dice-reroll">{rolling ? 'rolling…' : '↻ roll'}</span>
              </button>
              <div className="mj-dice-explain">
                → {total} lands on <strong>{SEAT_META[breakSeat].en}</strong> <em>({SEAT_META[breakSeat].zh})</em>. Break at stack <strong>{total}</strong> from the right.
              </div>
            </div>
          </div>
          <SmallWall variant="break" breakSeat={breakSeat} breakIdx={breakStackFromRight} />
        </div>

        <div className="mj-draw-step">
          <div className="mj-draw-step-num">3</div>
          <div className="mj-draw-step-content">
            <div className="mj-draw-step-title">
              {variant === 'taiwan' ? 'Deal 16 to each player' : 'Deal 13 to each player'}
            </div>
            {variant === 'taiwan' ? (
              <p>Four tiles at a time until everyone has 16. The dealer draws first to hold 17. Any <strong>flower or season tile</strong> drawn during the deal is immediately revealed, set aside, and replaced from the dead wall — this can chain if the replacement is also a bonus tile.</p>
            ) : (
              <p>Starting with the dealer, players take tiles in <strong>counter-clockwise</strong> order (East → South → West → North). Four tiles at a time until everyone has 12, then one more each. The dealer takes 14.</p>
            )}
          </div>
          <SmallWall variant="deal" showDirection />
        </div>

        <div className="mj-draw-step">
          <div className="mj-draw-step-num">4</div>
          <div className="mj-draw-step-content">
            <div className="mj-draw-step-title">Draw on your turn</div>
            {variant === 'taiwan' ? (
              <p>Click a stack in the wall to draw the next tile. You now have 17 — discard one to return to 16. If you draw a flower or season tile, reveal it, set it aside, and draw a replacement instead. Play continues <strong>counter-clockwise</strong> (E → S → W → N).</p>
            ) : (
              <p>Click a stack in the wall to draw the next tile. You now have 14 — discard one to return to 13. Play continues <strong>counter-clockwise</strong> (E → S → W → N).</p>
            )}
            <div className="mj-draw-controls">
              <button className="mj-btn mj-btn-primary" onClick={doDraw} disabled={drawing || handFull}>
                {hand.length === 0 ? 'Start drawing' : !handFull ? `Draw tile ${hand.length + 1}` : 'Hand full'}
              </button>
              <button className="mj-btn" onClick={resetHand}>Reset</button>
            </div>
          </div>
          <div className={`mj-wall-mini variant-interactive`}>
            <div className="mj-wall-inner">
              {wallSides.map((side) => (
                <div key={side} className={`mj-wall-side mj-wall-${side}`}>
                  {Array.from({ length: 17 }).map((_, i) => {
                    const drawnCount = hand.length;
                    const isDrawn = side === 'top' && i >= 17 - Math.min(drawnCount, 17);
                    return (
                      <div
                        key={i}
                        className={`mj-wall-stack ${isDrawn ? 'is-drawn' : ''}`}
                        onClick={side === 'top' && !isDrawn ? doDraw : undefined}
                        style={{ cursor: side === 'top' && !isDrawn ? 'pointer' : 'default' }}
                      >
                        <div className="mj-wall-tile mj-wall-top-tile" />
                        <div className="mj-wall-tile mj-wall-bot-tile" />
                      </div>
                    );
                  })}
                </div>
              ))}
              <div className="mj-dir-arrow mj-dir-arrow-top"><span className="mj-dir-arrow-label">北 N</span><span className="mj-dir-arrow-glyph">←</span></div>
              <div className="mj-dir-arrow mj-dir-arrow-left"><span className="mj-dir-arrow-glyph">↓</span><span className="mj-dir-arrow-label">西 W</span></div>
              <div className="mj-dir-arrow mj-dir-arrow-bottom"><span className="mj-dir-arrow-glyph">→</span><span className="mj-dir-arrow-label">南 S</span></div>
              <div className="mj-dir-arrow mj-dir-arrow-right"><span className="mj-dir-arrow-label">东 E</span><span className="mj-dir-arrow-glyph">↑</span></div>
            </div>
          </div>
        </div>
      </div>

      {/* Your hand */}
      <div className="mj-your-hand">
        <div className="mj-hand-label">
          Your hand · <span className="mj-hand-count">{hand.length} / {MAX_HAND}</span>
          {handFull && <span className="mj-hand-discard-hint"> — tap a tile to discard</span>}
        </div>
        <div className={`mj-hand-row ${handFull ? 'is-discard-mode' : ''}`}>
          {hand.map((t, i) => (
            <div
              key={`${t}-${i}`}
              className={`mj-hand-tile-wrap ${handFull ? 'is-discardable' : ''}`}
              style={{ animation: !sorted && i === hand.length - 1 ? 'mjDrawIn 340ms cubic-bezier(.3,.7,.3,1)' : 'none' }}
              onClick={handFull ? () => discardTile(i) : undefined}
            >
              <Tile id={t} size="md" />
            </div>
          ))}
          {hand.length === 0 && (
            <div className="mj-hand-empty">Click a stack in the wall (step 4) to draw a tile →</div>
          )}
        </div>
      </div>

      {/* Simple list — re-done as per user request */}
      <ul className="mj-draw-list">
        <li><strong>Draw order.</strong> Counter-clockwise. East (the dealer) always starts.</li>
        <li><strong>Dead wall.</strong> The last 14 tiles are reserved for kongs and replacements.</li>
        <li><strong>Kong replacement.</strong> Declare a kong → draw one extra tile from the dead wall's end.</li>
        {variant === 'taiwan' && <li><strong>Flower replacement.</strong> Draw a flower or season tile → reveal it, set it aside face-up, and draw a replacement from the dead wall. Happens during the deal and on any subsequent draw.</li>}
        <li><strong>Exhausted wall.</strong> If the live wall runs out with no winner, it's a draw (黄庄 · huáng zhuāng).</li>
      </ul>
    </section>
  );
}

Object.assign(window, { SectionDraw });
