
const BlackjackGame = {
    deck: [],
    playerHand: [],
    dealerHand: [],
    gameState: 'START', // START, PLAYING, END, VICTORY
    blurLevel: 50,
    currentLevel: 1,
    maxLevels: 3, // based on files seen: level_1, level_2, level_3
    message: "Place your bet!",

    // Card Suits and Values
    suits: ['♠', '♥', '♦', '♣'],
    values: ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A'],

    init: function () {
        this.currentLevel = 1;
        this.blurLevel = 50;
        this.gameState = 'START';
        this.message = "Tap 'Deal' to start";
        this.playerHand = [];
        this.dealerHand = [];

        // Tutorial Notification
        setTimeout(() => {
            if (typeof showIOSModal === 'function') {
                showIOSModal(
                    "How to Play",
                    "Win rounds to clear the image blur. Beat the dealer to strip the image layer by layer!",
                    [{ text: "Let's Play", bold: true }]
                );
            }
        }, 800);
    },

    createDeck: function () {
        this.deck = [];
        for (let suit of this.suits) {
            for (let value of this.values) {
                this.deck.push({ suit, value });
            }
        }
        // Shuffle
        for (let i = this.deck.length - 1; i > 0; i--) {
            const j = Math.floor(Math.random() * (i + 1));
            [this.deck[i], this.deck[j]] = [this.deck[j], this.deck[i]];
        }
    },

    getCardValue: function (card) {
        if (['J', 'Q', 'K'].includes(card.value)) return 10;
        if (card.value === 'A') return 11;
        return parseInt(card.value);
    },

    calculateScore: function (hand) {
        let score = 0;
        let aces = 0;
        for (let card of hand) {
            score += this.getCardValue(card);
            if (card.value === 'A') aces += 1;
        }
        while (score > 21 && aces > 0) {
            score -= 10;
            aces -= 1;
        }
        return score;
    },

    deal: function () {
        if (this.blurLevel <= 0) return; // Game Over / Victory state

        this.createDeck();
        this.playerHand = [this.deck.pop(), this.deck.pop()];
        this.dealerHand = [this.deck.pop(), this.deck.pop()];
        this.gameState = 'PLAYING';
        this.message = "Hit or Stand?";
        this.render();
    },

    hit: function () {
        if (this.gameState !== 'PLAYING') return;
        this.playerHand.push(this.deck.pop());
        const score = this.calculateScore(this.playerHand);

        if (score > 21) {
            this.endRound('BUST! You lost.');
        } else {
            this.render();
        }
    },

    stand: function () {
        if (this.gameState !== 'PLAYING') return;

        // Dealer logic: hit until 17 or higher
        while (this.calculateScore(this.dealerHand) < 17) {
            this.dealerHand.push(this.deck.pop());
        }

        const playerScore = this.calculateScore(this.playerHand);
        const dealerScore = this.calculateScore(this.dealerHand);

        if (dealerScore > 21) {
            this.endRound('Dealer BUST! You Win!');
        } else if (dealerScore > playerScore) {
            this.endRound('Dealer Wins!');
        } else if (dealerScore < playerScore) {
            this.endRound('You Win!');
        } else {
            this.endRound('Push (Tie).');
        }
    },

    endRound: function (msg) {
        this.gameState = 'END';
        this.message = msg;

        if (msg.includes('Win')) {
            this.blurLevel = Math.max(0, this.blurLevel - 10);
            if (this.blurLevel === 0) {
                this.gameState = 'VICTORY';
                this.message = "VICTORY! Image Unlocked.";
                // Auto-save logic could go here
                if (!GameState.inventory.unlockedPhotos.includes(`naked_image_level_${this.currentLevel}`)) {
                    GameState.inventory.unlockedPhotos.push(`naked_image_level_${this.currentLevel}`);
                }
            }
        }

        this.render();
    },

    nextLevel: function () {
        if (this.currentLevel < this.maxLevels) {
            this.currentLevel++;
            this.blurLevel = 50;
            this.gameState = 'START';
            this.message = "Level Up! New Image.";
            this.playerHand = [];
            this.dealerHand = [];
            this.render();
        } else {
            this.message = "All levels completed!";
            this.render();
        }
    },

    // UI Rendering
    render: function () {
        const container = document.getElementById('screen-renderer');
        if (!container) return; // Safety check

        // If not in BLACKJACK view, don't render
        if (typeof GameState !== 'undefined' && GameState.view !== 'BLACKJACK') return;

        const bgImage = `images/naked_image_level_${this.currentLevel}.jpg`;

        // Card HTML helper
        const renderCard = (card, hidden = false) => {
            if (hidden) {
                return `<div class="w-16 h-24 bg-indigo-900 rounded-lg border-2 border-white/20 flex items-center justify-center shadow-lg transform translate-y-2">
                        <div class="w-12 h-20 bg-indigo-800 rounded border border-white/10 flex items-center justify-center">?</div>
                    </div>`;
            }
            const colorClass = (card.suit === '♥' || card.suit === '♦') ? 'text-red-500' : 'text-slate-900';
            return `<div class="w-16 h-24 bg-white rounded-lg flex flex-col items-center justify-center shadow-lg transform hover:-translate-y-2 transition-transform duration-200">
                        <span class="text-xl font-bold ${colorClass}">${card.value}</span>
                        <span class="text-2xl ${colorClass}">${card.suit}</span>
                    </div>`;
        };

        const dealerCardsHtml = this.gameState === 'PLAYING' && this.dealerHand.length > 0
            ? `${renderCard(this.dealerHand[0])}${renderCard(this.dealerHand[1], true)}`
            : this.dealerHand.map(c => renderCard(c)).join('');

        const playerCardsHtml = this.playerHand.map(c => renderCard(c)).join('');

        const dealerScore = (this.gameState === 'PLAYING' && this.dealerHand.length > 0) ? '?' : this.calculateScore(this.dealerHand);
        const playerScore = this.calculateScore(this.playerHand);

        const controlButtons = this.gameState === 'PLAYING'
            ? `<button onclick="BlackjackGame.hit()" class="px-6 py-3 bg-emerald-500 hover:bg-emerald-600 active:scale-95 text-white rounded-xl font-bold shadow-lg transition-all">HIT</button>
               <button onclick="BlackjackGame.stand()" class="px-6 py-3 bg-rose-500 hover:bg-rose-600 active:scale-95 text-white rounded-xl font-bold shadow-lg transition-all">STAND</button>`
            : (this.gameState === 'VICTORY'
                ? (this.currentLevel < this.maxLevels
                    ? `<button onclick="BlackjackGame.nextLevel()" class="px-8 py-3 bg-indigo-500 text-white rounded-xl font-bold shadow-lg animate-pulse">NEXT LEVEL</button>`
                    : `<div class="px-6 py-3 bg-amber-500 text-white rounded-xl font-bold">ALL CLEARED!</div>`)
                : `<button onclick="BlackjackGame.deal()" class="px-8 py-3 bg-blue-500 hover:bg-blue-600 active:scale-95 text-white rounded-xl font-bold shadow-lg transition-all">${this.gameState === 'START' ? 'DEAL CARDS' : 'PLAY AGAIN'}</button>`);

        container.innerHTML = `
            <div class="relative w-full h-full overflow-hidden bg-black">
                <!-- Background Image with dynamic blur -->
                <div class="absolute inset-0 bg-cover bg-center transition-all duration-1000 ease-in-out"
                     style="background-image: url('${bgImage}'); filter: blur(${this.blurLevel}px);">
                </div>
                
                <!-- Overlay Gradient for readability -->
                <div class="absolute inset-0 bg-gradient-to-b from-black/60 via-transparent to-black/80 pointer-events-none"></div>

                <!-- Header -->
                <div class="absolute top-0 left-0 right-0 p-4 pt-12 flex justify-between items-center z-10">
                    <button onclick="goHome()" class="p-2 bg-white/10 backdrop-blur-md rounded-full text-white hover:bg-white/20 transition">
                        <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7"></path></svg>
                    </button>
                    <div class="px-4 py-1 bg-black/30 backdrop-blur-md rounded-full border border-white/10">
                         <span class="text-xs font-mono text-white/80">BLUR: ${this.blurLevel}px</span>
                    </div>
                    <div class="px-4 py-1 bg-black/30 backdrop-blur-md rounded-full border border-white/10">
                         <span class="text-xs font-mono text-white/80">LVL ${this.currentLevel}</span>
                    </div>
                </div>

                <!-- Game Area -->
                <div class="absolute inset-0 flex flex-col justify-center items-center gap-8 z-0 pt-16 pb-32 pointer-events-none">
                    
                    <!-- Dealer Area -->
                    <div class="flex flex-col items-center gap-2 transform scale-90">
                        <div class="flex gap-2 pointer-events-auto">
                            ${dealerCardsHtml || '<div class="w-16 h-24 border-2 border-dashed border-white/20 rounded-lg"></div><div class="w-16 h-24 border-2 border-dashed border-white/20 rounded-lg"></div>'}
                        </div>
                        <span class="text-white/70 text-sm font-medium drop-shadow-md">Dealer: ${dealerScore || 0}</span>
                    </div>

                    <!-- Message Banner -->
                    <div class="py-2 px-6 bg-white/10 backdrop-blur-xl border border-white/20 rounded-2xl shadow-xl transform hover:scale-105 transition duration-300">
                        <span class="text-white font-bold text-lg drop-shadow-md tracking-wide">${this.message}</span>
                    </div>

                    <!-- Player Area -->
                    <div class="flex flex-col items-center gap-2">
                        <span class="text-white/70 text-sm font-medium drop-shadow-md">You: ${playerScore}</span>
                        <div class="flex gap-2 pointer-events-auto">
                            ${playerCardsHtml || '<div class="w-16 h-24 border-2 border-dashed border-white/20 rounded-lg"></div><div class="w-16 h-24 border-2 border-dashed border-white/20 rounded-lg"></div>'}
                        </div>
                    </div>
                </div>

                <!-- Controls -->
                <div class="absolute bottom-10 left-0 right-0 p-6 flex justify-center gap-4 z-20 pointer-events-auto">
                    ${controlButtons}
                </div>
            </div>
        `;
    }
};
