class WompumGrid {
    constructor(element, metadata) {
        this.gridElement = element;
        this.metadata = metadata;
        this.gridSize = {
            columns: parseInt(element.dataset.columns) || 7,
            rows: parseInt(element.dataset.rows) || 5
        };
        
        // Set grid template columns based on data attribute or default
        this.gridElement.style.gridTemplateColumns = `repeat(${this.gridSize.columns}, 1fr)`;
        
        // Generate sigils for each metadata component
        this.sigils = {
            narrator: Sigil.generate(metadata.narrator),
            subject: Sigil.generate(metadata.subject),
            facilitator: Sigil.generate(metadata.facilitator)
        };

        // Initialize color calculator
        this.colorCalculator = new ColorCalculator();

        // Store sigils as data attributes for future use
        this.gridElement.dataset.narratorSigil = JSON.stringify(this.sigils.narrator);
        this.gridElement.dataset.subjectSigil = JSON.stringify(this.sigils.subject);
        this.gridElement.dataset.facilitatorSigil = JSON.stringify(this.sigils.facilitator);
    }

    // Get sigil digit for a cell based on its section and position
    getSigilDigit(section, position) {
        const sigil = this.sigils[section];
        if (!sigil || !sigil.length) return 0;
        return sigil[position % sigil.length];
    }

    // Get influences from adjacent cells
    getInfluences(column, row) {
        const influences = [];
        
        // Check adjacent cells (up, down, left, right)
        const adjacentPositions = [
            [column, row - 1], // up
            [column, row + 1], // down
            [column - 1, row], // left
            [column + 1, row]  // right
        ];

        for (const [adjCol, adjRow] of adjacentPositions) {
            if (adjCol >= 0 && adjCol < this.gridSize.columns && 
                adjRow >= 0 && adjRow < this.gridSize.rows) {
                const cell = this.gridElement.querySelector(
                    `[data-column="${adjCol}"][data-row="${adjRow}"]`
                );
                if (cell && cell.dataset.sigilDigit) {
                    influences.push(parseInt(cell.dataset.sigilDigit));
                }
            }
        }

        return influences;
    }

    // Apply metadata-based design to the grid
    applyMetadataDesign() {
        const cells = this.gridElement.querySelectorAll('.wompum-cell');
        
        cells.forEach(cell => {
            const section = cell.dataset.section;
            const column = parseInt(cell.dataset.column);
            const row = parseInt(cell.dataset.row);
            
            // Get sigil digit for this cell
            const sigilDigit = this.getSigilDigit(section, row);
            cell.dataset.sigilDigit = sigilDigit;
            
            // Get influences from adjacent cells
            const influences = this.getInfluences(column, row);
            
            // Calculate and apply color
            const color = this.colorCalculator.getColor(sigilDigit, influences);
            cell.style.backgroundColor = color;
        });
    }

    // Initialize the grid
    init() {
        if (!this.gridElement) return;
        this.createGrid();
        this.applyMetadataDesign();
        this.setGridAreas();
    }

    // Define grid areas for each section
    setGridAreas() {
        const totalColumns = this.gridSize.columns;
        const narratorColumns = 2;
        const facilitatorColumns = 2;
        const subjectColumns = totalColumns - narratorColumns - facilitatorColumns;

        this.gridElement.style.gridTemplateAreas = `
            "narrator subject facilitator"
        `;
        // this.gridElement.style.gridTemplateColumns = `${narratorColumns}fr ${subjectColumns}fr ${facilitatorColumns}fr`;
    }

    // Create the grid cells with position awareness
    createGrid() {
        const totalCells = this.gridSize.columns * this.gridSize.rows;
        
        for (let i = 0; i < totalCells; i++) {
            const cell = document.createElement('div');
            const column = i % this.gridSize.columns;
            const row = Math.floor(i / this.gridSize.columns);
            
            // Determine which section this cell belongs to
            let section;
            if (column < 2) section = 'narrator';
            else if (column >= this.gridSize.columns - 2) section = 'facilitator';
            else section = 'subject';
            
            cell.className = 'wompum-cell';
            cell.setAttribute('data-cell-index', i);
            cell.setAttribute('data-section', section);
            cell.setAttribute('data-column', column);
            cell.setAttribute('data-row', row);
            
            this.gridElement.appendChild(cell);
        }
    }
}

// Wait for DOM to be ready
document.addEventListener('DOMContentLoaded', () => {
    // Find all grid elements
    const gridElements = document.querySelectorAll('.wompum-grid');
    
    // Initialize a grid for each element found
    gridElements.forEach(element => {
        let metadata = {};
        try {
            metadata = JSON.parse(element.dataset.metadata || '{}');
        } catch (e) {
            console.error('Error parsing metadata for grid:', e);
        }
        
        const wompum = new WompumGrid(element, metadata);
        wompum.init();
    });
}); 