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

export const ShopOverlay = {
    open() {
        const { win, content } = WindowManager.create('window-shop', '🏪 Shop', { x: 790, y: 20, width: 250, height: 350 });
        this.update(content);
    },

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

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

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

        MB.state.shops.seed.inventory.forEach(item => {
            const purchased = MB.state.shopPurchases?.seed?.purchases?.[item.species] || 0;
            const stock = Math.max(0, item.initialStock - purchased);
            const stockColor = stock > 0 ? '#66bb6a' : '#ff5252';
            const auto = MB.automation?.autoBuyItems?.has(item.species);

            const div = document.createElement('div');
            div.style.cssText = `background: rgba(255,255,255,0.05); padding: 5px; border-radius: 4px; border-left: 2px solid ${stockColor}; border-right: 2px solid ${auto ? '#ffd700' : 'transparent'}; cursor: pointer;`;

            div.innerHTML = `<div style="font-weight:bold;">${item.species}</div><div style="color:#888;">${stock}/${item.initialStock}</div>`;

            div.oncontextmenu = (e) => {
                e.preventDefault();
                if (auto) MB.automation.autoBuyItems.delete(item.species);
                else MB.automation.autoBuyItems.add(item.species);
                this.update(container); // Refresh immediately to show border change
            };

            div.onclick = () => {
                if (stock > 0) MB.sendMsg({ scopePath: ["Room", "Quinoa"], type: "PurchaseSeed", species: item.species });
            };

            grid.appendChild(div);
        });

        container.appendChild(grid);
    }
};
