/* =============================================================
   File: assets/js/architects.js   —  used by architects.html only
   ============================================================= */

document.addEventListener("DOMContentLoaded", function(){

  var user = requireLogin();
  if(!user) return;

  $("#logoutBtn").addEventListener("click", logout);

  var rows   = $("#listRows");
  var cards  = $("#listCards");
  var modal  = $("#editModal");
  var stateEl = $("#edit_state");
  var cityEl  = $("#edit_city");
  var editIndex = -1;

  populateStates(stateEl);
  stateEl.addEventListener("change", function(){ populateCities(stateEl, cityEl); });
  digitsOnly($("#edit_mobile"));
  digitsOnly($("#edit_pin"));

  /* =============================================================
     RENDER LIST
     DEVELOPER (PHP): replace Store.getArchitects() with
     get_architects.php, or render the rows server-side.
     ============================================================= */
  function render(){
    var list = Store.getArchitects();

    if(list.length === 0){
      rows.innerHTML =
        '<tr><td colspan="7" class="empty">No architects mapped yet.<br>' +
        '<a class="btn btn-primary" href="register.html">Register your first architect</a></td></tr>';
      cards.innerHTML =
        '<div class="empty">No architects mapped yet.<br>' +
        '<a class="btn btn-primary" href="register.html">Register your first architect</a></div>';
      return;
    }

    rows.innerHTML = list.map(function(a, i){
      return '<tr>' +
        '<td>' + (i + 1) + '</td>' +
        '<td><strong>' + escapeHtml(a.name) + '</strong>' +
          '<br><small style="color:var(--muted)">' + escapeHtml(a.date) + '</small></td>' +
        '<td>' + escapeHtml(a.mobile) + '</td>' +
        '<td>' + escapeHtml(a.email) + '</td>' +
        '<td>' + escapeHtml(a.city) + '</td>' +
        '<td><span class="pill ' + a.status + '">' + (a.status === "invited" ? "Invited" : "Active") + '</span></td>' +
        '<td><div class="row-actions">' +
          '<button class="copy-btn" data-edit="' + i + '">Edit</button>' +
          '<button class="copy-btn" data-resend="' + i + '">Resend invite</button>' +
        '</div></td>' +
      '</tr>';
    }).join("");

    cards.innerHTML = list.map(function(a, i){
      return '<article class="arch-card">' +
        '<div class="ac-head">' +
          '<div><div class="ac-name">' + escapeHtml(a.name) + '</div>' +
          '<div class="ac-date">Added ' + escapeHtml(a.date) + '</div></div>' +
          '<span class="pill ' + a.status + '">' + (a.status === "invited" ? "Invited" : "Active") + '</span>' +
        '</div>' +
        '<dl>' +
          '<dt>Contact</dt><dd>' + escapeHtml(a.mobile) + '</dd>' +
          '<dt>Email</dt><dd>' + escapeHtml(a.email) + '</dd>' +
          '<dt>City</dt><dd>' + escapeHtml(a.city) + '</dd>' +
        '</dl>' +
        '<div class="ac-actions">' +
          '<button class="copy-btn" data-edit="' + i + '">Edit</button>' +
          '<button class="copy-btn" data-resend="' + i + '">Resend invite</button>' +
        '</div>' +
      '</article>';
    }).join("");
  }

  /* event delegation — works for both the table and the card list */
  document.addEventListener("click", function(e){
    var editBtn   = e.target.closest("[data-edit]");
    var resendBtn = e.target.closest("[data-resend]");
    if(editBtn)   openEdit(parseInt(editBtn.getAttribute("data-edit"), 10));
    if(resendBtn){
      Store.setLastInvite(parseInt(resendBtn.getAttribute("data-resend"), 10));
      window.location.href = "credentials.html";
    }
  });

  /* =============================================================
     EDIT MODAL
     ============================================================= */
  function openEdit(i){
    var a = Store.getArchitect(i);
    if(!a) return;
    editIndex = i;

    $("#edit_id").value      = i;      /* PHP: use the database id here */
    $("#edit_name").value    = a.name;
    $("#edit_mobile").value  = a.mobile;
    $("#edit_email").value   = a.email;
    $("#edit_pin").value     = a.pin || "";
    $("#edit_address").value = a.address || "";
    stateEl.value = a.state || "";
    populateCities(stateEl, cityEl, a.city !== "—" ? a.city : "");

    Validate.reset("#editForm");
    modal.hidden = false;
    document.body.classList.add("no-scroll");
    $("#edit_name").focus();
  }

  function closeEdit(){
    modal.hidden = true;
    document.body.classList.remove("no-scroll");
    editIndex = -1;
  }

  $("#editClose").addEventListener("click", closeEdit);
  $("#editCancel").addEventListener("click", closeEdit);
  modal.addEventListener("click", function(e){ if(e.target === modal) closeEdit(); });
  document.addEventListener("keydown", function(e){
    if(e.key === "Escape" && !modal.hidden) closeEdit();
  });

  $("#editForm").addEventListener("submit", function(e){
    e.preventDefault();

    var name    = $("#edit_name").value.trim();
    var mobile  = $("#edit_mobile").value.trim();
    var email   = $("#edit_email").value.trim();
    var pin     = $("#edit_pin").value.trim();
    var address = $("#edit_address").value.trim();

    var ok = true;
    ok = Validate.mark("ef-name",    Validate.filled(name))    && ok;
    ok = Validate.mark("ef-mobile",  Validate.mobile(mobile))  && ok;
    ok = Validate.mark("ef-email",   Validate.email(email))    && ok;
    ok = Validate.mark("ef-pin",     Validate.pin(pin))        && ok;
    ok = Validate.mark("ef-address", Validate.filled(address)) && ok;
    if(!ok){ toast("Please fix the highlighted fields"); return; }

    /* DEVELOPER (PHP): post this form to update_architect.php */
    Store.updateArchitect(editIndex, {
      name:    name,
      mobile:  mobile,
      email:   email,
      state:   stateEl.value,
      city:    cityEl.value || "—",
      pin:     pin,
      address: address,
      loginId: mobile
    });

    closeEdit();
    render();
    toast("Architect details updated");
  });

  render();

});
