export async function render(container) {
  const projectId = window.currentProjectId;
  if (!projectId) {
    container.innerHTML = '<p>No project selected</p>';
    return;
  }

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

    <div class="form-panel">
      <div class="form-group">
        <label>Name</label>
        <input id="name" />
      </div>

      <div class="form-group">
        <label>Slug</label>
        <input id="slug" />
      </div>

      <div class="form-group">
        <label>Description</label>
        <textarea id="description"></textarea>
      </div>

      <div class="form-group">
        <label>Project Head</label>
        <select id="projectHead"></select>
      </div>

      <div class="form-group">
        <label>Related Project</label>
        <select id="relatedProject">
          <option value="">None</option>
        </select>
      </div>

      <div class="form-actions">
        <button id="saveBtn" class="btn-primary">Save Changes</button>
      </div>

      <div id="msg" class="form-message"></div>
    </div>
  `;

  const token = localStorage.getItem('token');
  const msg = container.querySelector('#msg');
  const API = window.location.origin;

  const nameInput = container.querySelector('#name');
  const slugInput = container.querySelector('#slug');
  const descInput = container.querySelector('#description');
  const headSelect = container.querySelector('#projectHead');
  const relatedSelect = container.querySelector('#relatedProject');

  /* ---------------------------
     LOAD USERS
  --------------------------- */
  async function loadUsers() {
    const res = await fetch(`${API}/users/org`, {
      headers: { Authorization: `Bearer ${token}` }
    });
    const data = await res.json();

    data.users.forEach(u => {
      const opt = document.createElement('option');
      opt.value = u.id;
      opt.textContent = `${u.firstName} ${u.lastName}`;
      headSelect.appendChild(opt);
    });
  }

  /* ---------------------------
     LOAD PROJECTS
  --------------------------- */
  async function loadProjects() {
    const res = await fetch(`${API}/projects`, {
      headers: { Authorization: `Bearer ${token}` }
    });
    const data = await res.json();

    data.projects.forEach(p => {
      if (p.id === projectId) return;
      const opt = document.createElement('option');
      opt.value = p.id;
      opt.textContent = p.name;
      relatedSelect.appendChild(opt);
    });
  }

  /* ---------------------------
     LOAD CURRENT PROJECT
  --------------------------- */
  async function loadProject() {
    const res = await fetch(`${API}/projects/${projectId}`, {
      headers: { Authorization: `Bearer ${token}` }
    });
    const data = await res.json();
    const p = data.project;

    nameInput.value = p.name || '';
    slugInput.value = p.slug || '';
    descInput.value = p.description || '';
    headSelect.value = p.projectHeadUserId || '';
    relatedSelect.value = p.relatedProjectId || '';
  }

  /* ---------------------------
     SAVE
  --------------------------- */
  container.querySelector('#saveBtn').onclick = async () => {
    msg.textContent = 'Saving...';

    const res = await fetch(`${API}/projects/${projectId}`, {
      method: 'PATCH',
      headers: {
        'Content-Type': 'application/json',
        Authorization: `Bearer ${token}`
      },
      body: JSON.stringify({
        name: nameInput.value,
        slug: slugInput.value,
        description: descInput.value,
        projectHeadUserId: headSelect.value || null,
        relatedProjectId: relatedSelect.value || null
      })
    });

    const data = await res.json();

    if (!data.success) {
      msg.textContent = 'Update failed';
      return;
    }

    msg.textContent = 'Project updated';
    setTimeout(() => loadPanel('projects'), 600);
  };

  await loadUsers();
  await loadProjects();
  await loadProject();
}
