// MODIBU - Board (40 tiles + center panel)

const { useState: useStateB, useEffect: useEffectB, useMemo: useMemoB, useRef: useRefB } = React;

// Map tile index → grid position (row, col) on 11x11 grid
// Map tile index → grid position (row, col) on 9x9 grid (32 tiles)
function tileGridPosition(i) {
  // Bottom row: i = 0..8 → row 9, col = 9 - i
  if (i <= 8) return { row: 9, col: 9 - i };
  // Left col: i = 9..15 → col 1, row = 17 - i
  if (i <= 15) return { row: 17 - i, col: 1 };
  // Top row: i = 16..24 → row 1, col = i - 15
  if (i <= 24) return { row: 1, col: i - 15 };
  // Right col: i = 25..31 → col 9, row = i - 23
  return { row: i - 23, col: 9 };
}

function tileRotation(i) {
  if (i <= 8) return 0;
  if (i <= 15) return 90;
  if (i <= 24) return 180;
  return 270;
}

// Group label color per type
const TYPE_INFO = {
  edukasi: { bg: 'var(--c-edukasi)', deep: 'var(--c-edukasi-deep)', short: 'EDUKASI' },
  fakta: { bg: 'var(--c-fakta)', deep: 'var(--c-fakta-deep)', short: 'FAKTA' },
  tantangan: { bg: 'var(--c-tantangan)', deep: 'var(--c-tantangan-deep)', short: 'TANTANGAN' },
  refleksi: { bg: 'var(--c-refleksi)', deep: 'var(--c-refleksi-deep)', short: 'REFLEKSI' },
  kesempatan: { bg: 'var(--c-kesempatan)', deep: 'var(--c-kesempatan-deep)', short: 'KESEMPATAN' },
  hukuman: { bg: 'var(--c-hukuman)', deep: 'var(--c-hukuman-deep)', short: 'HUKUMAN' },
  start: { bg: 'var(--c-start)', deep: 'var(--c-start-deep)', short: 'START' },
  finish: { bg: 'var(--c-finish)', deep: 'var(--c-finish-deep)', short: 'FINISH' },
  penjara: { bg: '#495057', deep: '#212529', short: 'PENJARA' },
  bonus: { bg: '#FAB005', deep: '#F08C00', short: 'BONUS' },
};

