// /dashboard/panels/projects.js

export async function render(container) {

  container.innerHTML = `
    <div class="panel-header">
      <h2>Projects</h2>
    </div>

    <div id="projectsMsg" class="form-message"></div>

    <table class="data-table">
      <thead>
        <tr>
          <th>Name</th>
          <th>Slug</th>
          <th>Project Head</th>
          <th>Related Project</th>
          <th>Actions</th>
        </tr>
      </thead>
      <tbody id="projectsBody"></tbody>
    </table>
  `;

  const msg = container.querySelector('#projectsMsg');
  const tbody = container.querySelector('#projectsBody');

  const token = localStorage.getItem('token');
  if (!token) {
    msg.textContent = 'Not authenticated';
    return;
  }

  const API = window.location.origin;

  async function loadProjects() {

    msg.textContent = 'Loading projects...';
    tbody.innerHTML = '';

    try {

      const res = await fetch(`${API}/projects`, {
        headers: { Authorization: `Bearer ${token}` }
      });

      const data = await res.json();

      const projects = Array.isArray(data)
        ? data
        : data.projects || [];

      if (!projects.length) {
        msg.textContent = 'No projects found';
        return;
      }

      msg.textContent = '';

      projects.forEach(p => {

        const tr = document.createElement('tr');

        tr.innerHTML = `
          <td>${p.name}</td>
          <td>${p.slug || '—'}</td>
          <td>${p.headName || '—'}</td>
          <td>${p.relatedProjectName || '—'}</td>
          <td>
            <button class="assign-btn">Assign Users</button>
            <button class="edit-btn">Edit</button>
          </td>
        `;

        tr.querySelector('.assign-btn').onclick = () => {
          window.currentProjectId = p.id;
          window.currentProjectName = p.name;
          loadPanel('assignUsers');
        };

        tr.querySelector('.edit-btn').onclick = () => {
          window.currentProjectId = p.id;
          loadPanel('editProject');
        };

        tbody.appendChild(tr);
      });

    } catch (err) {
      console.error(err);
      msg.textContent = 'Failed to load projects';
    }
  }

  loadProjects();
}
