(function () {
  "use strict";

  var MSG = {
    titleLogin: "ورود",
    titleSignup: "ثبت\u200cنام",
    subtitlePhone: "شماره موبایل خود را وارد کنید",
    subtitleCodeLogin: "کد ورود را وارد کنید",
    subtitleCodeSignup: "کد تأیید و اطلاعات حساب را تکمیل کنید",
    toggleSignup: "حساب کاربری ندارید؟ ثبت\u200cنام کنید",
    toggleLogin: "حساب دارید؟ ورود",
    btnLogin: "ورود",
    btnSignup: "ثبت\u200cنام و ورود",
    btnSendOtp: "دریافت کد",
  };

  function initMobileAuth() {
    var root = document.getElementById("ty-auth-root");
    if (!root) return;

    var API = root.dataset.identityApi || "http://localhost:8001";
    var intent = "login";
    var mobile = "";
    var countdownTimer = null;
    var signupMode = false;
    var step = "phone";

    function $(id) {
      return document.getElementById(id);
    }

    function showError(msg) {
      var el = $("ty-mobile-error");
      if (!el) return;
      el.textContent = msg || "";
      el.hidden = !msg;
    }

    function profileFromDom() {
      return {
        display_name: (($("ty-display-name") || {}).value || "").trim(),
        email: (($("ty-email") || {}).value || "").trim(),
        username: (($("ty-username") || {}).value || "").trim(),
        password: (($("ty-password") || {}).value || ""),
      };
    }

    function profileComplete(p) {
      return (
        p.display_name.length > 0 &&
        p.email.length > 0 &&
        p.username.length >= 3 &&
        p.password.length >= 8
      );
    }

    function showProfileFields(show) {
      var fields = $("ty-signup-fields");
      if (fields) fields.hidden = !show;
    }

    function updateHeader() {
      var title = $("ty-auth-title");
      var subtitle = $("ty-auth-subtitle");
      if (title) {
        title.textContent = signupMode ? MSG.titleSignup : MSG.titleLogin;
      }
      if (!subtitle) return;
      if (step === "phone") {
        subtitle.textContent = MSG.subtitlePhone;
      } else if (intent === "login") {
        subtitle.textContent = MSG.subtitleCodeLogin;
      } else {
        subtitle.textContent = MSG.subtitleCodeSignup;
      }
    }

    function updateToggleSignup() {
      var toggle = $("ty-toggle-signup");
      if (!toggle) return;
      toggle.textContent = signupMode ? MSG.toggleLogin : MSG.toggleSignup;
    }

    function showPanel(name) {
      var passwordPanel = $("ty-panel-password");
      var mobilePanel = $("ty-panel-mobile");
      document.querySelectorAll(".ty-auth-tab").forEach(function (tab) {
        var active = tab.getAttribute("data-ty-tab") === name;
        tab.classList.toggle("ty-auth-tab--active", active);
        tab.setAttribute("aria-selected", active ? "true" : "false");
      });
      if (passwordPanel) {
        passwordPanel.classList.toggle("ty-auth-panel--active", name === "password");
        passwordPanel.hidden = name !== "password";
      }
      if (mobilePanel) {
        mobilePanel.classList.toggle("ty-auth-panel--active", name === "mobile");
        mobilePanel.hidden = name !== "mobile";
        if (name === "mobile") {
          var input = step === "phone" ? $("ty-mobile-input") : $("ty-otp-code");
          if (input) setTimeout(function () { input.focus(); }, 80);
        }
      }
      showError("");
    }

    function normalizePhone(v) {
      var d = String(v || "")
        .replace(/[\u06F0-\u06F9\u0660-\u0669]/g, function (c) {
          return String.fromCharCode(c.charCodeAt(0) & 15);
        })
        .replace(/\D/g, "");
      if (d.indexOf("98") === 0 && d.length === 12) d = "0" + d.slice(2);
      if (d.length === 10 && d.charAt(0) !== "0") d = "0" + d;
      return d;
    }

    function normalizeCode(v) {
      return String(v || "")
        .replace(/[\u06F0-\u06F9\u0660-\u0669]/g, function (c) {
          return String.fromCharCode(c.charCodeAt(0) & 15);
        })
        .replace(/\D/g, "")
        .slice(0, 4);
    }

    function isValidMobile(m) {
      return /^09\d{9}$/.test(m);
    }

    function apiPost(path, body) {
      return fetch(API + path, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(body),
      }).then(function (res) {
        return res.json().catch(function () { return {}; }).then(function (data) {
          if (!res.ok) {
            var msg =
              (data.error && data.error.message) ||
              (typeof data.detail === "string" ? data.detail : null) ||
              "خطا در ارتباط با سرور";
            throw new Error(msg);
          }
          return data;
        });
      }).catch(function (err) {
        if (err instanceof TypeError) {
          throw new Error("اتصال به سرویس هویت برقرار نشد (" + API + ")");
        }
        throw err;
      });
    }

    function setLoading(btn, loading) {
      if (!btn) return;
      btn.disabled = loading;
      if (!btn.dataset.label) btn.dataset.label = btn.textContent;
      btn.textContent = loading ? "..." : btn.dataset.label;
    }

    function startCountdown(sec) {
      var el = $("ty-countdown");
      if (!el) return;
      if (countdownTimer) clearInterval(countdownTimer);
      var left = sec;
      el.hidden = false;
      function tick() {
        el.textContent = "ارسال مجدد تا " + left + " ثانیه";
        if (left <= 0) {
          el.hidden = true;
          clearInterval(countdownTimer);
          return;
        }
        left -= 1;
      }
      tick();
      countdownTimer = setInterval(tick, 1000);
    }

    function goToCodeStep(res) {
      intent = res.intent;
      step = "code";
      startCountdown(res.expires_in || 120);
      var stepPhone = $("ty-mobile-step-phone");
      var stepCode = $("ty-mobile-step-code");
      if (stepPhone) stepPhone.hidden = true;
      if (stepCode) stepCode.hidden = false;
      var display = $("ty-mobile-display");
      if (display) display.textContent = mobile;

      var needProfile = res.intent === "register";
      showProfileFields(signupMode || needProfile);

      var verifyBtn = $("ty-verify-otp");
      if (verifyBtn) {
        verifyBtn.textContent = res.intent === "login" ? MSG.btnLogin : MSG.btnSignup;
      }
      updateHeader();
      var otpInput = $("ty-otp-code");
      if (otpInput) {
        otpInput.value = "";
        otpInput.focus();
      }
    }

    function goToPhoneStep() {
      step = "phone";
      var stepCode = $("ty-mobile-step-code");
      var stepPhone = $("ty-mobile-step-phone");
      if (stepCode) stepCode.hidden = true;
      if (stepPhone) stepPhone.hidden = false;
      showProfileFields(signupMode);
      showError("");
      updateHeader();
      if (countdownTimer) clearInterval(countdownTimer);
      var otpInput = $("ty-otp-code");
      if (otpInput) otpInput.value = "";
    }

    document.querySelectorAll(".ty-auth-tab").forEach(function (tab) {
      tab.addEventListener("click", function (e) {
        e.preventDefault();
        showPanel(tab.getAttribute("data-ty-tab"));
      });
    });

    var toggleSignup = $("ty-toggle-signup");
    if (toggleSignup) {
      toggleSignup.addEventListener("click", function () {
        signupMode = !signupMode;
        showProfileFields(signupMode);
        updateToggleSignup();
        updateHeader();
        showError("");
      });
    }

    var requestBtn = $("ty-request-otp");
    if (requestBtn) {
      requestBtn.addEventListener("click", function () {
        showError("");
        mobile = normalizePhone(($("ty-mobile-input") || {}).value);
        if (!isValidMobile(mobile)) {
          showError("شماره موبایل صحیح نیست (مثال: 09123456789)");
          return;
        }
        var profile = profileFromDom();
        if (signupMode && !profileComplete(profile)) {
          showError("نام، ایمیل، نام کاربری (حداقل ۳ کاراکتر) و رمز (حداقل ۸) الزامی است");
          return;
        }
        setLoading(requestBtn, true);
        apiPost("/api/v1/auth/mobile/start", { mobile: mobile })
          .then(function (res) {
            if (res.intent === "login" && signupMode) {
              signupMode = false;
              showProfileFields(false);
              updateToggleSignup();
              showError("این شماره ثبت شده است — کد ورود ارسال شد");
            }
            goToCodeStep(res);
          })
          .catch(function (e) {
            showError(e.message);
          })
          .finally(function () {
            setLoading(requestBtn, false);
          });
      });
    }

    var backBtn = $("ty-back-phone");
    if (backBtn) {
      backBtn.addEventListener("click", goToPhoneStep);
    }

    function verifyOtp(codeOverride) {
      showError("");
      var code = normalizeCode(codeOverride || ($("ty-otp-code") || {}).value);
      if (code.length !== 4) {
        showError("کد ۴ رقمی را وارد کنید");
        return;
      }
      var profile = profileFromDom();
      var needProfile = intent === "register" || signupMode;
      if (needProfile && !profileComplete(profile)) {
        showError("نام، ایمیل، نام کاربری و رمز (۸+ کاراکتر) الزامی است");
        return;
      }
      var payload = {
        mobile: mobile,
        code: code,
        create_handoff: true,
        display_name: profile.display_name || undefined,
      };
      if (profileComplete(profile)) {
        payload.email = profile.email;
        payload.username = profile.username;
        payload.password = profile.password;
      }
      var verifyBtn = $("ty-verify-otp");
      setLoading(verifyBtn, true);
      apiPost("/api/v1/auth/mobile/complete", payload)
        .then(function (res) {
          if (res.redirect_url) {
            window.location.href = res.redirect_url;
            return;
          }
          if (res.access_token) {
            window.location.href = root.dataset.callbackUrl || "/auth/callback";
            return;
          }
          throw new Error("پاسخ ورود نامعتبر بود");
        })
        .catch(function (e) {
          showError(e.message);
          setLoading(verifyBtn, false);
        });
    }

    var verifyBtn = $("ty-verify-otp");
    if (verifyBtn) verifyBtn.addEventListener("click", function () { verifyOtp(); });

    var otpInput = $("ty-otp-code");
    if (otpInput) {
      otpInput.addEventListener("input", function (e) {
        var next = normalizeCode(e.target.value);
        e.target.value = next;
        if (next.length !== 4) return;
        var profile = profileFromDom();
        var canAuto = intent === "login" || profileComplete(profile);
        if (canAuto) verifyOtp(next);
      });
    }

    var mobileInput = $("ty-mobile-input");
    if (mobileInput) {
      mobileInput.addEventListener("input", function (e) {
        e.target.value = normalizePhone(e.target.value);
      });
      mobileInput.addEventListener("keydown", function (e) {
        if (e.key === "Enter") {
          e.preventDefault();
          if (requestBtn) requestBtn.click();
        }
      });
    }

    try {
      if (sessionStorage.getItem("ty_signup_mode") === "1") {
        signupMode = true;
        sessionStorage.removeItem("ty_signup_mode");
        showProfileFields(true);
      }
    } catch (ignore) {}

    updateToggleSignup();
    updateHeader();
    showPanel("mobile");
  }

  if (document.readyState === "loading") {
    document.addEventListener("DOMContentLoaded", initMobileAuth);
  } else {
    initMobileAuth();
  }
})();
