import * as bus from '../../../core/bus.js';
import * as scene from '../../../core/scene.js';
import * as audio from '../../../core/audio.js';
import * as store from '../../../core/store.js';
import { t } from '../../../core/i18n.js';
import { createCanvas, clear } from '../../../core/canvas.js';
import * as rules from '../logic/rules.js';

let state, tableCtx, tableCanvas, tableW, tableH;

const TABLE_COLOR = '#1B5E20';
const TABLE_FELT = '#2E7D32';
const TILE_BG = '#FFFFF0';
const TILE_BORDER = '#333';
const PIP_COLOR = '#111';

export function mountGame(el, params) {
  const { mode = 'bot', numPlayers = 2 } = params;
  scene.enterGameMode();

  const allTiles = rules.shuffle(rules.createDominoSet());
  const { hands, boneyard } = rules.dealHands(allTiles, numPlayers);

  state = {
    hands, boneyard, chain: [],
    leftEnd: null, rightEnd: null,
    currentPlayer: 0, numPlayers, mode,
    scores: new Array(numPlayers).fill(0),
    gameOver: false, selectedTile: null
  };

  el.innerHTML = `
    <div style="display:flex;flex-direction:column;height:100%;background:#0d3311;">
      <div style="display:flex;align-items:center;justify-content:space-between;padding:8px 12px;background:#0a2a0e;border-bottom:1px solid rgba(255,255,255,0.1);">
        <span id="domino-turn" style="font-size:13px;font-weight:600;color:#4CAF50;">${t('game.your_turn')}</span>
        <span style="font-size:14px;font-weight:700;color:#fff;">${t('game.domino')}</span>
      </div>
      <div style="display:flex;justify-content:space-between;padding:4px 12px;background:#0a2a0e;">
        <span style="font-size:11px;color:#81C784;">الخصم: <span id="opp-count">${hands[1]?.length || 0}</span> قطع</span>
        <span style="font-size:11px;color:#81C784;">المخزن: <span id="bone-count">${boneyard.length}</span></span>
      </div>
      <div id="domino-table" style="flex:1;display:flex;align-items:center;justify-content:center;padding:8px;overflow:hidden;"></div>
      <div id="domino-hand" style="display:flex;gap:6px;padding:10px 8px;overflow-x:auto;background:#0a2a0e;border-top:1px solid rgba(255,255,255,0.1);min-height:90px;align-items:center;justify-content:center;flex-wrap:wrap;"></div>
      <div style="display:flex;gap:8px;padding:8px 12px;background:#0a2a0e;">
        <button class="btn btn-secondary" id="domino-draw" style="flex:1;font-size:13px;background:#1B5E20;border-color:#388E3C;color:#fff;">سحب</button>
        <button class="btn btn-secondary" id="domino-pass" style="flex:1;font-size:13px;background:#1B5E20;border-color:#388E3C;color:#fff;">تمرير</button>
      </div>
    </div>
  `;

  // Setup table canvas
  const tableContainer = el.querySelector('#domino-table');
  tableW = tableContainer.clientWidth || 360;
  tableH = tableContainer.clientHeight || 300;
  const { canvas, ctx } = createCanvas(tableContainer, tableW, tableH);
  canvas.style.cssText = 'width:100%;height:100%;border-radius:8px;';
  tableCtx = ctx;
  tableCanvas = canvas;

  renderTable();
  renderHand(el);

  el.querySelector('#domino-draw').addEventListener('click', () => drawTile(el));
  el.querySelector('#domino-pass').addEventListener('click', () => passTurn(el));

  bus.emit('game:started', { gameKey: 'domino', mode });
}

