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

    var selectedTile = null;
    var onTilePlay = null;
    var onDraw = null;
    var onPass = null;

    function init(callbacks) {
        onTilePlay = callbacks.onTilePlay || null;
        onDraw = callbacks.onDraw || null;
        onPass = callbacks.onPass || null;
    }

    // ─── Tile Rendering ─────────────────────────────────────────────────────

    function createPipDots(value) {
        var positions = DominoConstants.PIP_POSITIONS[value] || [];
        var html = '';
        for (var i = 0; i < 9; i++) {
            if (positions.indexOf(i) !== -1) {
                html += '<span class="domino-pip"></span>';
            } else {
                html += '<span class="domino-pip domino-pip--empty"></span>';
            }
        }
        return html;
    }

    function renderTile(tile, options) {
        options = options || {};
        var isVertical = options.vertical || false;
        var isBack = options.back || false;
        var isPlayable = options.playable || false;
        var isSelected = options.selected || false;
        var small = options.small || false;

        var classes = ['domino-tile'];
        if (isVertical) classes.push('domino-tile--vertical');
        if (isBack) classes.push('domino-tile--back');
        if (isPlayable) classes.push('domino-tile--playable');
        if (isSelected) classes.push('domino-tile--selected');
        if (small) classes.push('domino-tile--small');
        if (tile && DominoConstants.isDouble(tile)) classes.push('domino-tile--double');

        var dataAttr = tile ? ' data-tile-id="' + tile.id + '"' : '';

        if (isBack) {
            return '<div class="' + classes.join(' ') + '"' + dataAttr + '>' +
                '<div class="domino-half domino-half--back"></div>' +
                '<div class="domino-divider"></div>' +
                '<div class="domino-half domino-half--back"></div>' +
                '</div>';
        }

        return '<div class="' + classes.join(' ') + '"' + dataAttr + '>' +
            '<div class="domino-half"><div class="domino-pips">' + createPipDots(tile.left) + '</div></div>' +
            '<div class="domino-divider"></div>' +
            '<div class="domino-half"><div class="domino-pips">' + createPipDots(tile.right) + '</div></div>' +
            '</div>';
    }

    // ─── Hand Rendering ─────────────────────────────────────────────────────

    function renderHand(hand, options) {
        options = options || {};
        var isCurrentPlayer = options.isCurrentPlayer || false;
        var playableEnds = options.playableEnds || {};
        var boardEmpty = options.boardEmpty || false;

        var container = document.getElementById('domino-hand');
        if (!container) return;

        var html = '';
        for (var i = 0; i < hand.length; i++) {
            var tile = hand[i];
            var isPlayable = false;

            if (isCurrentPlayer) {
                if (boardEmpty || playableEnds.any) {
                    isPlayable = true;
                } else {
                    for (var side in playableEnds) {
                        if (DominoConstants.tileMatchesEnd(tile, playableEnds[side])) {
                            isPlayable = true;
                            break;
                        }
                    }
                }
            }

            html += renderTile(tile, {
                playable: isPlayable,
                selected: selectedTile && selectedTile.id === tile.id
            });
        }

        container.innerHTML = html;

        // Attach click events
        var tiles = container.querySelectorAll('.domino-tile');
        for (var t = 0; t < tiles.length; t++) {
            tiles[t].addEventListener('click', handleTileClick);
        }
    }

    function handleTileClick(e) {
        var el = e.currentTarget;
        var tileId = el.dataset.tileId;
        if (!tileId) return;
        if (!el.classList.contains('domino-tile--playable')) return;

        // Toggle selection
        if (selectedTile && selectedTile.id === tileId) {
            selectedTile = null;
            el.classList.remove('domino-tile--selected');
            hideEndButtons();
            return;
        }

        // Deselect previous
        var prev = document.querySelector('.domino-tile--selected');
        if (prev) prev.classList.remove('domino-tile--selected');

        selectedTile = { id: tileId };
        el.classList.add('domino-tile--selected');
        showEndButtons(tileId);
    }

    function showEndButtons(tileId) {
        var endBtns = document.getElementById('domino-end-buttons');
        if (!endBtns) return;
        endBtns.style.display = 'flex';
        endBtns.dataset.tileId = tileId;
    }

    function hideEndButtons() {
        var endBtns = document.getElementById('domino-end-buttons');
        if (endBtns) endBtns.style.display = 'none';
    }

    function handleEndButtonClick(side) {
        if (!selectedTile) return;
        if (onTilePlay) onTilePlay(selectedTile.id, side);
        selectedTile = null;
        hideEndButtons();
    }

    // ─── Board Rendering ────────────────────────────────────────────────────

    function renderBoard(board, spinner) {
        var container = document.getElementById('domino-board');
        if (!container) return;

        if (!board || board.length === 0) {
            container.innerHTML = '<div class="domino-board-empty">اختر قطعة للبدء</div>';
            return;
        }

        var eastChain = board.filter(function(e) { return e.side === 'east'; });
        var westChain = board.filter(function(e) { return e.side === 'west'; });
        var northChain = board.filter(function(e) { return e.side === 'north'; });
        var southChain = board.filter(function(e) { return e.side === 'south'; });
        var spinnerEntry = board.find(function(e) { return e.isSpinner || e.side === null; });

        var html = '<div class="domino-board-layout">';

        // North chain (vertical, bottom to top)
        if (northChain.length > 0) {
            html += '<div class="domino-chain domino-chain--north">';
            for (var n = northChain.length - 1; n >= 0; n--) {
                html += renderTile(northChain[n].tile, { vertical: true, small: true });
            }
            html += '</div>';
        }

        // Main row: West + Spinner + East
        html += '<div class="domino-chain domino-chain--main">';

        // West (reversed — newest at far left)
        if (westChain.length > 0) {
            for (var w = westChain.length - 1; w >= 0; w--) {
                html += renderTile(westChain[w].tile, { small: true });
            }
        }

        // Spinner / first tile
        if (spinnerEntry) {
            var isSpinnerDouble = DominoConstants.isDouble(spinnerEntry.tile);
            html += '<div class="domino-spinner">' + renderTile(spinnerEntry.tile, { vertical: isSpinnerDouble, small: true }) + '</div>';
        }

        // East
        if (eastChain.length > 0) {
            for (var e = 0; e < eastChain.length; e++) {
                html += renderTile(eastChain[e].tile, { small: true });
            }
        }

        html += '</div>';

        // South chain (vertical, top to bottom)
        if (southChain.length > 0) {
            html += '<div class="domino-chain domino-chain--south">';
            for (var s = 0; s < southChain.length; s++) {
                html += renderTile(southChain[s].tile, { vertical: true, small: true });
            }
            html += '</div>';
        }

        html += '</div>';
        container.innerHTML = html;
    }

    // ─── Opponent Hands ─────────────────────────────────────────────────────

    function renderOpponentHands(hands, players, currentPlayerIdx, playerCount) {
        var positions = getOpponentPositions(currentPlayerIdx, playerCount);

        for (var pos in positions) {
            var container = document.getElementById('domino-opponent-' + pos);
            if (!container) continue;

            var idx = positions[pos];
            if (idx === null) { container.innerHTML = ''; continue; }

            var count = typeof hands[idx] === 'number' ? hands[idx] : (hands[idx] ? hands[idx].length : 0);
            var name = players[idx] ? players[idx].name : '';

            var html = '<div class="domino-opponent-info">';
            html += '<span class="domino-opponent-name">' + name + '</span>';
            html += '<span class="domino-opponent-count">' + count + ' قطع</span>';
            html += '</div>';
            html += '<div class="domino-opponent-tiles">';
            for (var t = 0; t < Math.min(count, 7); t++) {
                html += renderTile(null, { back: true, small: true });
            }
            html += '</div>';

            container.innerHTML = html;
        }
    }

    function getOpponentPositions(myIdx, playerCount) {
        if (playerCount === 2) {
            return { top: (myIdx + 1) % 2, left: null, right: null };
        }
        // 4 players: partner on top, opponents on sides
        return {
            top: (myIdx + 2) % 4,
            left: (myIdx + 1) % 4,
            right: (myIdx + 3) % 4
        };
    }

    // ─── Scores ─────────────────────────────────────────────────────────────

    function renderScores(scores, players, mode, targetScore) {
        var container = document.getElementById('domino-scores');
        if (!container) return;

        var html = '<div class="domino-score-header">النتيجة (الهدف: ' + targetScore + ')</div>';
        html += '<div class="domino-score-list">';

        if (mode === '4p_teams') {
            html += '<div class="domino-score-row"><span>فريق 1</span><span class="domino-score-val">' + (scores[0] || 0) + '</span></div>';
            html += '<div class="domino-score-row"><span>فريق 2</span><span class="domino-score-val">' + (scores[1] || 0) + '</span></div>';
        } else {
            for (var i = 0; i < players.length; i++) {
                html += '<div class="domino-score-row"><span>' + players[i].name + '</span><span class="domino-score-val">' + (scores[i] || 0) + '</span></div>';
            }
        }

        html += '</div>';
        container.innerHTML = html;
    }

    // ─── Status Bar ─────────────────────────────────────────────────────────

    function renderStatus(text, type) {
        var container = document.getElementById('domino-status');
        if (!container) return;
        container.className = 'domino-status domino-status--' + (type || 'info');
        container.textContent = text;
    }

    // ─── Boneyard ───────────────────────────────────────────────────────────

    function renderBoneyard(count, canDraw) {
        var container = document.getElementById('domino-boneyard');
        if (!container) return;

        if (count <= 0) {
            container.innerHTML = '<div class="domino-boneyard-empty">البونيارد فارغ</div>';
            return;
        }

        var html = '<div class="domino-boneyard-pile' + (canDraw ? ' domino-boneyard-pile--active' : '') + '">';
        html += '<div class="domino-boneyard-stack">';
        html += renderTile(null, { back: true, small: true });
        html += '</div>';
        html += '<span class="domino-boneyard-count">' + count + '</span>';
        if (canDraw) {
            html += '<button class="btn btn-sm btn-gold domino-draw-btn" id="domino-draw-btn">اسحب</button>';
        }
        html += '</div>';

        container.innerHTML = html;

        if (canDraw) {
            var btn = document.getElementById('domino-draw-btn');
            if (btn) btn.addEventListener('click', function() { if (onDraw) onDraw(); });
        }
    }

    // ─── Actions ────────────────────────────────────────────────────────────

    function renderActions(options) {
        var container = document.getElementById('domino-actions');
        if (!container) return;

        var html = '';
        if (options.canPass) {
            html += '<button class="btn btn-ghost btn-sm" id="domino-pass-btn">تمرير</button>';
        }
        container.innerHTML = html;

        if (options.canPass) {
            var btn = document.getElementById('domino-pass-btn');
            if (btn) btn.addEventListener('click', function() { if (onPass) onPass(); });
        }
    }

    // ─── End Buttons (choose which end to play on) ──────────────────────────

    function renderEndButtons(availableEnds, boardEmpty) {
        var container = document.getElementById('domino-end-buttons');
        if (!container) return;

        if (boardEmpty) {
            container.innerHTML = '<button class="btn btn-gold btn-sm domino-end-btn" data-side="any">ضع هنا</button>';
        } else {
            var html = '';
            var sideLabels = { east: 'شرق ←', west: '→ غرب', north: '↑ شمال', south: '↓ جنوب' };
            for (var side in availableEnds) {
                html += '<button class="btn btn-gold btn-sm domino-end-btn" data-side="' + side + '">' + (sideLabels[side] || side) + ' (' + availableEnds[side] + ')</button>';
            }
            container.innerHTML = html;
        }

        container.style.display = 'none'; // Hidden until tile selected

        var btns = container.querySelectorAll('.domino-end-btn');
        for (var i = 0; i < btns.length; i++) {
            btns[i].addEventListener('click', function() {
                handleEndButtonClick(this.dataset.side);
            });
        }
    }

    // ─── Round Over Overlay ─────────────────────────────────────────────────

    function showRoundOverlay(data) {
        var overlay = document.getElementById('domino-round-overlay');
        if (!overlay) return;

        var html = '<div class="domino-overlay-content">';
        html += '<h3>' + (data.matchOver ? 'انتهت المباراة!' : 'انتهت الجولة ' + data.round + '!') + '</h3>';

        if (data.type === 'domino') {
            html += '<p class="domino-overlay-result">دومينو! ' + data.winnerName + ' فاز</p>';
        } else {
            html += '<p class="domino-overlay-result">اللعب مقفل — ' + (data.winnerName || 'تعادل') + '</p>';
        }

        html += '<p class="domino-overlay-score">+' + data.score + ' نقطة</p>';

        if (data.matchOver) {
            html += '<button class="btn btn-gold btn-lg" onclick="location.href=\'/domino\'">العودة للوبي</button>';
        } else {
            html += '<button class="btn btn-gold btn-lg" id="domino-next-round-btn">الجولة التالية</button>';
        }

        html += '</div>';
        overlay.innerHTML = html;
        overlay.style.display = 'flex';

        if (!data.matchOver) {
            var btn = document.getElementById('domino-next-round-btn');
            if (btn) btn.addEventListener('click', function() {
                overlay.style.display = 'none';
            });
        }
    }

    function clearSelection() {
        selectedTile = null;
        hideEndButtons();
        var prev = document.querySelector('.domino-tile--selected');
        if (prev) prev.classList.remove('domino-tile--selected');
    }

    return {
        init: init,
        renderTile: renderTile,
        renderHand: renderHand,
        renderBoard: renderBoard,
        renderOpponentHands: renderOpponentHands,
        renderScores: renderScores,
        renderStatus: renderStatus,
        renderBoneyard: renderBoneyard,
        renderActions: renderActions,
        renderEndButtons: renderEndButtons,
        showRoundOverlay: showRoundOverlay,
        clearSelection: clearSelection,
        getSelectedTile: function() { return selectedTile; }
    };
})();
