/**********************************
 *  FILE
 * This script enhances file input elements by making them keyboard and mouse accessible.
 * It listens for specific key presses and clicks on a custom file input wrapper,
 * then updates a text element with the file name once a file is selected.
 **********************************/
/*
window.onload = function () {
    // Select all elements with the class ".file" to enhance their file input behavior.
    document.querySelectorAll(".file").forEach((file) => {
      // Find the actual file input and the element where the file name will be displayed within the ".file" container.
      const fileInput = file.querySelector(".file-input");
      const fileText = file.querySelector(".file-text");

      // Listen for keydown events to allow keyboard interaction (Enter and Space keys) for focusing the file input.
      file.addEventListener("keydown", function (event) {
        if (event.key === "Enter" || event.key === " ") {
          // When Enter or Space is pressed, focus the file input to trigger the file selection dialog.
          fileInput.focus();
        }
      });

      // Listen for click events on the custom file input container to focus the hidden file input.
      file.addEventListener("click", function () {
        // Focus the file input to trigger the file selection dialog.
        fileInput.focus();
        // Prevent the default action to ensure custom behavior is executed.
        return false;
      });

      // When a file is selected, update the text content of the specified element to display the file name.
      fileInput.addEventListener("change", function () {
        // Update the text content with the name of the selected file.
        // 'this.value' contains the path of the selected file, but only the file name is typically displayed for security reasons.
        fileText.textContent = this.value.split("\\").pop(); // Added split to extract the file name from the path.
      });
    });
};

// Replace input file
const labelElement = document.createElement('label');
labelElement.setAttribute('tabindex', '0');
labelElement.setAttribute('for', 'AttachFile');
labelElement.classList.add('file');

const fileTextElement = document.createElement('div');
fileTextElement.classList.add('file-text');

const fileInputElement = document.createElement('input');
fileInputElement.setAttribute('type', 'file');
fileInputElement.classList.add('file-input');
fileInputElement.setAttribute('id', 'AttachFile');

// Append the child elements
labelElement.appendChild(fileTextElement);
labelElement.appendChild(fileInputElement);

// Get the existing input element
const existingInput = document.getElementById('AttachFile');

// Replace the existing input with the label element
existingInput.parentNode.replaceChild(labelElement, existingInput);*/


//------------

/**********************************
 *  FILE
 * This script enhances file input elements by making them keyboard and mouse accessible.
 * It listens for specific key presses and clicks on a custom file input wrapper,
 * then updates a text element with the file name once a file is selected.
 **********************************/

document.addEventListener("DOMContentLoaded", () => {
  document.querySelectorAll(".file-container").forEach((container) => {
    const fileInput = container.querySelector(".file-input");
    const fileUpload = container.querySelector(".file-upload");
    const fileLabel = container.querySelector(".file");

    fileInput.addEventListener("change", () => updateFileList());

    fileUpload.addEventListener("click", (event) => {
      if (event.target.classList.contains("file-upload-delete")) {
        removeFile(parseInt(event.target.dataset.index));
      }
    });

    function updateFileList() {
      const dt = new DataTransfer();
      const files = [...fileInput.files];

      fileLabel.classList.toggle("active", files.length > 0);
      fileUpload.replaceChildren(
        ...files.map((file, index) => createFileItem(file, index, dt))
      );

      fileInput.files = dt.files;
    }

    function removeFile(index) {
      const dt = new DataTransfer();
      const files = [...fileInput.files];

      files.splice(index, 1);
      files.forEach((file) => dt.items.add(file));

      fileInput.files = dt.files;
      updateFileList();
    }

    function createFileItem(file, index, dt) {
      dt.items.add(file);

      const fileItem = document.createElement("div");
      fileItem.className = "file-upload-item";

      fileItem.innerHTML = `
        <div class="file-upload-name">${file.name}</div>
        <div class="file-upload-size">${formatFileSize(file.size)}</div>
        <div class="file-upload-delete" data-index="${index}"></div>
      `;

      return fileItem;
    }

    function formatFileSize(size) {
      return size < 1024
        ? `${size} B`
        : size < 1024 * 1024
        ? `${(size / 1024).toFixed(1)} KB`
        : `${(size / (1024 * 1024)).toFixed(1)} MB`;
    }
  });
});
