
import { TILES } from './TileDefinitions.js';

export class DungeonDeck {

    constructor() {
        this.cards = [];
        this.discards = [];
    }

    generateMissionDeck(objectiveTileId) {

        this.cards = [];

        // 1. Create a "Pool" of standard dungeon tiles
        let pool = [];
        const composition = [
            { id: 'room_dungeon', count: 6 },
            { id: 'corridor_straight', count: 7 },
            { id: 'corridor_steps', count: 1 },
            { id: 'corridor_corner', count: 1 }, // L-Shape
            { id: 'junction_t', count: 3 }
        ];

        composition.forEach(item => {
            // FIXED: Access by Key string directly
            const tileDef = TILES[item.id];

            if (tileDef) {
                for (let i = 0; i < item.count; i++) {
                    pool.push(tileDef);
                }
            } else {
                console.error(`❌ Missing Tile Definition for ID: ${item.id}`);
            }
        });

        const drawRandom = (source, count) => {
            const drawn = [];
            for (let i = 0; i < count; i++) {
                if (source.length === 0) break;
                const idx = Math.floor(Math.random() * source.length);
                drawn.push(source[idx]);
                source.splice(idx, 1);
            }
            return drawn;
        };

        // --- Step 1 & 2: Bottom Pool ---
        const bottomPool = drawRandom(pool, 6);

        const objectiveDef = TILES[objectiveTileId];
        if (objectiveDef) {
            bottomPool.push(objectiveDef);
        } else {
            console.error("Objective Tile ID not found:", objectiveTileId);
        }

        this.shuffleArray(bottomPool);

        // --- Step 4: Top Pool ---
        const topPool = drawRandom(pool, 6);
        this.shuffleArray(topPool);

        // --- Step 5: Stack ---
        this.cards = [...topPool, ...bottomPool];


    }

    shuffleArray(array) {
        for (let i = array.length - 1; i > 0; i--) {
            const j = Math.floor(Math.random() * (i + 1));
            [array[i], array[j]] = [array[j], array[i]];
        }
    }

    draw() {
        if (this.cards.length === 0) return null;
        return this.cards.shift();
    }

    insertCard(tileId, position = 0) {
        const tileDef = TILES[tileId];
        if (tileDef) {
            this.cards.splice(position, 0, tileDef);
        }
    }
}
