document.addEventListener('DOMContentLoaded', function() {
  var user_actions_modal = document.getElementById("user_actions_modal");
  var modal_content = document.getElementById("modal_content");
  var profile_picture_input = document.getElementById("profile_picture");

  // Event listener on the file input
  profile_picture_input.addEventListener('change', function() {
    if (profile_picture_input.files && profile_picture_input.files[0]) {
      var file = profile_picture_input.files[0];
      var form_data = new FormData();
      form_data.append('upload', file);
      form_data.append('test_key', 'test_value');


      var xhr = new XMLHttpRequest();
      xhr.open('POST', 'http://localhost:2025/functions/functions.php', true);
      xhr.setRequestHeader('enctype', 'multipart/form-data');

      xhr.onload = function() {
        if (xhr.status >= 200 && xhr.status < 300) {
          filepath = '/data/tmp/' + profile_picture_input.files[0].name;
          openModal('profile_cropper', filepath);
        } else {
          console.error('Error uploading file:', xhr.status, xhr.statusText);
        }

        xhr.onerror = function() {
          console.error('Network error occurred.');
        };
      };

      xhr.send(form_data);
    }
  });

  // Open modal function
  function openModal(formId, filePath = null) {
    let content = document.getElementById(formId).innerHTML;
    if (filePath) {
      content = content.replace('IMG_UPLOAD_PATH', filePath);
    }
    modal_content.innerHTML = content;
    user_actions_modal.style.display = "block";

    cropper();
  }

  function cropper() {
    let img_to_crop = document.getElementById('img_to_crop');
    let selection_box = document.getElementById('img_crop_selection');
    let crop_button = document.getElementById('crop_button');
    let corners = document.querySelectorAll('.corner');

    let selection = {
      x: 0,
      y: 0,
      width: 100,
      height: 100,
      is_resizing: false,
      is_dragging: false,
      resize_corner: null,
    };

    function updateSelection() {
      selection_box.style.left = `${selection.x}px`;
      selection_box.style.top = `${selection.y}px`;
      selection_box.style.width = `${selection.width}px`;
      selection_box.style.height = `${selection.height}px`;
    }

    img_to_crop.addEventListener('mousemove', (e) => {
      const { clientX, clientY } = e;
      if (!selection_box.classList.contains('stop')) {

        // const img_bounds = img_to_crop.getBoundingClientRect();
        // const box_bounds = selection_box.getBoundingClientRect();
        //
        // console.log('img_bounds: ' + img_bounds.top);
        // console.log('box_bounds: ' + box_bounds.top);
        // if (box_bounds.left > img_bounds.left || box_bounds.right < img_bounds.right)
        selection.x = clientX;
        // if (box_bounds.top > img_bounds.top || box_bounds.bottom > img_bounds.bottom)
        selection.y = clientY;

        updateSelection();
      } else if (selection.is_resizing) {
        resizing(e);
      }
    });

    img_to_crop.addEventListener('click', function(event) {
      if (selection_box.classList.contains('stop')) {
        selection.is_resizing = false;
        selection_box.classList.remove('stop');
      }
      else {
        selection_box.classList.add('stop');
      }
    })

    corners.forEach((corner) => {
      corner.addEventListener('mousedown', (e) => {
        console.log('resizing');
        selection.resize_corner = corner.id;
        selection.is_resizing = true;
        e.stopPropagation(); // Prevent image click event
      });

      corner.addEventListener('dragstart', (e) => {
        e.preventDefault();
      })
    });

    crop_button.addEventListener('click', () => {
      document.getElementById('crop_x').value = selection.x + (selection.width / 1.5);
      document.getElementById('crop_y').value = selection.y + (selection.width / 1.5);
      document.getElementById('crop_width').value = selection.width;

      closeModal();
    });

    function resizing(e) {
      if (!selection.is_resizing) return;

      const aspect_ratio = 1;

      let newWidth = selection.width;

      switch (selection.resize_corner) {
        case 'corner_nw':
          newWidth = selection.x - e.clientX;
          break;
        case 'corner_sw':
          newWidth = selection.x - e.clientX;
          break;
        case 'corner_ne':
          newWidth = e.clientX - selection.x;
          break;
        case 'corner_se':
          newWidth = e.clientX - selection.x;
          break;
      }

      selection.width = newWidth;
      selection.height = newWidth / aspect_ratio;
      // }
      updateSelection();
    }
  }

  modal_content.addEventListener('click', function(event) {
    if (event.target.classList.contains('modal_close')) {
      closeModal();
    }
  });

  window.onclick = function(event) {
    if (event.target.classList.contains('modal')) {
      closeModal();
    }
  };

  // Close modal function
  function closeModal() {
    modal_content.innerHTML = ""; // Clear content when closing
    user_actions_modal.style.display = "none";
  }
});
