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

  var C = BackgammonConstants;
  var selected = null;
  var gameState = null;

  function init(state) {
    gameState = state;
    var board = document.getElementById('bg-board');
    if (!board) return;
    board.innerHTML = buildBoardHTML();
    bindEvents();
  }

  function buildBoardHTML() {
    var html = '<div class="bg-board-inner">';
    html += '<div class="bg-half bg-half--top">';
    html += '<div class="bg-quadrant bg-quadrant--top-left">';
    for (var i = 12; i <= 17; i++) html += '<div class="bg-point bg-point--top" data-point="' + i + '"></div>';
    html += '</div>';
    html += '<div class="bg-bar-area bg-bar--top" data-action="bar"></div>';
    html += '<div class="bg-quadrant bg-quadrant--top-right">';
    for (var i = 18; i <= 23; i++) html += '<div class="bg-point bg-point--top" data-point="' + i + '"></div>';
    html += '</div></div>';

    html += '<div class="bg-half bg-half--bottom">';
    html += '<div class="bg-quadrant bg-quadrant--bottom-left">';
    for (var i = 11; i >= 6; i--) html += '<div class="bg-point bg-point--bottom" data-point="' + i + '"></div>';
    html += '</div>';
    html += '<div class="bg-bar-area bg-bar--bottom" data-action="bar"></div>';
    html += '<div class="bg-quadrant bg-quadrant--bottom-right">';
    for (var i = 5; i >= 0; i--) html += '<div class="bg-point bg-point--bottom" data-point="' + i + '"></div>';
    html += '</div></div></div>';

    html += '<div class="bg-borne-off-area">';
    html += '<div class="bg-borne-off bg-borne-off--black" data-action="off"></div>';
    html += '<div class="bg-borne-off bg-borne-off--white" data-action="off"></div>';
    html += '</div>';
    return html;
  }

  function bindEvents() {
    var board = document.getElementById('bg-board');
    if (!board) return;
    board.addEventListener('click', function(e) {
      var point = e.target.closest('[data-point]');
      var action = e.target.closest('[data-action]');
      if (point) BackgammonGame.handlePointClick(point.dataset.point);
      else if (action) BackgammonGame.handlePointClick(action.dataset.action);
    });

    var rollBtn = document.getElementById('bg-roll-btn');
    if (rollBtn) rollBtn.addEventListener('click', function() { BackgammonGame.rollDice(); });

    var undoBtn = document.getElementById('bg-undo-btn');
    if (undoBtn) undoBtn.addEventListener('click', function() { BackgammonGame.handlePointClick('undo'); });
  }

  // ─── Render ────────────────────────────────────────────────────────────────

  function render(state) {
    gameState = state;
    renderCheckers(state);
    renderBar(state);
    renderBorneOff(state);
    renderDice(state);
    renderControls(state);
    renderPipCount(state);
  }

  function renderCheckers(state) {
    var points = document.querySelectorAll('.bg-point');
    points.forEach(function(el) {
      var idx = parseInt(el.dataset.point);
      var count = state.board[idx];
      var absCount = Math.abs(count);
      var player = (count > 0) ? 0 : (count < 0) ? 1 : -1;

      var html = '';
      if (absCount > 0) {
        var display = Math.min(absCount, 5);
        var compact = absCount > 3 ? ' bg-checkers-stack--compact' : '';
        html = '<div class="bg-checkers-stack' + compact + '">';
        for (var c = 0; c < display; c++) {
          var cls = 'bg-checker bg-checker--' + (player === 0 ? 'white' : 'black');
          if (selected === idx && c === display - 1) cls += ' bg-checker--selected';
          html += '<div class="' + cls + '"></div>';
        }
        html += '</div>';
        if (absCount > 5) html += '<span class="bg-checker-count-badge">' + absCount + '</span>';
      }
      el.innerHTML = html;

      // Clear all state classes
      el.classList.remove('bg-point--valid', 'bg-point--selected', 'bg-point--source');
      if (selected === idx) el.classList.add('bg-point--selected');
    });
  }

  function renderBar(state) {
    var barTop = document.querySelector('.bg-bar--top');
    var barBottom = document.querySelector('.bg-bar--bottom');
    if (!barTop || !barBottom) return;

    barTop.innerHTML = buildBarHTML(state.bar[1], 'black');
    barBottom.innerHTML = buildBarHTML(state.bar[0], 'white');

    barBottom.classList.toggle('bg-point--source', selected === 'bar');
  }

  function buildBarHTML(count, color) {
    var html = '';
    for (var i = 0; i < Math.min(count, 4); i++) {
      html += '<div class="bg-checker bg-checker--' + color + '"></div>';
    }
    if (count > 4) html += '<span class="bg-checker-count-badge">' + count + '</span>';
    return html;
  }

  function renderBorneOff(state) {
    var whiteOff = document.querySelector('.bg-borne-off--white');
    var blackOff = document.querySelector('.bg-borne-off--black');
    if (!whiteOff || !blackOff) return;
    whiteOff.innerHTML = buildBorneHTML(state.borneOff[0], 'white');
    blackOff.innerHTML = buildBorneHTML(state.borneOff[1], 'black');
  }

  function buildBorneHTML(count, color) {
    var html = '';
    for (var i = 0; i < count; i++) html += '<div class="bg-borne-chip bg-borne-chip--' + color + '"></div>';
    if (count > 0) html += '<span class="bg-borne-count">' + count + '</span>';
    return html;
  }

  function renderDice(state) {
    var container = document.getElementById('bg-dice-container');
    if (!container) return;
    if (!state.dice) { container.innerHTML = ''; return; }

    var html = '<div class="bg-dice-pair">';
    var total = state.dice[0] === state.dice[1] ? 4 : 2;
    var remaining = state.diceRemaining.slice();

    for (var d = 0; d < total; d++) {
      var val = state.dice[d < 2 ? d : 0];
      var usedIdx = remaining.indexOf(val);
      var isUsed = (usedIdx === -1);
      if (!isUsed) remaining.splice(usedIdx, 1);
      html += renderDie(val, isUsed);
    }
    html += '</div>';
    container.innerHTML = html;
  }

  function renderDie(value, used) {
    var cls = 'bg-dice' + (used ? ' bg-dice--used' : '');
    var dots = C.DICE_FACES[value] || [];
    var html = '<div class="' + cls + '">';
    for (var i = 0; i < 9; i++) {
      html += '<span class="bg-dice-dot' + (dots.indexOf(i) !== -1 ? ' bg-dice-dot--filled' : '') + '"></span>';
    }
    return html + '</div>';
  }

  function renderControls(state) {
    var rollBtn = document.getElementById('bg-roll-btn');
    var undoBtn = document.getElementById('bg-undo-btn');

    if (rollBtn) {
      var canRoll = state.phase === 'awaiting_roll' && state.players[state.currentTurn].type === 'human';
      rollBtn.style.display = canRoll ? '' : 'none';
    }
    if (undoBtn) {
      undoBtn.style.display = state.phase === 'moving' && state.players[state.currentTurn].type === 'human' ? '' : 'none';
    }
  }

  function renderPipCount(state) {
    var el0 = document.getElementById('bg-pip-0');
    var el1 = document.getElementById('bg-pip-1');
    if (el0) el0.textContent = C.pipCount(state.board, state.bar, 0);
    if (el1) el1.textContent = C.pipCount(state.board, state.bar, 1);
  }

  // ─── Selection & Highlighting ──────────────────────────────────────────────

  function setSelected(val) {
    selected = val;
    // Apply visual immediately
    if (val === 'bar') {
      var bar = document.querySelector('.bg-bar--bottom');
      if (bar) bar.classList.add('bg-point--selected');
    } else if (val !== null) {
      var el = document.querySelector('[data-point="' + val + '"]');
      if (el) {
        el.classList.add('bg-point--selected');
        var checker = el.querySelector('.bg-checker:last-child');
        if (checker) checker.classList.add('bg-checker--selected');
      }
    }
  }

  function getSelected() { return selected; }

  function clearSelected() {
    selected = null;
    document.querySelectorAll('.bg-point--selected').forEach(function(el) { el.classList.remove('bg-point--selected'); });
    document.querySelectorAll('.bg-checker--selected').forEach(function(el) { el.classList.remove('bg-checker--selected'); });
  }

  function highlightSources(sources) {
    clearHighlights();
    sources.forEach(function(src) {
      if (src === 'bar') {
        var bar = document.querySelector('.bg-bar--bottom');
        if (bar) bar.classList.add('bg-point--source');
      } else {
        var el = document.querySelector('[data-point="' + src + '"]');
        if (el) el.classList.add('bg-point--source');
      }
    });
  }

  function highlightTargets(targets) {
    clearHighlights();
    targets.forEach(function(t) {
      if (t === 'off') {
        document.querySelectorAll('.bg-borne-off').forEach(function(el) { el.classList.add('bg-point--valid'); });
      } else {
        var el = document.querySelector('[data-point="' + t + '"]');
        if (el) el.classList.add('bg-point--valid');
      }
    });
  }

  function clearHighlights() {
    document.querySelectorAll('.bg-point--valid, .bg-point--source').forEach(function(el) {
      el.classList.remove('bg-point--valid', 'bg-point--source');
    });
  }

  // ─── Status & Log ──────────────────────────────────────────────────────────

  function setStatus(msg) {
    var el = document.getElementById('bg-status');
    if (el) el.textContent = msg;
  }

  function showLog(msg) {
    var log = document.getElementById('bg-log');
    if (!log) return;
    var entry = document.createElement('div');
    entry.className = 'bg-log-entry';
    entry.textContent = msg;
    log.prepend(entry);
    if (log.children.length > 15) log.removeChild(log.lastChild);
  }

  function showResult(winnerName, winType, points) {
    var overlay = document.getElementById('bg-result-overlay');
    if (!overlay) return;
    var label = (winType === 'backgammon') ? 'باكغمّون!' : (winType === 'gammon') ? 'غمّون!' : 'فوز!';
    overlay.innerHTML = '<div class="bg-result-card">' +
      '<h2>' + winnerName + '</h2>' +
      '<p class="bg-result-type">' + label + '</p>' +
      '<p class="bg-result-points">+' + points + '</p>' +
      '<button class="bg-new-game-btn" onclick="location.reload()">لعبة جديدة</button></div>';
    overlay.style.display = 'flex';
  }

  function animateMove() {}

  return {
    init: init,
    render: render,
    setSelected: setSelected,
    getSelected: getSelected,
    clearSelected: clearSelected,
    highlightSources: highlightSources,
    highlightTargets: highlightTargets,
    clearHighlights: clearHighlights,
    setStatus: setStatus,
    showLog: showLog,
    showResult: showResult,
    animateMove: animateMove
  };
})();
