class InventorySystem {
    constructor(scene) {
        this.scene = scene;

        // Data structure: Array of slots
        // Each slot: { type: 'wood', count: 5 } or null
        this.slots = new Array(9).fill(null);
        this.maxStack = 99;

        // Generate tool icons if missing
        if (typeof TextureGenerator !== 'undefined') {
            TextureGenerator.createToolSprites(this.scene);
        }

        // Initial items
        this.addItem('axe', 1);      // 🪓 Sekira
        this.addItem('pickaxe', 1);  // ⛏️ Kramp
        this.addItem('hoe', 1);
        this.addItem('seeds', 5);    // Zmanjšano število semen
        // Removed default wood/stone so player has to gather them

        this.gold = 0;
    }

    addItem(type, count) {
        // 1. Try to stack
        for (let i = 0; i < this.slots.length; i++) {
            if (this.slots[i] && this.slots[i].type === type) {
                const space = this.maxStack - this.slots[i].count;
                if (space > 0) {
                    const toAdd = Math.min(space, count);
                    this.slots[i].count += toAdd;
                    count -= toAdd;
                    if (count === 0) break;
                }
            }
        }

        // 2. Empty slots
        if (count > 0) {
            for (let i = 0; i < this.slots.length; i++) {
                if (!this.slots[i]) {
                    const toAdd = Math.min(this.maxStack, count);
                    this.slots[i] = { type: type, count: toAdd };
                    count -= toAdd;
                    if (count === 0) break;
                }
            }
        }

        this.updateUI();

        return count === 0; // True if everything added
    }

    removeItem(type, count) {
        for (let i = 0; i < this.slots.length; i++) {
            if (this.slots[i] && this.slots[i].type === type) {
                if (this.slots[i].count >= count) {
                    this.slots[i].count -= count;
                    if (this.slots[i].count === 0) this.slots[i] = null;
                    this.updateUI();
                    return true;
                } else {
                    count -= this.slots[i].count;
                    this.slots[i] = null;
                }
            }
        }
        this.updateUI();
        return false; // Not enough items
    }

    updateUI() {
        const uiScene = this.scene.scene.get('UIScene');
        if (uiScene) {
            uiScene.updateInventory(this.slots);
            if (uiScene.updateGold) uiScene.updateGold(this.gold);
        }
    }

    hasItem(type, count) {
        let total = 0;
        for (const slot of this.slots) {
            if (slot && slot.type === type) {
                total += slot.count;
            }
        }
        return total >= count;
    }
}