function BoardTile({ tile, players, isCurrent }) {
  const info = TYPE_INFO[tile.type] || TYPE_INFO.edukasi;

  const isStart = tile.i === 0;
  const isCorner = [0, 8, 16, 24].includes(tile.i);
  const cornerTile = isCorner;

  // Pawn slots on tile
  const here = (players || []).filter(p => p && p.position === tile.i);

  return (
    <div
      className="tile"
      style={{
        background: info.bg,
        gridRow: tileGridPosition(tile.i).row,
        gridColumn: tileGridPosition(tile.i).col,
        borderRadius: cornerTile ? '18px' : '8px',
        transform: cornerTile ? 'scale(1.1)' : 'none',
        zIndex: cornerTile ? 10 : 1,
        boxShadow: isCurrent
          ? '0 0 0 4px #FFA94D, 0 8px 20px rgba(0,0,0,0.22)'
          : cornerTile 
            ? '0 4px 12px rgba(0,0,0,0.12)' 
            : '0 2px 4px rgba(0,0,0,0.08)',
        position: 'relative',
        outline: isCurrent ? '3px solid white' : 'none',
        outlineOffset: isCurrent ? '-3px' : 0,
        containerType: 'inline-size',
      }}
    >
      <TilePattern />

      {/* Header strip - category */}
      {/* Price at Top */}
      {!cornerTile && tile.price && (
        <div className="tile-price-top">
          {tile.price}
        </div>
      )}

      {/* Body */}
      <div style={{
        flex: 1,
        display: 'flex',
        flexDirection: 'column',
        alignItems: 'center',
        justifyContent: cornerTile ? 'center' : 'space-between',
        padding: '2px 1px',
        gap: 2,
        position: 'relative',
        zIndex: 1,
        width: '100%',
      }}>
        {cornerTile ? (
          <CornerArt tile={tile} info={info} />
        ) : (
          <>
            <div style={{
              width: '48cqi',
              height: '48cqi',
              maxWidth: 36, maxHeight: 36,
              minWidth: 18, minHeight: 18,
              borderRadius: '50%',
              background: 'rgba(255,255,255,0.4)',
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              border: '2px solid rgba(255,255,255,0.65)',
              marginTop: 4,
              boxShadow: '0 2px 8px rgba(0,0,0,0.06)'
            }}>
              <TileIcon type={tile.type} size="80%" customIcon={tile.icon} />
            </div>
            {/* Category at Bottom */}
            {!cornerTile && (
              <div className="tile-cat-bottom" style={{ '--cat-deep': info.deep }}>
                {info.short}
              </div>
            )}
          </>
        )}
      </div>

      {/* Position number (Very Small & Subtle) */}
      <div style={{
        position: 'absolute',
        top: 0, left: 0,
        background: 'rgba(0,0,0,0.4)',
        padding: '2px 5px',
        borderRadius: '0 0 10px 0',
        fontFamily: 'Fredoka', fontWeight: 700,
        fontSize: 'clamp(9px, 14cqi, 14px)',
        color: 'white',
        zIndex: 3,
        lineHeight: 1,
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        backdropFilter: 'blur(2px)',
      }}>
        {tile.i}
      </div>

      {here.length > 0 && (
        <div style={{
          position: 'absolute',
          bottom: cornerTile ? '16%' : 4,
          left: '50%',
          transform: 'translateX(-50%)',
          display: 'grid',
          gridTemplateColumns: here.length > 1 ? 'repeat(2, auto)' : 'auto',
          gap: 'clamp(2px, 1cqi, 6px)',
          justifyContent: 'center',
          alignItems: 'center',
          zIndex: 3,
          pointerEvents: 'none',
        }}>
          {here.map((p) => (
            <div key={p.id} style={{
              transform: `scale(${cornerTile ? 0.55 : 0.75})`,
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              width: '32px',
              height: '28px',
              position: 'relative'
            }}>
              <Pawn color={p.color} icon={p.icon} />
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

function CornerArt({ tile, info }) {
  // Custom images for corners 8, 16, 24
  if (tile.i === 8) {
    return (
      <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 4, justifyContent: 'center', height: '100%' }}>
        <img src="/shock.png" style={{ width: '60%', height: 'auto', objectFit: 'contain' }} alt="Hukuman" />
        <div className="font-display-b" style={{ fontSize: 'clamp(7px, 11cqi, 12px)', color: 'white', textShadow: '0 1px 0 rgba(0,0,0,0.2)' }}>HUKUMAN</div>
      </div>
    );
  }
  if (tile.i === 16) {
    return (
      <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 4, justifyContent: 'center', height: '100%' }}>
        <img src="/not-accept.png" style={{ width: '60%', height: 'auto', objectFit: 'contain' }} alt="Penjara" />
        <div className="font-display-b" style={{ fontSize: 'clamp(7px, 11cqi, 12px)', color: 'white', textShadow: '0 1px 0 rgba(0,0,0,0.2)' }}>PENJARA</div>
      </div>
    );
  }
  if (tile.i === 24) {
    return (
      <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 4, justifyContent: 'center', height: '100%' }}>
        <img src="/target.png" style={{ width: '60%', height: 'auto', objectFit: 'contain' }} alt="Edukasi" />
        <div className="font-display-b" style={{ fontSize: 'clamp(7px, 11cqi, 12px)', color: 'white', textShadow: '0 1px 0 rgba(0,0,0,0.2)' }}>EDUKASI</div>
      </div>
    );
  }

  if (tile.type === 'start') {
    return (
      <div style={{
        display: 'flex', flexDirection: 'column', alignItems: 'center',
        gap: 2, justifyContent: 'center', height: '100%',
      }}>
        <svg width="45%" height="45%" viewBox="0 0 24 24" fill="white">
          <polygon points="5,3 21,12 5,21" />
        </svg>
        <div className="font-display-b" style={{
          fontSize: 'clamp(8px, 12cqi, 13px)', color: 'white', textShadow: '0 1px 0 rgba(0,0,0,0.18)',
        }}>START</div>
      </div>
    );
  }

  // Fallback for other corners if any
  return (
    <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 2, justifyContent: 'center', height: '100%' }}>
       <div className="font-display-b" style={{ fontSize: 'clamp(8px, 11cqi, 12px)', color: 'white', textShadow: '0 1px 0 rgba(0,0,0,0.18)', textAlign: 'center' }}>{tile.label}</div>
    </div>
  );
}

