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

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

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

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

  /* which architect are we sharing?
     DEVELOPER (PHP): read the record id from the query string,
     e.g. credentials.php?id=123, then load it from the database. */
  var index = Store.getLastInvite();
  var architect = Store.getArchitect(index);

  if(!architect){
    toast("No architect selected");
    setTimeout(function(){ window.location.href = "architects.html"; }, 1200);
    return;
  }

  /* ---------- fill the credentials card ---------- */
  $("#cPlay").textContent  = PLAY_LINK;
  $("#cApple").textContent = APP_STORE_LINK;
  $("#cUser").textContent  = architect.loginId;
  $("#cPass").textContent  = architect.pass;
  $("#cAid").textContent   = user.email;

  $("#succTitle").textContent = architect.name + " is registered and mapped to your account";
  $("#succSub").textContent   = "Share the app links and credentials with " + architect.name + " (" + architect.mobile + ").";

  var message = buildInviteText(architect, user.email);

  /* ---------- copy buttons ---------- */
  $$(".copy-btn[data-copy]").forEach(function(btn){
    btn.addEventListener("click", function(){
      copyText($("#" + btn.getAttribute("data-copy")).textContent, "Copied to clipboard");
    });
  });

  $("#copyAllBtn").addEventListener("click", function(){
    copyText(message, "Full invite message copied");
  });

  /* ---------- share buttons ---------- */
  $("#shareWA").addEventListener("click", function(){
    window.open("https://wa.me/91" + architect.mobile + "?text=" + encodeURIComponent(message), "_blank");
    toast("Invite opened in WhatsApp");
  });

  $("#shareSMS").addEventListener("click", function(){
    window.location.href = "sms:+91" + architect.mobile + "?body=" + encodeURIComponent(message);
  });

  $("#shareEmail").addEventListener("click", function(){
    var to = architect.email && architect.email !== "—" ? architect.email : "";
    window.location.href = "mailto:" + to +
      "?subject=" + encodeURIComponent("Your Designer Club app access") +
      "&body=" + encodeURIComponent(message);
  });

});
