// Fetch LabelStudioProjects from backend and render as selectable cards
window.addEventListener('DOMContentLoaded', () => {
  let projectsList = document.getElementById('projects-list');
  const selectedIds = new Set();
  if (!projectsList) {
    // Try to create the container if missing
    projectsList = document.createElement('div');
    projectsList.id = 'projects-list';
    document.body.appendChild(projectsList);
  }
  else{console.log("noep")}
  fetch('/api/label-studio-projects')
    .then(res => res.json())
    .then(projects => {
      projectsList.innerHTML = '';
      if (!projects || projects.length === 0) {
        projectsList.innerHTML = '<div>No Label Studio projects found</div>';
        return;
      }
      for (const project of projects) {
        // Only show card if there is at least one non-empty annotation class
        const annotationClasses = Object.entries(project.annotationCounts || {})
          .filter(([label, count]) => label && label.trim() !== '');
        if (annotationClasses.length === 0) continue;
        const card = document.createElement('div');
        card.className = 'card';
        card.style.background = '#f5f5f5';
        card.style.borderRadius = '12px';
        card.style.overflow = 'hidden';
        card.style.boxShadow = '0 2px 8px rgba(0,0,0,0)';
        card.style.display = 'flex';
        card.style.background = 'white';
        card.style.cursor = 'pointer';
        card.tabIndex = 0;
        card.setAttribute('role', 'button');
        card.setAttribute('aria-label', `Open project ${project.title || project.project_id}`);

        // Selection logic
        card.dataset.projectId = project.project_id;
        card.addEventListener('click', () => {
          card.classList.toggle('selected');
          if (card.classList.contains('selected')) {
            card.style.background = '#009eac'; // main dif color for card
            selectedIds.add(project.project_id);
          } else {
            card.style.background = 'white'; // revert card color
            selectedIds.delete(project.project_id);
          }
          // Debug: log selected ids array
          console.log(Array.from(selectedIds));
        });

        // Info
        const infoDiv = document.createElement('div');
        infoDiv.className = 'info';
        infoDiv.style.background = 'rgba(210, 238, 240)';
        infoDiv.style.flex = '1';
        infoDiv.style.padding = '16px';
        infoDiv.innerHTML = `
          <h3 style="margin:0 0 8px 0;font-size:1.5em;font-weight:bold;">${project.project_id ?? 'N/A'}  &nbsp;&nbsp;&nbsp; ${project.title || 'Untitled'}</h3>
          <div class="label-classes" style="font-size:1em;">
            ${annotationClasses.map(([label, count]) => `<p>${label}: ${count}</p>`).join('')}
          </div>
        `;

        card.appendChild(infoDiv);
        projectsList.appendChild(card);
      }
    })
    .catch(() => {
      projectsList.innerHTML = '<div>Error loading Label Studio projects</div>';
    });

    // Add Next button at the bottom right of the page
    const nextBtn = document.createElement('button');
    nextBtn.id = 'next-btn';
    nextBtn.className = 'button';
    nextBtn.textContent = 'Next';
    nextBtn.style.position = 'fixed';
    nextBtn.style.right = '32px';
    nextBtn.style.bottom = '32px';
    nextBtn.style.zIndex = '1000';
    document.body.appendChild(nextBtn);

    // Get training_project_id from URL
    const urlParams = new URLSearchParams(window.location.search);
    const trainingProjectId = urlParams.get('id');

    // Next button click handler
    nextBtn.addEventListener('click', () => {
        console.log(trainingProjectId)
      if (!trainingProjectId) {
        alert('No training project selected.');
        return;
      }
      if (selectedIds.size === 0) {
        alert('Please select at least one Label Studio project.');
        return;
      }
      const annotationProjectsJson = JSON.stringify(Array.from(selectedIds));
      fetch('/api/training-project-details', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          project_id: Number(trainingProjectId),
          annotation_projects: Array.from(selectedIds)
        })
      })
      .then(res => res.json())
      .then(data => {
        alert('TrainingProjectDetails saved!');
        console.log(data);
        // Redirect to start-training.html with id
        window.location.href = `/setup-training-project.html?id=${trainingProjectId}`;
      })
      .catch(err => {
        alert('Error saving TrainingProjectDetails');
        console.error(err);
      });
    });

    // Add description field above the project cards
    const descDiv = document.createElement('div');
    descDiv.id = 'dashboard-description';
    descDiv.style.width = '100%';
    descDiv.style.maxWidth = '900px';
    descDiv.style.margin = '0 auto 24px auto';
    descDiv.style.padding = '18px 24px';
    descDiv.style.background = '#eaf7fa';
    descDiv.style.borderRadius = '12px';
    descDiv.style.boxShadow = '0 2px 8px rgba(0,0,0,0.04)';
    descDiv.style.fontSize = '1.15em';
    descDiv.style.color = '#009eac';
    descDiv.style.textAlign = 'center';
    descDiv.textContent = 'Select one or more Label Studio projects by clicking the cards below. The annotation summary for each project is shown. Click Next to continue.';
    projectsList.parentNode.insertBefore(descDiv, projectsList);
});
