// /public/dashboard/panels/users.js

/* ============================================================
   Small local API helper (matches your auth model)
============================================================ */
async function apiFetch(url, options = {}) {
  const token = localStorage.getItem('token'); // same token dashboard uses

  const headers = {
    'Content-Type': 'application/json',
    ...(options.headers || {})
  };

  if (token) {
    headers['Authorization'] = `Bearer ${token}`;
  }

  const res = await fetch(url, {
    ...options,
    headers
  });

  if (!res.ok) {
    let err;
    try {
      err = await res.json();
    } catch {
      throw new Error('Request failed');
    }
    throw new Error(err.message || 'Request failed');
  }

  return res.json();
}

/* ============================================================
   Render Users Panel
============================================================ */
export function render(el) {
  el.innerHTML = `
    <h2>Users</h2>

    <div id="usersList">
      <!-- existing users list stays untouched -->
    </div>

    <hr />

    <h2>Invite User</h2>

    <div class="invite-form">
      <input
        type="email"
        id="inviteEmail"
        placeholder="User email"
      />

      <select id="inviteRole">
        <option value="user">User</option>
        <option value="manager">Manager</option>
        <option value="admin">Admin</option>
      </select>

      <button id="sendInviteBtn">Send Invite</button>
    </div>

    <div id="inviteMessage"></div>

    <hr />

    <h2>Invites</h2>
    <div id="inviteList"></div>
  `;

  document
    .getElementById('sendInviteBtn')
    .addEventListener('click', sendInvite);

  loadInvites();
}

/* ============================================================
   Send Invite
============================================================ */
async function sendInvite() {
  const emailInput = document.getElementById('inviteEmail');
  const roleInput = document.getElementById('inviteRole');
  const messageBox = document.getElementById('inviteMessage');

  const email = emailInput.value.trim();
  const role = roleInput.value;

  if (!email) {
    messageBox.innerText = 'Email is required';
    return;
  }

  messageBox.innerText = 'Sending invite...';

  try {
    await apiFetch('/dashboard/invites/create', {
      method: 'POST',
      body: JSON.stringify({ email, role })
    });

    messageBox.innerText = 'Invite sent successfully';
    emailInput.value = '';

    loadInvites();

  } catch (err) {
    console.error(err);
    messageBox.innerText = err.message || 'Failed to send invite';
  }
}

/* ============================================================
   Load Invites
============================================================ */
async function loadInvites() {
  const list = document.getElementById('inviteList');
  list.innerHTML = 'Loading invites...';

  try {
    const res = await apiFetch('/dashboard/invites/list');
    renderInvites(res.invites || []);
  } catch (err) {
    console.error(err);
    list.innerHTML = 'Failed to load invites';
  }
}

/* ============================================================
   Render Invites
============================================================ */
function renderInvites(invites) {
  const list = document.getElementById('inviteList');
  list.innerHTML = '';

  if (!invites.length) {
    list.innerHTML = '<p>No invites found</p>';
    return;
  }

  invites.forEach(invite => {
    const row = document.createElement('div');
    row.className = 'invite-row';

    row.innerHTML = `
      <strong>${invite.email}</strong>
      <span>(${invite.role})</span>
      <span>Status: ${invite.status}</span>
      <span>Expires: ${new Date(invite.expiresAt).toLocaleString()}</span>
      ${
        invite.status === 'pending'
          ? `<button class="revoke-btn">Revoke</button>`
          : ''
      }
    `;

    if (invite.status === 'pending') {
      row
        .querySelector('.revoke-btn')
        .addEventListener('click', () =>
          revokeInvite(invite.inviteID)
        );
    }

    list.appendChild(row);
  });
}

/* ============================================================
   Revoke Invite
============================================================ */
async function revokeInvite(inviteID) {
  if (!confirm('Revoke this invite?')) return;

  try {
    await apiFetch('/dashboard/invites/revoke', {
      method: 'POST',
      body: JSON.stringify({ inviteID })
    });

    loadInvites();

  } catch (err) {
    console.error(err);
    alert('Failed to revoke invite');
  }
}
