import { auth } from "./firebase-config.js";
import { showLoader, hideLoader } from "./loader.js";
import { showToast } from "./toast.js";

import {
  sendPasswordResetEmail
} from "https://www.gstatic.com/firebasejs/10.12.2/firebase-auth.js";

const resetPasswordForm = document.getElementById("resetPasswordForm");
const resetEmailInput = document.getElementById("resetEmail");
const submitButton = resetPasswordForm?.querySelector("button[type='submit']");

function setLoading(isLoading) {
  if (!submitButton) return;

  submitButton.disabled = isLoading;
  submitButton.textContent = isLoading ? "Sending..." : "Send Reset Link";
}

resetPasswordForm?.addEventListener("submit", async function (event) {
  event.preventDefault();

  const email = resetEmailInput.value.trim().toLowerCase();

  if (!email) {
    showToast("Please enter your email address.", "warning");
    return;
  }

  showLoader("Sending password reset link...");
  setLoading(true);

  try {
    await sendPasswordResetEmail(auth, email);

    showToast("Password reset email sent. Please check your inbox.", "success");

    resetPasswordForm.reset();
  } catch (error) {
    console.error("Password reset error:", error);
    showToast("Could not send reset email: " + error.message, "error");
  } finally {
    setLoading(false);
    hideLoader();
  }
});