function Board({ players = [], currentTurnIdx = 0, diceValue, diceValues, isRolling, isAnimating, onRoll, onPause, onHelp, sessionCode, round, onEndGame, onOpenGuru }) {
  const tiles = BOARD_TILES;
  const safePlayers = Array.isArray(players) ? players : [];
  const currentPlayer = safePlayers[currentTurnIdx] || safePlayers[0] || { name: '...', color: 'gray', stats: {} };
  const d = diceValues || [diceValue || 1, diceValue || 1];

  return (
    <div className="board-wrap" style={{
      width: 'min(96vw, calc(100vh - 80px))',
      maxWidth: 1400,
      margin: '0 auto',
      position: 'relative',
    }}>
      <div className="board" style={{
        display: 'grid',
        gridTemplateColumns: 'repeat(9, 1fr)',
        gridTemplateRows: 'repeat(9, 1fr)',
        gap: 2,
        aspectRatio: '1 / 1',
        background: 'linear-gradient(135deg, #E3F5FD 0%, #BDE8F9 100%)',
        padding: 10,
        borderRadius: 28,
        border: '4px solid white',
        boxShadow: '0 12px 36px rgba(20,50,80,0.18)',
        position: 'relative',
      }}>
        {tiles.map(t => (
          <BoardTile key={t.i} tile={t} players={safePlayers} isCurrent={currentPlayer && t.i === currentPlayer.position} />
        ))}

        <div style={{
          gridRow: '2 / 9', gridColumn: '2 / 9',
          background: '#E3F5FD',
          borderRadius: 16, padding: '2.2cqi',
          display: 'flex', flexDirection: 'column', gap: 12,
          alignItems: 'center', justifyContent: 'center',
          position: 'relative', containerType: 'size',
        }}>
          <BoardCenter
            players={players} currentTurnIdx={currentTurnIdx}
            diceValues={d} isRolling={isRolling} isAnimating={isAnimating}
            onRoll={onRoll} sessionCode={sessionCode} round={round}
          />
        </div>
      </div>

      {/* Action Sidebar - Forced outside to the right of the board */}
      <div style={{
        position: 'absolute',
        top: 0,
        left: 'calc(100% + 20px)', // Forces it outside to the right
        display: 'flex',
        flexDirection: 'column',
        gap: 12,
        zIndex: 100,
      }}>
        <button className="icon-btn pink" onClick={onHelp} title="Tips & Materi" style={{ width: 52, height: 52, fontSize: 24, boxShadow: '0 4px 12px rgba(255,107,107,0.3)' }}>💡</button>
        {onPause && <button className="icon-btn orange" onClick={onPause} title="Kembali ke Beranda" style={{ width: 52, height: 52, fontSize: 24, boxShadow: '0 4px 12px rgba(255,169,77,0.3)' }}>🏠</button>}
        {onOpenGuru && <button className="icon-btn blue" onClick={onOpenGuru} title="Panel Guru BK" style={{ width: 52, height: 52, fontSize: 24, boxShadow: '0 4px 12px rgba(77,171,247,0.3)' }}>🎓</button>}
        {onEndGame && <button className="icon-btn" onClick={onEndGame} title="Akhiri Sesi" style={{ width: 52, height: 52, fontSize: 24, background: '#FF6B6B', boxShadow: '0 4px 12px rgba(255,107,107,0.3)' }}>⛔</button>}
      </div>
    </div>
  );
}

