// ==============================
// AUTH.JS
// MINING CLOUDE MASTER
// ==============================

import {
  auth,
  db
} from "/firebase/firebase-config.js";

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

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

// ==============================
// LOGIN FORM
// ==============================

const loginForm =
  document.getElementById(
    "loginForm"
  );

if (loginForm) {

  loginForm.addEventListener(
    "submit",
    async (e) => {

      e.preventDefault();

      const email =
        document.getElementById(
          "email"
        ).value.trim();

      const password =
        document.getElementById(
          "password"
        ).value;

      const loginBtn =
        document.querySelector(
          ".btn-login"
        );

      try {

        loginBtn.innerText =
          "Loading...";
        loginBtn.disabled =
          true;

        const userCredential =
          await signInWithEmailAndPassword(
            auth,
            email,
            password
          );

        const uid =
          userCredential.user.uid;

        const userDoc =
          await getDoc(
            doc(db, "users", uid)
          );

        if (
          userDoc.exists()
        ) {

          const userData =
            userDoc.data();

          localStorage.setItem(
            "miningUser",
            JSON.stringify(
              userData
            )
          );

          alert(
            "Login berhasil!"
          );

          window.location.replace(
  "/pages/dashboard.html"
          );

        }

      } catch (error) {

        console.error(error);

        let message =
          "Login gagal";

        switch (
          error.code
        ) {

          case "auth/user-not-found":
          case "auth/invalid-credential":
            message =
              "Email atau password salah";
            break;

          case "auth/wrong-password":
            message =
              "Password salah";
            break;

          case "auth/invalid-email":
            message =
              "Email tidak valid";
            break;

          default:
            message =
              error.message;
        }

        alert(message);

      } finally {

        loginBtn.innerText =
          "Login Sekarang";

        loginBtn.disabled =
          false;

      }

    }
  );
}

// ==============================
// REGISTER FORM
// ==============================

const registerForm =
  document.getElementById(
    "registerForm"
  );

if (registerForm) {

  registerForm.addEventListener(
    "submit",
    async (e) => {

      e.preventDefault();

      const username =
        document.getElementById(
          "username"
        ).value.trim();

      const email =
        document.getElementById(
          "email"
        ).value.trim();

      const password =
        document.getElementById(
          "password"
        ).value;

      const confirmPassword =
        document.getElementById(
          "confirmPassword"
        ).value;

      const referralCodeInput =
        document.getElementById(
          "referralCode"
        )?.value || "";

      const registerBtn =
        document.querySelector(
          ".btn-login"
        );

      if (
        password !==
        confirmPassword
      ) {
        return alert(
          "Password tidak cocok!"
        );
      }

      if (
        password.length < 6
      ) {
        return alert(
          "Password minimal 6 karakter"
        );
      }

      try {

        registerBtn.innerText =
          "Loading...";
        registerBtn.disabled =
          true;

        const userCredential =
          await createUserWithEmailAndPassword(
            auth,
            email,
            password
          );

        const user =
          userCredential.user;

        const referralCode =
          "MCM" +
          Math.floor(
            100000 +
            Math.random() *
            900000
          );

        await setDoc(
          doc(
            db,
            "users",
            user.uid
          ),
          {
            uid:
              user.uid,
            username,
            email,
            balance: 0,
            miningRate:
              0.0005,
            miningStatus:
              false,
            vipLevel:
              "Basic",
            totalWithdraw:
              0,
            totalEarning:
              0,
            referralCode,
            referredBy:
              referralCodeInput ||
              null,
            createdAt:
              serverTimestamp()
          }
        );

        alert(
          "Registrasi berhasil!"
        );

        window.location.replace(
  "/login.html"
);

      } catch (error) {

        console.error(error);

        let message =
          "Registrasi gagal";

        switch (
          error.code
        ) {

          case "auth/email-already-in-use":
            message =
              "Email sudah digunakan";
            break;

          case "auth/weak-password":
            message =
              "Password terlalu lemah";
            break;

          case "auth/invalid-email":
            message =
              "Email tidak valid";
            break;

          default:
            message =
              error.message;
        }

        alert(message);

      } finally {

        registerBtn.innerText =
          "Daftar Sekarang";

        registerBtn.disabled =
          false;

      }

    }
  );
}

// ==============================
// CHECK LOGIN
// ==============================

onAuthStateChanged(
  auth,
  (user) => {

    const path =
      window.location.pathname;

    const isAuthPage =
      path.includes(
        "login.html"
      ) ||
      path.includes(
        "register.html"
      );

    const isDashboardPage =
      path.includes(
        "dashboard.html"
      );

    // kalau sudah login
    if (
      user &&
      isAuthPage
    ) {

      window.location.replace(
        "/pages/dashboard.html"
      );

    }

    // kalau belum login
    if (
      !user &&
      isDashboardPage
    ) {

      window.location.replace(
        "/login.html"
      );

    }

  }
);

// ==============================
// LOGOUT
// ==============================

window.logout =
  async function () {

    try {

      await signOut(
        auth
      );

      localStorage.removeItem(
        "miningUser"
      );

      window.location.replace(
        "/login.html"
      );

    } catch (
      error
    ) {

      console.error(
        error
      );

      alert(
        "Logout gagal"
      );

    }

  };
