(function () {
  var shell = document.querySelector(".js-auth-shell");
  if (!shell) return;

  var defaultView = document.body.getAttribute("data-default-view");
  var buttons = document.querySelectorAll(".js-auth-switch");
  var panel = shell.querySelector(".auth-panel");
  var activeView = defaultView === "register" ? "register" : defaultView === "verify" ? "verify" : "login";
  var lock = false;

  function setView(view) {
    if (lock || view === activeView) return;
    lock = true;
    if (panel) panel.classList.add("is-changing");
    
    // Remove all view classes
    shell.classList.remove("is-register", "is-verify");
    
    if (view === "register") {
      shell.classList.add("is-register");
    } else if (view === "verify") {
      shell.classList.add("is-verify");
    }
    
    activeView = view;

    setTimeout(function () {
      if (panel) panel.classList.remove("is-changing");
      lock = false;
    }, 380);
  }

  // Set initial view
  if (activeView === "register") {
    shell.classList.add("is-register");
  } else if (activeView === "verify") {
    shell.classList.add("is-verify");
  }

  window.requestAnimationFrame(function () {
    shell.classList.add("is-ready");
  });

  buttons.forEach(function (btn) {
    btn.addEventListener("click", function () {
      var switchTo = btn.getAttribute("data-switch");
      setView(switchTo);
      
      // Dispatch custom event for OTP flow
      var event = new CustomEvent('authSwitched', { detail: switchTo });
      document.dispatchEvent(event);
    });
  });
})();