function BoardCenter({ players = [], currentTurnIdx = 0, diceValues, isRolling, isAnimating, onRoll, sessionCode, round }) {
  const currentPlayer = players[currentTurnIdx] || players[0] || { name: '...', color: 'gray', stats: {} };
  const isDouble = diceValues && diceValues[0] === diceValues[1] && !isRolling;
  return (
    <div style={{
      width: '100%', height: '100%',
      display: 'flex', flexDirection: 'column',
      justifyContent: 'space-between',
      gap: 'clamp(6px, 1.2cqh, 14px)',
    }}>
      <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 12, flex: 1 }}>
        <img src="/modibu-image.png" alt="Illustration" style={{
          height: 'clamp(140px, 45cqh, 280px)',
          width: 'auto',
          objectFit: 'contain'
        }} />
        
        <span className="chip" style={{ background: 'white', fontSize: 'clamp(8px, 1.6cqh, 12px)', padding: '4px 12px', boxShadow: '0 2px 8px rgba(0,0,0,0.05)', border: '2px solid rgba(0,0,0,0.03)' }}>
          <span className="chip-dot" style={{ background: '#51CF66', width: 6, height: 6 }} />
          Ronde {round || 1} · {sessionCode}
        </span>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 'clamp(4px, 1cqh, 10px)' }}>
        {players.map((p, idx) => (
          <PlayerPanel key={p.id} player={p} active={idx === currentTurnIdx} />
        ))}
      </div>

      <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 'clamp(4px, 1cqh, 10px)' }}>
        <div style={{ display: 'flex', gap: 'clamp(4px, 1.2cqh, 12px)' }}>
          <Dice value={diceValues[0]} rolling={isRolling} size="clamp(36px, 8cqh, 64px)" />
          <Dice value={diceValues[1]} rolling={isRolling} size="clamp(36px, 8cqh, 64px)" />
        </div>
        {isDouble && <div style={{ fontFamily: 'Fredoka', fontWeight: 700, fontSize: 'clamp(10px, 1.8cqh, 14px)', color: '#E8852C' }}>🎯 DOUBLE! Giliran ekstra!</div>}
        <button className="btn btn-primary" onClick={onRoll} disabled={isRolling} style={{
          padding: 'clamp(7px, 1.4cqh, 12px) clamp(14px, 3cqh, 26px)',
          fontSize: 'clamp(12px, 2.4cqh, 17px)',
        }}>
          {currentPlayer?.isInJail ? '🔓 Keluar Penjara' : currentPlayer?.skipTurn ? '⏭ Skip Giliran' : isRolling ? 'Mengocok…' : isAnimating ? 'Berjalan…' : '🎲 Lempar Dadu'}
        </button>
        <div style={{
          fontSize: 'clamp(14px, 2.6cqh, 20px)',
          color: 'var(--ink)',
          fontFamily: 'Fredoka',
          fontWeight: 700,
          display: 'flex',
          alignItems: 'center',
          gap: 10,
          background: 'rgba(255,255,255,0.5)',
          padding: '6px 16px',
          borderRadius: 999,
          border: '2px solid rgba(0,0,0,0.05)',
          marginTop: 4
        }}>
          Giliran: <Avatar color={currentPlayer?.color || 'gray'} label={currentPlayer?.icon} size={28} active={true} /> <span style={{ color: (currentPlayer?.color === 'yellow' ? '#E8852C' : currentPlayer?.color) || 'inherit' }}>{currentPlayer?.name || '...'}</span>
        </div>
      </div>
    </div>
  );
}

function PlayerPanel({ player, active }) {
  return (
    <div style={{
      background: active ? 'white' : 'rgba(255,255,255,0.7)',
      borderRadius: 14,
      padding: 'clamp(4px, 0.8cqh, 8px)',
      display: 'flex',
      alignItems: 'center',
      gap: 'clamp(4px, 1cqh, 8px)',
      border: active ? `2px solid var(--c-start)` : '2px solid transparent',
      boxShadow: active ? '0 3px 8px rgba(255,169,77,0.25)' : '0 2px 4px rgba(0,0,0,0.04)',
      transition: 'all 0.2s',
      minWidth: 0,
    }}>
      <Avatar
        color={player.color}
        label={player.icon}
        size="clamp(36px, 6cqh, 56px)"
        active={active}
      />
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{
          fontFamily: 'Fredoka', fontWeight: 600,
          fontSize: 'clamp(12px, 2cqh, 16px)',
          color: 'var(--ink)',
          overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
        }}>
          {player.name}
        </div>
        <div style={{ display: 'flex', alignItems: 'baseline', gap: 3 }}>
          <span style={{
            fontFamily: 'Fredoka', fontWeight: 700,
            fontSize: 'clamp(16px, 3cqh, 24px)',
            color: 'var(--ink)',
            lineHeight: 1,
          }}>
            {player.score}
          </span>
          <span style={{
            fontSize: 'clamp(10px, 1.5cqh, 13px)',
            color: 'var(--ink-soft)', fontWeight: 600,
          }}>poin</span>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, {
  Board, BoardCenter, BoardTile, TYPE_INFO,
});
