export async function render(container) {
  container.innerHTML = `
    <div class="panel-header">
      <h2>Create Project</h2>
    </div>

    <div class="form-panel">
      <div class="form-group">
        <label>Project Name</label>
        <input type="text" id="projectName" required />
      </div>

      <div class="form-group">
        <label>Project Slug</label>
        <input type="text" id="projectSlug" placeholder="e.g. alpha-core" />
      </div>

      <div class="form-group">
        <label>Description</label>
        <textarea id="projectDescription" rows="4"></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="createProjectBtn" class="btn-primary">
          Create Project
        </button>
      </div>

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

  const token = localStorage.getItem('token');
  const msg = container.querySelector('#createMsg');

  const nameInput = container.querySelector('#projectName');
  const slugInput = container.querySelector('#projectSlug');
  const descInput = container.querySelector('#projectDescription');
  const headSelect = container.querySelector('#projectHead');
  const relatedSelect = container.querySelector('#relatedProject');
  const createBtn = container.querySelector('#createProjectBtn');

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

  const API = window.location.origin;

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

    const data = await res.json();
    const users = data.users || [];

    headSelect.innerHTML = '<option value="">Select user</option>';

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

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

    const data = await res.json();
    if (!data.success) return;

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

  /* ---------------------------
     CREATE PROJECT
  --------------------------- */
  createBtn.onclick = async () => {
    const payload = {
      name: nameInput.value.trim(),
      slug: slugInput.value.trim(),
      description: descInput.value.trim(),
      projectHeadUserId: headSelect.value || null,
      relatedProjectId: relatedSelect.value || null
    };

    if (!payload.name) {
      msg.textContent = 'Project name is required';
      return;
    }

    msg.textContent = 'Creating project...';

    const res = await fetch(`${API}/projects`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        Authorization: `Bearer ${token}`
      },
      body: JSON.stringify(payload)
    });

    const data = await res.json();

    if (!data.success) {
      msg.textContent = 'Failed to create project';
      return;
    }

    msg.textContent = 'Project created successfully';

    setTimeout(() => {
      loadPanel('projects');
    }, 600);
  };

  /* ---------------------------
     INIT
  --------------------------- */
  await loadUsers();
  await loadProjects();
}
