document.addEventListener("DOMContentLoaded",()=>{const gridContainer=document.querySelector(".grid-container");if(!gridContainer)return;const gridRows=parseInt(gridContainer.dataset.rows)||1;const gridCols=parseInt(gridContainer.dataset.cols)||6;let selectedIndices=[];const fragment=document.createDocumentFragment();for(let i=0;i<gridRows*gridCols;i++){const gridItem=document.createElement("div");gridItem.classList.add("grid-cell");gridItem.dataset.index=i;gridItem.addEventListener("click",()=>toggleCell(i));fragment.appendChild(gridItem)}gridContainer.appendChild(fragment);function toggleCell(index){if(selectedIndices.includes(index)){removeRowOrColumn(index)}else{selectedIndices.push(index);fillSelection()}updateGrid();saveSelection()}function removeRowOrColumn(index){const row=Math.floor(index/gridCols);const col=index%gridCols;if(col===0){selectedIndices=selectedIndices.filter(cell=>{const cellRow=Math.floor(cell/gridCols);return cellRow<row})}else{selectedIndices=selectedIndices.filter(cell=>{const cellCol=cell%gridCols;return cellCol!==col});adjustRectangleAfterColumnRemoval()}}function adjustRectangleAfterColumnRemoval(){if(selectedIndices.length===0)return;const firstCol=Math.min(...selectedIndices.map(cell=>cell%gridCols));const lastCol=Math.max(...selectedIndices.map(cell=>cell%gridCols));for(let col=firstCol;col<=lastCol;col++){const isColumnEmpty=!selectedIndices.some(cell=>cell%gridCols===col);if(isColumnEmpty){selectedIndices=selectedIndices.filter(cell=>cell%gridCols<col);break}}}function fillSelection(){if(selectedIndices.length===0)return;const firstRow=Math.min(...selectedIndices.map(cell=>Math.floor(cell/gridCols)));const lastRow=Math.max(...selectedIndices.map(cell=>Math.floor(cell/gridCols)));const firstCol=Math.min(...selectedIndices.map(cell=>cell%gridCols));const lastCol=Math.max(...selectedIndices.map(cell=>cell%gridCols));const newSelection=[];for(let row=firstRow;row<=lastRow;row++){for(let col=firstCol;col<=lastCol;col++){const cellIndex=row*gridCols+col;newSelection.push(cellIndex)}}selectedIndices=newSelection}function updateGrid(){gridContainer.querySelectorAll(".grid-cell").forEach(cell=>{cell.classList.remove("selected")});selectedIndices.forEach(index=>{gridContainer.querySelector(`.grid-cell[data-index="${index}"]`)?.classList.add("selected")})}function saveSelection(){const gridDataInput=document.getElementById("grid-data");if(gridDataInput){gridDataInput.value=JSON.stringify(selectedIndices)}}});