function renderTable() {
  const ctx = tableCtx;
  clear(ctx, tableW, tableH);

  // Felt background
  ctx.fillStyle = TABLE_COLOR;
  ctx.fillRect(0, 0, tableW, tableH);
  // Subtle texture
  ctx.fillStyle = TABLE_FELT;
  for (let i = 0; i < tableW; i += 20) {
    for (let j = 0; j < tableH; j += 20) {
      if ((i + j) % 40 === 0) ctx.fillRect(i, j, 10, 10);
    }
  }

  // Draw chain
  if (state.chain.length === 0) {
    ctx.fillStyle = 'rgba(255,255,255,0.15)';
    ctx.font = '14px sans-serif';
    ctx.textAlign = 'center';
    ctx.fillText('ابدأ اللعب', tableW / 2, tableH / 2);
    return;
  }

  const tileW = 24;
  const tileH = 44;
  const gap = 2;
  const totalWidth = state.chain.length * (tileW + gap);
  let startX = Math.max(4, (tableW - totalWidth) / 2);
  const cy = tableH / 2;

  state.chain.forEach((tile, i) => {
    const x = startX + i * (tileW + gap);
    const y = cy - tileH / 2;
    drawTileOnTable(ctx, x, y, tileW, tileH, tile);
  });
}

function drawTileOnTable(ctx, x, y, w, h, tile) {
  // Tile background
  ctx.fillStyle = TILE_BG;
  ctx.strokeStyle = TILE_BORDER;
  ctx.lineWidth = 1;
  ctx.beginPath();
  ctx.roundRect(x, y, w, h, 3);
  ctx.fill();
  ctx.stroke();

  // Divider line
  ctx.beginPath();
  ctx.moveTo(x + 2, y + h / 2);
  ctx.lineTo(x + w - 2, y + h / 2);
  ctx.strokeStyle = '#999';
  ctx.lineWidth = 1;
  ctx.stroke();

  // Draw pips
  drawPips(ctx, x + w / 2, y + h / 4, w * 0.7, tile.left);
  drawPips(ctx, x + w / 2, y + h * 3 / 4, w * 0.7, tile.right);
}

function drawPips(ctx, cx, cy, size, value) {
  const r = size * 0.1;
  ctx.fillStyle = PIP_COLOR;
  const positions = getPipPositions(value, size * 0.3);

  positions.forEach(([dx, dy]) => {
    ctx.beginPath();
    ctx.arc(cx + dx, cy + dy, r, 0, Math.PI * 2);
    ctx.fill();
  });
}

function getPipPositions(value, spread) {
  switch (value) {
    case 0: return [];
    case 1: return [[0, 0]];
    case 2: return [[-spread, -spread], [spread, spread]];
    case 3: return [[-spread, -spread], [0, 0], [spread, spread]];
    case 4: return [[-spread, -spread], [spread, -spread], [-spread, spread], [spread, spread]];
    case 5: return [[-spread, -spread], [spread, -spread], [0, 0], [-spread, spread], [spread, spread]];
    case 6: return [[-spread, -spread], [spread, -spread], [-spread, 0], [spread, 0], [-spread, spread], [spread, spread]];
    default: return [];
  }
}

function renderHand(el) {
  const handEl = el.querySelector('#domino-hand');
  const hand = state.hands[0];
  const validMoves = state.chain.length === 0
    ? hand.map(t => ({ tile: t }))
    : rules.getValidMoves(hand, state.leftEnd, state.rightEnd);
  const validIds = new Set(validMoves.map(m => m.tile.id));

  handEl.innerHTML = hand.map(tile => {
    const playable = validIds.has(tile.id);
    const selected = state.selectedTile?.id === tile.id;
    return `
    <div class="domino-tile ${playable ? 'playable' : ''} ${selected ? 'selected' : ''}"
         data-id="${tile.id}"
         style="width:36px;height:64px;background:${TILE_BG};border:2px solid ${selected ? '#4CAF50' : playable ? '#81C784' : '#555'};border-radius:4px;display:flex;flex-direction:column;align-items:center;justify-content:space-around;padding:3px;cursor:${playable ? 'pointer' : 'default'};opacity:${playable ? '1' : '0.5'};transition:transform 0.15s;${selected ? 'transform:translateY(-6px);box-shadow:0 4px 12px rgba(76,175,80,0.4);' : ''}">
      <div style="display:flex;flex-wrap:wrap;width:20px;height:20px;align-items:center;justify-content:center;">
        ${renderPipDots(tile.left)}
      </div>
      <div style="width:80%;height:1px;background:#999;"></div>
      <div style="display:flex;flex-wrap:wrap;width:20px;height:20px;align-items:center;justify-content:center;">
        ${renderPipDots(tile.right)}
      </div>
    </div>`;
  }).join('');

  handEl.querySelectorAll('.domino-tile.playable').forEach(tileEl => {
    tileEl.addEventListener('click', () => {
      audio.play('click');
      const id = tileEl.dataset.id;
      const tile = hand.find(t => t.id === id);
      if (!tile) return;
      if (state.selectedTile?.id === id) {
        playTile(el, tile);
      } else {
        state.selectedTile = tile;
        renderHand(el);
      }
    });
  });
}

