var LudoUI = (function() {
  'use strict';

  var C = LudoConstants;
  var boardEl = null;
  var piecesEl = null;
  var diceEl = null;
  var rollBtn = null;
  var turnEl = null;
  var logEl = null;
  var pieceElements = {};
  var playerCards = {};

  // Which cells belong to the main path (0-51)
  // Map position number to grid [col, row] from COORDINATES_MAP
  function getPathCells() {
    var cells = [];
    for (var i = 0; i <= 51; i++) {
      cells.push({ pos: i, col: C.COORDINATES_MAP[i][0], row: C.COORDINATES_MAP[i][1] });
    }
    return cells;
  }

  function getHomeEntranceCells() {
    var cells = [];
    var players = ['P1', 'P2', 'P3', 'P4'];
    players.forEach(function(p) {
      C.HOME_ENTRANCE[p].forEach(function(pos) {
        cells.push({ pos: pos, col: C.COORDINATES_MAP[pos][0], row: C.COORDINATES_MAP[pos][1], player: p });
      });
      // Home final cell
      var homePos = C.HOME_POSITIONS[p];
      cells.push({ pos: homePos, col: C.COORDINATES_MAP[homePos][0], row: C.COORDINATES_MAP[homePos][1], player: p });
    });
    return cells;
  }

  function renderBoard(containerSelector) {
    var container = document.querySelector(containerSelector);
    if (!container) return;

    container.innerHTML = '';
    container.classList.add('ludo-board');

    // Render corner bases
    ['P1', 'P2', 'P3', 'P4'].forEach(function(p) {
      var base = document.createElement('div');
      base.className = 'ludo-base ludo-base--' + p.toLowerCase();
      base.dataset.player = p;

      var inner = document.createElement('div');
      inner.className = 'ludo-base-inner';
      for (var i = 0; i < 4; i++) {
        var slot = document.createElement('div');
        slot.className = 'ludo-base-slot';
        inner.appendChild(slot);
      }
      base.appendChild(inner);
      container.appendChild(base);
    });

    // Render path cells
    var pathCells = getPathCells();
    pathCells.forEach(function(cell) {
      var el = document.createElement('div');
      el.className = 'ludo-cell';
      el.dataset.pos = cell.pos;
      el.style.gridColumn = (cell.col + 1).toString();
      el.style.gridRow = (cell.row + 1).toString();

      // Mark safe positions
      if (C.SAFE_POSITIONS.indexOf(cell.pos) !== -1) {
        el.classList.add('ludo-cell--safe');
      }

      // Mark start positions with player color
      if (cell.pos === C.START_POSITIONS.P1) el.classList.add('ludo-cell--start-p1');
      else if (cell.pos === C.START_POSITIONS.P2) el.classList.add('ludo-cell--start-p2');
      else if (cell.pos === C.START_POSITIONS.P3) el.classList.add('ludo-cell--start-p3');
      else if (cell.pos === C.START_POSITIONS.P4) el.classList.add('ludo-cell--start-p4');

      container.appendChild(el);
    });

    // Render home entrance cells
    var homeCells = getHomeEntranceCells();
    homeCells.forEach(function(cell) {
      var el = document.createElement('div');
      el.className = 'ludo-cell ludo-cell--home-' + cell.player.toLowerCase();
      el.dataset.pos = cell.pos;
      el.style.gridColumn = (cell.col + 1).toString();
      el.style.gridRow = (cell.row + 1).toString();
      container.appendChild(el);
    });

    // Center home area
    var center = document.createElement('div');
    center.className = 'ludo-center';
    ['p1', 'p2', 'p3', 'p4'].forEach(function(p) {
      var tri = document.createElement('div');
      tri.className = 'ludo-center-triangle ludo-center-triangle--' + p;
      center.appendChild(tri);
    });
    container.appendChild(center);

    // Pieces container (absolute overlay)
    piecesEl = document.createElement('div');
    piecesEl.className = 'ludo-pieces';
    container.parentElement.appendChild(piecesEl);

    boardEl = container;
  }

  function renderPieces(activePlayers) {
    if (!piecesEl) return;
    piecesEl.innerHTML = '';
    pieceElements = {};

    activePlayers.forEach(function(player) {
      pieceElements[player] = [];
      for (var i = 0; i < 4; i++) {
        var piece = document.createElement('div');
        piece.className = 'ludo-piece ludo-piece--' + player.toLowerCase();
        piece.dataset.player = player;
        piece.dataset.piece = i;
        piecesEl.appendChild(piece);
        pieceElements[player].push(piece);
      }
    });
  }

  function setPiecePosition(player, piece, position) {
    if (!pieceElements[player] || !pieceElements[player][piece]) return;

    var coords = C.COORDINATES_MAP[position];
    if (!coords) return;

    var el = pieceElements[player][piece];
    var halfStep = C.STEP_LENGTH / 2;
    el.style.top = (coords[1] * C.STEP_LENGTH + halfStep) + '%';
    el.style.left = (coords[0] * C.STEP_LENGTH + halfStep) + '%';

    // Bounce on landing
    el.classList.remove('ludo-piece--landed');
    void el.offsetWidth;
    el.classList.add('ludo-piece--landed');
    setTimeout(function() { el.classList.remove('ludo-piece--landed'); }, 400);

    // Mark as home if reached final
    if (position === C.HOME_POSITIONS[player]) {
      el.classList.add('ludo-piece--home');
    } else {
      el.classList.remove('ludo-piece--home');
    }
  }

  function highlightPieces(player, pieces) {
    pieces.forEach(function(pieceIdx) {
      if (pieceElements[player] && pieceElements[player][pieceIdx]) {
        pieceElements[player][pieceIdx].classList.add('ludo-piece--highlight');
      }
    });
  }

  function unhighlightPieces() {
    var all = piecesEl ? piecesEl.querySelectorAll('.ludo-piece--highlight') : [];
    all.forEach(function(el) { el.classList.remove('ludo-piece--highlight'); });
  }

  function updateStacking(positions, activePlayers) {
    // Reset stacking
    activePlayers.forEach(function(p) {
      for (var i = 0; i < 4; i++) {
        if (pieceElements[p] && pieceElements[p][i]) {
          pieceElements[p][i].removeAttribute('data-stack');
        }
      }
    });

    // Find pieces on same position
    var posMap = {};
    activePlayers.forEach(function(p) {
      positions[p].forEach(function(pos, idx) {
        var key = String(pos);
        if (!posMap[key]) posMap[key] = [];
        posMap[key].push({ player: p, piece: idx });
      });
    });

    Object.keys(posMap).forEach(function(key) {
      if (posMap[key].length > 1) {
        posMap[key].forEach(function(item, stackIdx) {
          if (stackIdx > 0 && pieceElements[item.player] && pieceElements[item.player][item.piece]) {
            pieceElements[item.player][item.piece].dataset.stack = stackIdx;
          }
        });
      }
    });
  }

  function renderDice(containerSelector) {
    var container = containerSelector ? document.querySelector(containerSelector) : null;
    if (!container) return;

    var area = document.createElement('div');
    area.className = 'ludo-dice-area';

    diceEl = document.createElement('div');
    diceEl.className = 'ludo-dice';
    diceEl.id = 'ludo-dice';

    for (var i = 0; i < 9; i++) {
      var dot = document.createElement('div');
      dot.className = 'ludo-dice-dot';
      dot.dataset.dot = i;
      diceEl.appendChild(dot);
    }

    rollBtn = document.createElement('button');
    rollBtn.className = 'ludo-roll-btn';
    rollBtn.id = 'ludo-roll-btn';
    rollBtn.textContent = 'ارمِ النرد';

    area.appendChild(diceEl);
    area.appendChild(rollBtn);
    container.appendChild(area);
  }

  function setDiceValue(value) {
    if (!diceEl) return;
    var dots = diceEl.querySelectorAll('.ludo-dice-dot');
    dots.forEach(function(d) { d.classList.remove('ludo-dice-dot--visible'); });

    if (value >= 1 && value <= 6) {
      var pattern = C.DICE_FACES[value];
      pattern.forEach(function(idx) {
        dots[idx].classList.add('ludo-dice-dot--visible');
      });
    }
  }

  function animateDiceRoll(finalValue, callback) {
    if (!diceEl) { if (callback) callback(); return; }

    diceEl.classList.add('ludo-dice--rolling');
    var count = 0;
    var interval = setInterval(function() {
      setDiceValue(1 + Math.floor(Math.random() * 6));
      count++;
      if (count >= 8) {
        clearInterval(interval);
        diceEl.classList.remove('ludo-dice--rolling');
        setDiceValue(finalValue);
        if (callback) callback();
      }
    }, 80);
  }

  function enableDice() {
    if (rollBtn) rollBtn.removeAttribute('disabled');
  }

  function disableDice() {
    if (rollBtn) rollBtn.setAttribute('disabled', '');
  }

  function listenDiceClick(callback) {
    if (rollBtn) rollBtn.addEventListener('click', callback);
  }

  function listenPieceClick(callback) {
    if (piecesEl) piecesEl.addEventListener('click', callback);
  }

  function setTurn(player, label) {
    // Update turn indicator
    if (turnEl) {
      turnEl.innerHTML = '<span style="color:var(--ludo-' + player.toLowerCase() + ')">' + (label || C.PLAYER_LABELS[player]) + '</span>';
    }

    // Update player cards
    Object.keys(playerCards).forEach(function(p) {
      if (playerCards[p]) {
        playerCards[p].classList.toggle('active', p === player);
      }
    });
  }

  function renderPlayerCards(containerTop, containerBottom, activePlayers, playerNames) {
    playerCards = {};

    // Top row: P2, P3 (or whoever is across)
    // Bottom row: P1, P4 (or whoever is player's side)
    var topPlayers = activePlayers.filter(function(p) { return p === 'P2' || p === 'P3'; });
    var bottomPlayers = activePlayers.filter(function(p) { return p === 'P1' || p === 'P4'; });

    function makeCard(player) {
      var card = document.createElement('div');
      card.className = 'ludo-player-card';
      card.dataset.player = player;

      var dot = document.createElement('div');
      dot.className = 'ludo-player-dot ludo-player-dot--' + player.toLowerCase();

      var name = document.createElement('span');
      name.className = 'ludo-player-name';
      name.textContent = playerNames[player] || C.PLAYER_LABELS[player];

      var status = document.createElement('span');
      status.className = 'ludo-player-status';

      card.appendChild(dot);
      card.appendChild(name);
      card.appendChild(status);
      playerCards[player] = card;
      return card;
    }

    if (containerTop) {
      containerTop.innerHTML = '';
      topPlayers.forEach(function(p) { containerTop.appendChild(makeCard(p)); });
    }
    if (containerBottom) {
      containerBottom.innerHTML = '';
      bottomPlayers.forEach(function(p) { containerBottom.appendChild(makeCard(p)); });
    }
  }

  function setPlayerFinished(player) {
    if (playerCards[player]) {
      playerCards[player].classList.add('finished');
      var status = playerCards[player].querySelector('.ludo-player-status');
      if (status) status.textContent = '✔';
    }
  }

  function showResult(title, subtitle) {
    if (!boardEl || !boardEl.parentElement) return;

    var existing = boardEl.parentElement.querySelector('.ludo-result');
    if (existing) existing.remove();

    var overlay = document.createElement('div');
    overlay.className = 'ludo-result';

    overlay.innerHTML = '<div class="ludo-result-title">' + title + '</div>' +
      '<div class="ludo-result-subtitle">' + subtitle + '</div>' +
      '<div class="ludo-result-actions">' +
      '<button class="btn btn-gold" id="ludo-play-again">العب مرة تانية</button>' +
      '<button class="btn btn-ghost" onclick="window.location.href=\'/ludo\'">القائمة</button>' +
      '</div>';

    boardEl.parentElement.appendChild(overlay);
  }

  function hideResult() {
    if (!boardEl || !boardEl.parentElement) return;
    var overlay = boardEl.parentElement.querySelector('.ludo-result');
    if (overlay) overlay.remove();
  }

  function addLogEntry(text) {
    if (!logEl) return;
    var entry = document.createElement('div');
    entry.className = 'ludo-log-entry';
    entry.textContent = text;
    logEl.appendChild(entry);
    logEl.scrollTop = logEl.scrollHeight;
  }

  function clearLog() {
    if (logEl) logEl.innerHTML = '';
  }

  function captureExplosion(player, position) {
    if (!piecesEl) return;
    var coords = C.COORDINATES_MAP[position];
    if (!coords) return;
    var halfStep = C.STEP_LENGTH / 2;
    var colors = { 0: '#E53935', 1: '#43A047', 2: '#FDD835', 3: '#1E88E5' };
    var color = colors[player] || '#fff';
    for (var i = 0; i < 10; i++) {
      var p = document.createElement('span');
      p.className = 'ludo-capture-particle';
      p.style.top = (coords[1] * C.STEP_LENGTH + halfStep) + '%';
      p.style.left = (coords[0] * C.STEP_LENGTH + halfStep) + '%';
      p.style.background = color;
      var angle = (Math.PI * 2 / 10) * i;
      var dist = 20 + Math.random() * 15;
      p.style.setProperty('--px', Math.cos(angle) * dist + 'px');
      p.style.setProperty('--py', Math.sin(angle) * dist + 'px');
      piecesEl.appendChild(p);
      setTimeout(function(el) { el.remove(); }, 700, p);
    }
    if (typeof App !== 'undefined' && App.playSound) App.playSound('capture');
  }

  function setTurnElement(el) { turnEl = el; }
  function setLogElement(el) { logEl = el; }

  return {
    renderBoard: renderBoard,
    renderPieces: renderPieces,
    renderDice: renderDice,
    renderPlayerCards: renderPlayerCards,
    setPiecePosition: setPiecePosition,
    highlightPieces: highlightPieces,
    unhighlightPieces: unhighlightPieces,
    updateStacking: updateStacking,
    setDiceValue: setDiceValue,
    animateDiceRoll: animateDiceRoll,
    enableDice: enableDice,
    disableDice: disableDice,
    listenDiceClick: listenDiceClick,
    listenPieceClick: listenPieceClick,
    setTurn: setTurn,
    setPlayerFinished: setPlayerFinished,
    showResult: showResult,
    hideResult: hideResult,
    addLogEntry: addLogEntry,
    clearLog: clearLog,
    captureExplosion: captureExplosion,
    setTurnElement: setTurnElement,
    setLogElement: setLogElement
  };
})();
