import { WindowManager } from './window_manager.js';

export const InventoryOverlay = {
    open() {
        const { win, content } = WindowManager.create('window-inventory', '🎒 Inventory', { x: 560, y: 20, width: 220, height: 300 });
        this.update(content);
    },

    update(container) {
        if (!container) container = document.getElementById('window-inventory-content');
        if (!container) return;

        const MB = window.MagicBot;
        if (!MB || !MB.state || !MB.state.inventory || !MB.state.inventory.items) {
            container.innerHTML = '<div style="color:red">No Data</div>';
            return;
        }

        container.innerHTML = '';
        const grid = document.createElement('div');
        grid.style.cssText = "display: grid; grid-template-columns: 1fr; gap: 5px; font-size: 11px;";

        MB.state.inventory.items.forEach(item => {
            let name = item.itemType;
            let species = item.species || item.parameters?.species || Object.values(item.parameters?.speciesIds || {})[0];
            if (species) name = species + " " + item.itemType;

            const div = document.createElement('div');
            div.style.cssText = "background: rgba(255,255,255,0.05); padding: 4px; border-radius: 4px; display: flex; justify-content: space-between; cursor: pointer;";
            div.innerHTML = `<span>${name}</span><span style="color:#aaa; font-weight:bold;">x${item.quantity || item.count || 1}</span>`;

            // Plant logic on click
            div.onclick = () => {
                if (item.itemType === 'Seed' && species) {
                    // Find empty slot
                    for (let i = 0; i < 200; i++) {
                        if (!MB.state.garden.tileObjects[i.toString()]?.slots?.length) {
                            MB.sendMsg({ type: "PlantSeed", slot: i, species: species, scopePath: ["Room", "Quinoa"] });
                            div.style.background = 'rgba(100,255,100,0.2)';
                            setTimeout(() => div.style.background = 'rgba(255,255,255,0.05)', 200);
                            return;
                        }
                    }
                    alert("Garden Full!");
                }
            };

            grid.appendChild(div);
        });

        if (MB.state.inventory.items.length === 0) grid.innerHTML = '<div style="color:#666; text-align:center;">Empty</div>';
        container.appendChild(grid);
    }
};
