/*implemento de codigo nuevo*/

 if(document.querySelectorAll('#tabla_modulo td')){

 var cells = document.querySelectorAll('#tabla_modulo td');



    // Iterar sobre las celdas y asignarles un atributo tabindex secuencial

    cells.forEach(function(cell, index) {

      // El índice comienza desde 0, así que sumamos 1 para que el primer tabindex sea 1

      var tabindex = index + 1;

      cell.setAttribute('tabindex', tabindex);

    });

 }

/*termina implemento de codigo nuevo*/

 var checkbox = document.getElementById("keynavigation");



  function mostrarEstado() {

    if(document.getElementById("tabla_modulo")){

        const excelTable = document.getElementById("tabla_modulo");

    

        if (checkbox.checked) {

          excelTable.setAttribute("data-selectable", "true");

          document.getElementById('button-checkbox').style.backgroundColor='lightblue';

        } else {

          excelTable.removeAttribute("data-selectable");

          deselectAllCells();

          document.getElementById('button-checkbox').style.backgroundColor='transparent';

        }

    }

  }



  let selectedCells = [];



  function deselectAllCells() {

    selectedCells.forEach(cell => cell.classList.remove('selected'));

    selectedCells = [];

    updateStats();

  }



  function selectCell(cell, addToSelection) {

    if (!addToSelection) {

      deselectAllCells();

    }

    if (!selectedCells.includes(cell)) {

      cell.classList.add('selected');

      selectedCells.push(cell);

      updateStats();

    }

  }



  function updateStats() {

    const statsDiv = document.getElementById('stats');

    const statsDivContent = document.getElementById('statsDiv');

    const selectedNumbers = selectedCells.map(cell => parseInt(cell.textContent)).filter(number => !isNaN(number));

    const sum = selectedNumbers.reduce((acc, curr) => acc + curr, 0);

    const count = selectedNumbers.length;

    const average = count > 0 ? sum / count : 0;

    statsDiv.innerHTML = `Suma: ${sum} | Número de elementos: ${count} | Promedio: ${average.toFixed(2)}`;

    statsDivContent.style.visibility = "visible";

  }



  function handleCellClick(event) {

    const cell = event.target;

    const excelTable = document.getElementById("tabla_modulo");

    if (excelTable.getAttribute("data-selectable") === "true") {

      if (!event.ctrlKey && !event.shiftKey) {

        deselectAllCells();

      }

      selectCell(cell, event.ctrlKey);

    }

  }



  function handleKeyDown(event) {

    const excelTable = document.getElementById("tabla_modulo");

    if (excelTable.getAttribute("data-selectable") === "true") {

      if (event.key === 'ArrowRight' || event.key === 'ArrowLeft' || event.key === 'ArrowUp' || event.key === 'ArrowDown') {

        event.preventDefault();

        const currentCell = document.activeElement;

        let nextCell;



        if (event.key === 'ArrowRight') {

          nextCell = currentCell.nextElementSibling;

        } else if (event.key === 'ArrowLeft') {

          nextCell = currentCell.previousElementSibling;

        } else if (event.key === 'ArrowUp') {

          const currentRowIndex = currentCell.parentElement.rowIndex;

          nextCell = currentCell.parentElement.previousElementSibling ? currentCell.parentElement.previousElementSibling.cells[currentCell.cellIndex] : null;

        } else if (event.key === 'ArrowDown') {

          const currentRowIndex = currentCell.parentElement.rowIndex;

          nextCell = currentCell.parentElement.nextElementSibling ? currentCell.parentElement.nextElementSibling.cells[currentCell.cellIndex] : null;

        }



        if (nextCell && nextCell.tagName === 'TD') {

          nextCell.focus();

          selectCell(nextCell, event.shiftKey);

        }

      } else if (event.ctrlKey && event.key === 'a') {

        event.preventDefault();

        const cells = document.querySelectorAll('#tabla_modulo td');

        cells.forEach(cell => selectCell(cell, true));

      }

    }

  }



  document.querySelectorAll('#tabla_modulo td').forEach(cell => {

    cell.addEventListener('click', handleCellClick);

  });



  document.addEventListener('click', function (event) {

    const isClickInsideTable = event.target.closest('#tabla_modulo');

    const statsDiv = document.getElementById('stats');

    const statsDivContent = document.getElementById('statsDiv');

    if (!isClickInsideTable) {

      deselectAllCells();

      statsDivContent.style.visibility = "hidden";

    }

  });





  document.addEventListener('keydown', handleKeyDown);

  mostrarEstado();