
export class GridSystem {
    constructor() {
        // Map "x,y" -> "tileId"
        this.occupiedCells = new Map();
        this.tiles = [];
    }

    /**
     * Checks if a specific VARIANT can be placed at anchorX, anchorY.
     * Does NOT rotate anything. Assumes variant is already the correct shape.
     */
    canPlace(variant, anchorX, anchorY) {
        const layout = variant.layout;
        const rows = layout.length;

        for (let row = 0; row < rows; row++) {
            const rowData = layout[row];
            const cols = rowData.length;

            for (let col = 0; col < cols; col++) {
                // If cell is 0 (empty), skip
                if (rowData[col] === 0) continue;

                // Calculate Global Position
                // Matrix Row 0 is Top (Max Y). Matrix Row Max is Bottom (Y=0).
                const lx = col;
                const ly = (rows - 1) - row;

                const gx = anchorX + lx;
                const gy = anchorY + ly;
                const key = `${gx},${gy}`;

                // Collision Check
                if (this.occupiedCells.has(key)) {
                    return false;
                }
            }
        }
        return true;
    }

    /**
     * Registers the tile cells as occupied.
     */
    placeTile(tileInstance, variant) {
        const layout = variant.layout;
        const rows = layout.length;
        const anchorX = tileInstance.x;
        const anchorY = tileInstance.y;

        for (let row = 0; row < rows; row++) {
            const rowData = layout[row];
            const cols = rowData.length;

            for (let col = 0; col < cols; col++) {
                if (rowData[col] === 0) continue;

                const lx = col;
                const ly = (rows - 1) - row;

                const gx = anchorX + lx;
                const gy = anchorY + ly;
                const key = `${gx},${gy}`;

                this.occupiedCells.set(key, tileInstance.id);
            }
        }
        this.tiles.push(tileInstance);
    }

    /**
     * Helper to return global cells for logic/renderer without modifying state.
     */
    calculateCells(variant, anchorX, anchorY) {
        const cells = [];
        const layout = variant.layout;
        const rows = layout.length;

        for (let row = 0; row < rows; row++) {
            const rowData = layout[row];
            const cols = rowData.length;

            for (let col = 0; col < cols; col++) {
                if (rowData[col] === 0) continue;

                const lx = col;
                const ly = (rows - 1) - row;

                const gx = anchorX + lx;
                const gy = anchorY + ly;

                cells.push({ x: gx, y: gy, value: rowData[col] });
            }
        }
        return cells;
    }

    /**
     * Helper to see if a specific global coordinate is occupied
     */
    isOccupied(x, y) {
        return this.occupiedCells.has(`${x},${y}`);
    }
}
