document.addEventListener("DOMContentLoaded", () => {
  getAllProject()
    .then((project_list) => {
      global_project_list = project_list;
      setupCarousel(global_project_list);
    })
    .catch((error) => {
      console.error(error);
    });
});

function formatDateToFrench(dateString) {
  const options = { 
    year: 'numeric', 
    month: 'long', 
    day: 'numeric'
  };
  const date = new Date(dateString);
  return date.toLocaleDateString('fr-FR', options);
}

function formatStatusWithColor(status) {
  let statusText = "";
  let colorClass = "";

  switch (status) {
    case 0:
      statusText = "Brouillon";
      colorClass = "status-draft";
      break;
    case 1:
      statusText = "En capture";
      colorClass = "status-capturing";
      break;
    case 2:
      statusText = "Terminé";
      colorClass = "status-idle";
      break;
    case 3:
      statusText = "En cours d\'arrêt";
      colorClass = "status-stopping";
      break; // Ajout du break manquant ici
    default:
      statusText = "Inconnu";
      colorClass = "status-unknown";
  }

  return `<span class="${colorClass}">${statusText}</span>`;
}

function formatStatus(status) {
  switch (status) {
    case 0:
      return "Brouillon"; // Projet à peine créé, vide sans config
    case 1:
      return "En capture"; // Projet en cours de capture
    case 2:
      return "En pause"; // Projet en pause ou inactif
    case 3:
      return "En cours d\'arrêt"; // Projet en cours d'arrêt
    default:
      return "Inconnu";
  }
}