function renderPipDots(value) {
  if (value === 0) return '';
  let dots = '';
  for (let i = 0; i < value; i++) {
    dots += '<div style="width:4px;height:4px;border-radius:50%;background:#111;margin:1px;"></div>';
  }
  return dots;
}

function playTile(el, tile) {
  if (state.currentPlayer !== 0 || state.gameOver) return;

  const validMoves = rules.getValidMoves([tile], state.leftEnd, state.rightEnd);
  if (validMoves.length === 0) return;

  const end = validMoves[0].end;
  const result = rules.placeTile(state.chain, tile, end === 'first' ? 'right' : end);
  state.chain = result.chain;
  state.leftEnd = result.leftEnd;
  state.rightEnd = result.rightEnd;

  state.hands[0] = state.hands[0].filter(t => t.id !== tile.id);
  state.selectedTile = null;
  audio.play('place', 'game');

  if (state.hands[0].length === 0 || rules.checkRoundEnd(state.hands, state.boneyard, state.chain)) {
    endRound(el); return;
  }

  nextTurn(el);
}

function drawTile(el) {
  if (state.currentPlayer !== 0 || state.boneyard.length === 0) return;
  const tile = state.boneyard.pop();
  state.hands[0].push(tile);
  audio.play('click');
  el.querySelector('#bone-count').textContent = state.boneyard.length;
  renderHand(el);
}

function passTurn(el) {
  if (state.currentPlayer !== 0) return;
  nextTurn(el);
}

function nextTurn(el) {
  state.currentPlayer = (state.currentPlayer + 1) % state.numPlayers;
  const turnEl = el.querySelector('#domino-turn');

  if (state.currentPlayer === 0) {
    turnEl.textContent = t('game.your_turn');
    turnEl.style.color = '#4CAF50';
    renderHand(el);
  } else {
    turnEl.textContent = t('game.opponent_turn');
    turnEl.style.color = '#81C784';
    setTimeout(() => botTurn(el), 800);
  }
  renderTable();
}

function botTurn(el) {
  if (state.gameOver) return;
  const hand = state.hands[state.currentPlayer];
  const validMoves = rules.getValidMoves(hand, state.leftEnd, state.rightEnd);

  if (validMoves.length === 0) {
    if (state.boneyard.length > 0) {
      hand.push(state.boneyard.pop());
      el.querySelector('#bone-count').textContent = state.boneyard.length;
      setTimeout(() => botTurn(el), 400);
      return;
    }
    nextTurn(el); return;
  }

  const move = validMoves[Math.floor(Math.random() * validMoves.length)];
  const result = rules.placeTile(state.chain, move.tile, move.end === 'first' ? 'right' : move.end);
  state.chain = result.chain;
  state.leftEnd = result.leftEnd;
  state.rightEnd = result.rightEnd;
  state.hands[state.currentPlayer] = hand.filter(t => t.id !== move.tile.id);
  audio.play('place', 'game');

  el.querySelector('#opp-count').textContent = state.hands[1]?.length || 0;

  if (state.hands[state.currentPlayer].length === 0 || rules.checkRoundEnd(state.hands, state.boneyard, state.chain)) {
    endRound(el); return;
  }
  nextTurn(el);
}

function endRound(el) {
  state.gameOver = true;
  const { winner, scores } = rules.getRoundWinner(state.hands);
  const result = winner === 0 ? 'win' : 'loss';
  audio.play(result === 'win' ? 'win' : 'lose', 'game');

  setTimeout(() => {
    scene.exitGameMode();
    scene.replace('domino-result', { result, scores, mode: state.mode });
    bus.emit('game:ended', { gameKey: 'domino', result, mode: state.mode });
  }, 1000);
}
