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

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

import {
  doc,
  getDoc
} from "https://www.gstatic.com/firebasejs/10.12.2/firebase-firestore.js";

const loginForm = document.getElementById("loginForm");
const emailInput = document.getElementById("email");
const passwordInput = document.getElementById("password");

const submitButton = loginForm?.querySelector("button[type='submit']");

const ROLE_HOME = {
  director: "dashboard.html",
  coach: "dashboard.html",
  player: "player-dashboard.html",
  biokineticist: "bio-dashboard.html"
};

function getRoleHome(role) {
  return ROLE_HOME[role] || "dashboard.html";
}

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

  const email = emailInput.value.trim().toLowerCase();
  const password = passwordInput.value;

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

  showLoader("Signing in...");
  
  if (submitButton) {
    submitButton.disabled = true;
    submitButton.textContent = "Signing In...";
  }

  try {
    const result = await signInWithEmailAndPassword(auth, email, password);

    const userRef = doc(db, "users", result.user.uid);
    const userSnap = await getDoc(userRef);

    if (!userSnap.exists()) {
      await signOut(auth);

      showToast(
        "User profile not found. Please contact support.",
        "error"
      );

      return;
    }

    const profile = userSnap.data();

    if (profile.status && profile.status !== "active") {
      await signOut(auth);

      showToast("Your account is not active.", "error");

      return;
    }

    const legal = profile.legalAcceptance || {};

    if (!legal.requiredAccepted) {
      window.location.href = "legal-acceptance.html";
      return;
    }

    window.location.href = getRoleHome(profile.role);
  } catch (error) {
    console.error("Login error:", error);
    showToast("Login failed: " + error.message, "error");
  } finally {
    if (submitButton) {
      submitButton.disabled = false;
      submitButton.textContent = "Sign In";
    }

    hideLoader();
  }
});