
(function() {

// ── STATE ──────────────────────────────────────────────────────
let bjDeck       = [];
let bjPlayerHand = [];
let bjDealerHand = [];
let bjBet        = 0;
let bjPhase      = 'betting'; // betting | playing | done

// ── OPEN / CLOSE ───────────────────────────────────────────────
window.openBlackjack = function() {
    const overlay = document.getElementById('blackjack-overlay');
    overlay.style.display = 'block';
    bjSyncCash();
    bjDeck = bjBuildDeck();
    bjResetRound();
};

window.closeBlackjack = function() {
    document.getElementById('blackjack-overlay').style.display = 'none';
    document.getElementById('bj-result').style.display  = 'none';
    document.getElementById('bj-broke').style.display   = 'none';
    // Sync cash back to game HUD
    updateCashUI();
    if (typeof MainUpdate === 'function') MainUpdate();
};

// ── CASH BRIDGE ────────────────────────────────────────────────
function bjGetCash() { return Number(localStorage.getItem('cash')) || 0; }
function bjSetCash(v) {
    const safe = Math.max(0, v);
    localStorage.setItem('cash', safe);
    document.getElementById('bj-hud-cash').textContent = safe;
    // Also update main game HUD live
    const ct = document.getElementById('cash-text');
    if (ct) ct.textContent = safe;
}
function bjSyncCash() {
    document.getElementById('bj-hud-cash').textContent = bjGetCash();
}

// ── DECK ───────────────────────────────────────────────────────
const BJ_SUITS = ['♠','♥','♦','♣'];
const BJ_RANKS = ['A','2','3','4','5','6','7','8','9','10','J','Q','K'];

function bjBuildDeck() {
    const d = [];
    for (let i = 0; i < 6; i++)
        for (const s of BJ_SUITS)
            for (const r of BJ_RANKS)
                d.push({ rank: r, suit: s });
    return bjShuffle(d);
}
function bjShuffle(arr) {
    for (let i = arr.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [arr[i], arr[j]] = [arr[j], arr[i]];
    }
    return arr;
}
function bjDraw() {
    if (bjDeck.length < 52) bjDeck = bjBuildDeck();
    return bjDeck.pop();
}

// ── HAND MATH ──────────────────────────────────────────────────
function bjCardVal(c) {
    if (['J','Q','K'].includes(c.rank)) return 10;
    if (c.rank === 'A') return 11;
    return parseInt(c.rank);
}
function bjTotal(hand) {
    let t = 0, aces = 0;
    for (const c of hand) { t += bjCardVal(c); if (c.rank === 'A') aces++; }
    while (t > 21 && aces > 0) { t -= 10; aces--; }
    return t;
}
function bjIsBlackjack(hand) { return hand.length === 2 && bjTotal(hand) === 21; }

// ── BET ────────────────────────────────────────────────────────
window.bjAddBet = function(amount) {
    if (bjPhase !== 'betting') return;
    const cash = bjGetCash();
    const maxAdd = cash - bjBet;
    if (maxAdd <= 0) return;
    bjBet += Math.min(amount, maxAdd);
    bjUpdateBetUI();
};
window.bjClearBet = function() {
    if (bjPhase !== 'betting') return;
    bjBet = 0;
    bjUpdateBetUI();
};
function bjUpdateBetUI() {
    document.getElementById('bj-bet-display').textContent = '$' + bjBet;
    const circle = document.getElementById('bj-bet-circle');
    circle.classList.toggle('bj-has-bet', bjBet > 0);
    bjSetBtn('bj-deal-btn',  bjBet > 0);
    bjSetBtn('bj-clear-btn', bjBet > 0);
}

// ── DEAL ───────────────────────────────────────────────────────
window.bjDeal = function() {
    if (bjPhase !== 'betting' || bjBet <= 0) return;
    bjPhase = 'playing';
    bjPlayerHand = [];
    bjDealerHand = [];
    bjClearCards();

    bjSetCash(bjGetCash() - bjBet);

    setTimeout(() => bjAddCard('player', bjDraw()),        0);
    setTimeout(() => bjAddCard('dealer', bjDraw()),      200);
    setTimeout(() => bjAddCard('player', bjDraw()),      400);
    setTimeout(() => bjAddCard('dealer', bjDraw(), true),600);

    setTimeout(() => {
        bjUpdateScores(true);
        bjSetBtn('bj-deal-btn', false); bjSetBtn('bj-clear-btn', false);
        bjSetBtn('bj-hit-btn', true);   bjSetBtn('bj-stand-btn', true);
        bjSetBtn('bj-double-btn', bjGetCash() >= bjBet);
        bjStatus('Your turn · Hit or Stand');
        if (bjIsBlackjack(bjPlayerHand)) {
            bjStatus('Blackjack! 🎉');
            setTimeout(bjRevealAndFinish, 300);
        }
    }, 900);
};

// ── HIT ────────────────────────────────────────────────────────
window.bjHit = function() {
    if (bjPhase !== 'playing') return;
    bjAddCard('player', bjDraw());
    bjSetBtn('bj-double-btn', false);
    bjUpdateScores(true);
    const t = bjTotal(bjPlayerHand);
    if (t > 21) {
        bjStatus('Bust! 💥'); bjPhase = 'done';
        setTimeout(() => bjShowResult('lose','Bust!', -bjBet), 400);
    } else if (t === 21) {
        bjStand();
    }
};

// ── STAND ──────────────────────────────────────────────────────
window.bjStand = function() {
    if (bjPhase !== 'playing') return;
    bjPhase = 'done';
    bjSetBtn('bj-hit-btn', false); bjSetBtn('bj-stand-btn', false); bjSetBtn('bj-double-btn', false);
    bjStatus('Dealer reveals…');
    bjRevealAndFinish();
};

// ── DOUBLE ─────────────────────────────────────────────────────
window.bjDoubleDown = function() {
    if (bjPhase !== 'playing') return;
    const extra = Math.min(bjBet, bjGetCash());
    bjSetCash(bjGetCash() - extra);
    bjBet += extra;
    document.getElementById('bj-bet-display').textContent = '$' + bjBet;
    bjAddCard('player', bjDraw());
    bjUpdateScores(true);
    bjStatus('Doubled! Standing…');
    const t = bjTotal(bjPlayerHand);
    if (t > 21) {
        bjPhase = 'done';
        setTimeout(() => bjShowResult('lose','Bust after double!', -bjBet), 400);
    } else {
        bjStand();
    }
};

// ── DEALER PLAY ────────────────────────────────────────────────
function bjRevealAndFinish() {
    bjRevealHidden();
    bjUpdateScores(false);
    const delay = bjIsBlackjack(bjPlayerHand) ? 200 : 600;
    setTimeout(() => bjDealerPlay(), delay);
}
function bjDealerPlay() {
    if (bjTotal(bjDealerHand) < 17) {
        setTimeout(() => {
            bjAddCard('dealer', bjDraw());
            bjUpdateScores(false);
            bjDealerPlay();
        }, 500);
    } else {
        bjFinishRound();
    }
}
function bjFinishRound() {
    const p = bjTotal(bjPlayerHand), d = bjTotal(bjDealerHand);
    const pBJ = bjIsBlackjack(bjPlayerHand), dBJ = bjIsBlackjack(bjDealerHand);
    let outcome, label, delta;

    if (pBJ && !dBJ)       { delta = Math.floor(bjBet*1.5); outcome='bj';   label='Blackjack! 🃏'; }
    else if (dBJ && !pBJ)  { delta = -bjBet;               outcome='lose'; label='Dealer Blackjack'; }
    else if (p > 21)        { delta = -bjBet;               outcome='lose'; label='Bust!'; }
    else if (d > 21)        { delta = bjBet;                outcome='win';  label='Dealer Busts!'; }
    else if (p > d)         { delta = bjBet;                outcome='win';  label='You Win!'; }
    else if (d > p)         { delta = -bjBet;               outcome='lose'; label='Dealer Wins'; }
    else                    { delta = 0;                    outcome='push'; label='Push'; }

    if (outcome === 'bj' || outcome === 'win') bjSetCash(bjGetCash() + bjBet + delta);
    else if (outcome === 'push')               bjSetCash(bjGetCash() + bjBet);

    setTimeout(() => bjShowResult(outcome, label, delta), 400);
}

// ── RENDER CARDS ───────────────────────────────────────────────
function bjClearCards() {
    document.getElementById('bj-player-cards').innerHTML = '';
    document.getElementById('bj-dealer-cards').innerHTML = '';
    document.getElementById('bj-player-score').style.visibility = 'hidden';
    document.getElementById('bj-dealer-score').style.visibility = 'hidden';
}

function bjAddCard(who, card, hidden=false) {
    if (who === 'player') bjPlayerHand.push(card);
    else                  bjDealerHand.push(card);

    const container = document.getElementById('bj-' + who + '-cards');
    const el = document.createElement('div');
    el.className = 'bj-card';
    el.style.animationDelay = (container.children.length * 0.05) + 's';
    if (hidden) el.dataset.hidden = '1';

    if (hidden) {
        el.innerHTML = `<div class="bj-card-back"></div>`;
    } else {
        const isRed = (card.suit === '♥' || card.suit === '♦');
        el.classList.add(isRed ? 'bj-red' : 'bj-black');
        el.innerHTML = `
            <div class="bj-card-face">
                <div class="bj-card-corner">
                    <div class="bj-card-rank">${card.rank}</div>
                    <div class="bj-card-suit">${card.suit}</div>
                </div>
                <div class="bj-card-center">${card.suit}</div>
                <div class="bj-card-corner bj-bottom">
                    <div class="bj-card-rank">${card.rank}</div>
                    <div class="bj-card-suit">${card.suit}</div>
                </div>
            </div>`;
    }
    container.appendChild(el);
}

function bjRevealHidden() {
    const container = document.getElementById('bj-dealer-cards');
    const el = container.querySelector('[data-hidden]');
    if (!el) return;
    const card = bjDealerHand[1];
    el.removeAttribute('data-hidden');
    const isRed = (card.suit === '♥' || card.suit === '♦');
    el.classList.add(isRed ? 'bj-red' : 'bj-black');
    el.innerHTML = `
        <div class="bj-card-face">
            <div class="bj-card-corner">
                <div class="bj-card-rank">${card.rank}</div>
                <div class="bj-card-suit">${card.suit}</div>
            </div>
            <div class="bj-card-center">${card.suit}</div>
            <div class="bj-card-corner bj-bottom">
                <div class="bj-card-rank">${card.rank}</div>
                <div class="bj-card-suit">${card.suit}</div>
            </div>
        </div>`;
    el.style.animation = 'none';
    el.offsetHeight;
    el.style.animation = 'bjDealCard 0.3s ease both';
}

// ── SCORES ─────────────────────────────────────────────────────
function bjUpdateScores(hideDealer) {
    const pBadge = document.getElementById('bj-player-score');
    const pTotal = bjTotal(bjPlayerHand);
    pBadge.style.visibility = 'visible';
    pBadge.textContent = pTotal;
    pBadge.className = 'bj-score-badge';
    if (pTotal > 21) pBadge.classList.add('bj-bust');
    else if (pTotal === 21) pBadge.classList.add('bj-blackjack');

    if (!hideDealer) {
        const dBadge = document.getElementById('bj-dealer-score');
        const dTotal = bjTotal(bjDealerHand);
        dBadge.style.visibility = 'visible';
        dBadge.textContent = dTotal;
        dBadge.className = 'bj-score-badge';
        if (dTotal > 21) dBadge.classList.add('bj-bust');
        else if (dTotal === 21) dBadge.classList.add('bj-blackjack');
    }
}

// ── RESULT ─────────────────────────────────────────────────────
function bjShowResult(outcome, label, delta) {
    const title  = document.getElementById('bj-result-title');
    const detail = document.getElementById('bj-result-detail');
    const change = document.getElementById('bj-result-change');

    const colors = { bj:'#f5d76e', win:'#f5d76e', lose:'#ff6b6b', push:'#aaaaaa' };
    title.textContent = label;
    title.style.color = colors[outcome] || '#fff';
    title.style.textShadow = (outcome === 'bj' || outcome === 'win')
        ? '0 0 20px rgba(245,215,110,0.6)' : 'none';

    detail.textContent = `You: ${bjTotal(bjPlayerHand)}  ·  Dealer: ${bjTotal(bjDealerHand)}`;

    if (delta > 0)       { change.textContent = '+$' + Math.abs(delta); change.style.color = '#4ade80'; }
    else if (delta < 0)  { change.textContent = '-$' + Math.abs(delta); change.style.color = '#ff6b6b'; }
    else                 { change.textContent = 'Push — bet returned';  change.style.color = '#aaa'; }

    document.getElementById('bj-result').style.display = 'flex';
}

// ── NEW ROUND ──────────────────────────────────────────────────
window.bjNewRound = function() {
    document.getElementById('bj-result').style.display = 'none';
    if (bjGetCash() <= 0) {
        document.getElementById('bj-broke').style.display = 'flex';
        return;
    }
    bjResetRound();
};

function bjResetRound() {
    bjPhase = 'betting'; bjBet = 0;
    bjPlayerHand = []; bjDealerHand = [];
    bjClearCards();
    bjUpdateBetUI();
    bjStatus('Place your bet to begin');
    bjSetBtn('bj-hit-btn', false); bjSetBtn('bj-stand-btn', false); bjSetBtn('bj-double-btn', false);
}

// ── HELPERS ────────────────────────────────────────────────────
function bjStatus(msg) { document.getElementById('bj-status').textContent = msg; }
function bjSetBtn(id, enabled) {
    const el = document.getElementById(id);
    if (el) el.disabled = !enabled;
}

})();