function setupCarousel(global_project_list) {
  const formContainer = document.getElementById('form-container');
  const carousel = document.getElementById('carousel');
  const carouselDots = document.getElementById('carousel-dots');
  let currentIndex = 0;
  let currdeg = 0;
  const degGlobal = 360 / global_project_list.length;

  function showForm() {
    formContainer.style.display = 'flex';
  }

  function hideForm() {
    formContainer.style.display = 'none';
  }

  document.getElementById('show-form-button').addEventListener('click', showForm);
  document.getElementById('close-form-button').addEventListener('click', hideForm);
  document.getElementById('submit').addEventListener('click', handleFormSubmit);

  async function handleFormSubmit() {
    const nameProject = document.getElementById('name').value;
    const description = document.getElementById('description').value;
    if (nameProject.length === 0 || !checkName(global_project_list, nameProject)) {
      alert('Le nom : "' + nameProject + '" est déjà pris ou vide ! \n' +
        'veuillez en trouver un autre');
      return;
    }
    PostNewProject(nameProject, description).then(() => {
      location.reload();
    });
  }

  function checkName(Projects, name) {
    return !Projects.some(project => project.name === name);
  }


  function updateDots() {
    const dots = document.querySelectorAll('.dot');
    dots.forEach((dot, index) => {
      dot.classList.toggle('active', index === currentIndex);
    });
  }

  function showPrevProject() {
    currentIndex = (currentIndex > 0) ? currentIndex - 1 : global_project_list.length - 1;
    updateDots();
  }

  function showNextProject() {
    currentIndex = (currentIndex < global_project_list.length - 1) ? currentIndex + 1 : 0;
    updateDots();
  }

  document.getElementById('prev-button').addEventListener('click', showPrevProject);
  document.getElementById('next-button').addEventListener('click', showNextProject);

  const letter = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'v', 'w', 'x', 'y', 'z'];

  global_project_list.forEach((project, index) => {
    const projectDiv = document.createElement('div');
    projectDiv.classList.add('project');
    projectDiv.classList.add('item');
    projectDiv.classList.add(letter[index]);
    projectDiv.innerHTML = `
      <h2>${project.name}</h2>
      <p class="project-description" style="font-size: 0.8em; font-style: italic; margin-top: -5px; margin-bottom: 10px;">${project.description || 'Pas de description'}</p>
      <p><strong>Date de début :</strong> ${formatDateToFrench(project.start_date)}</p>
      <p><strong>Statut :</strong> ${formatStatusWithColor(parseInt(project.status))}</p>
      <div class="project_buttons">
        <button class="default-access-button">Voir les détails</button>
        <button class="default-delete-button">Supprimer</button>
      </div>
    `;
    carousel.appendChild(projectDiv);
    projectDiv.style.transform = `rotateY(${index * degGlobal}deg) translateZ(${global_project_list.length*3.5}vw)`;

    const detailButton = projectDiv.querySelector('.default-access-button');
    detailButton.addEventListener('click', (event) => {
      event.stopPropagation();
      window.location.href = `pages/projet_detail.html?id=${project.id}`;
    });

    const deleteButton = projectDiv.querySelector('.default-delete-button');
    deleteButton.addEventListener('click', (event) => {
      event.stopPropagation();
      const projectName = project.name;
      const projectStatus = parseInt(project.status);
      
      // Vérifier si le projet est en cours de capture (statut 1) ou en cours d'arrêt (statut 3)
      if (projectStatus === 1 || projectStatus === 3) {
        alert(`Impossible de supprimer "${projectName}" car sa capture est ${projectStatus === 1 ? 'en cours' : 'en cours d\'arrêt'}.\nVeuillez d'abord arrêter la procédure de capture.`);
        return;
      }
      
      document.getElementById('alertMessage').textContent = `Veux-tu vraiment supprimer le projet : ${projectName} ?`;
      document.getElementById('customAlert').style.display = 'block';

      document.getElementById('okBtn').onclick = function () {
        document.getElementById('customAlert').style.display = 'none';
        deleteProject(project.id).then(() => {
          location.reload();
        });
      };

      document.getElementById('cancelBtn').onclick = function () {
        document.getElementById('customAlert').style.display = 'none';
      };
    });

    const dot = document.createElement('div');
    dot.classList.add('dot');
    dot.addEventListener('click', () => {
      currentIndex = index;
      currdeg = -index * degGlobal;
      carousel.style.transform = `rotateY(${currdeg}deg) translateZ(-${global_project_list.length * 3.5}vw)`;
      updateDots();
    });
    carouselDots.appendChild(dot);
  });
  carousel.style.transformOrigin = `50% 50% -${global_project_list.length * 3.5}vw`;
  carousel.style.transform = `translateZ(-${global_project_list.length * 3.5}vw)`
  //updateCarousel();
  $(".next").on("click", { d: "n" }, rotate);
  $(".prev").on("click", { d: "p" }, rotate);

  function rotate(e) {
    if (e.data.d == "n") {
      currdeg = currdeg - degGlobal;
    }
    if (e.data.d == "p") {
      currdeg = currdeg + degGlobal;
    }
    if (currdeg > 360) {
      currdeg = currdeg % 360;
    }
    carousel.style.transform = `rotateY(${currdeg}deg) translateZ(-${global_project_list.length * 3.5}vw)`;

  }
}

function handleResize() {
  window.location.reload();
}

window.addEventListener('resize', handleResize);

function isMobileDevice() {
  return /(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(navigator.userAgent || navigator.vendor || window.opera ) ||  document.documentElement.clientWidth / document.documentElement.clientHeight < 1;
}

window.addEventListener('DOMContentLoaded', (event) => {
  if (isMobileDevice()) {
    const body = document.body;
    const downloadApp = document.getElementById('download');
    body.childNodes.forEach((child) => {
      if (child.nodeType === 1 && child !== downloadApp) {
        child.style.display = 'none';
      }
    });
    const newH1 = document.createElement('h1');
    newH1.textContent = "Caméra Timelapse sur mobile, utilisez l'app !!!";
    newH1.classList.add('global_title_h1');
    body.appendChild(newH1);
  }
});

let titleIsReadable = true;

function change_title_style() {
  const titlePlaceHolder = document.getElementById('title-global');
  const ball = document.getElementById('ball');
  const xyz = document.getElementById('xyz');
  const h1_title = document.getElementById('h1-title');
  if (titleIsReadable) {
    titleIsReadable = false;
    titlePlaceHolder.classList.add('container-title');
    ball.style.display = 'block';
    xyz.style.display = 'block';
  } else {
    titleIsReadable = true;
    titlePlaceHolder.classList.remove('container-title');
    ball.style.display = 'none';
    xyz.style.display = 'none';
    h1_title.style.display = 'block';
  }
}

change_title_style();

