import { initializeApp } from "https://www.gstatic.com/firebasejs/10.12.5/firebase-app.js";
import {
  getAuth,
  setPersistence,
  browserLocalPersistence,
  signInWithEmailAndPassword,
  createUserWithEmailAndPassword,
  onAuthStateChanged
} from "https://www.gstatic.com/firebasejs/10.12.5/firebase-auth.js";

const messageEl = document.getElementById("loginMessage");
const loginButton = document.getElementById("loginButton");
const createAccountButton = document.getElementById("createAccountButton");

let auth = null;

function showLoginMessage(message, type = "") {
  if (!messageEl) return;
  messageEl.textContent = message;
  messageEl.className = type ? `status ${type}` : "status";
  messageEl.style.display = message ? "block" : "none";
}

function setLoginButtonsEnabled(enabled) {
  if (loginButton) loginButton.disabled = !enabled;
  if (createAccountButton) createAccountButton.disabled = !enabled;
}

async function loadFirebaseConfig() {
  const response = await fetch("/api/public/firebase-web-config");
  const config = await response.json().catch(() => ({}));

  if (!response.ok) {
    throw new Error(config.error || "Could not load Firebase web config.");
  }

  if (!config.apiKey || !config.projectId) {
    throw new Error("Firebase web config is missing apiKey or projectId.");
  }

  return {
    apiKey: config.apiKey,
    authDomain: config.authDomain,
    projectId: config.projectId,
    appId: config.appId
  };
}

function readLoginFields() {
  return {
    email: document.getElementById("loginEmail")?.value.trim() || "",
    password: document.getElementById("loginPassword")?.value || ""
  };
}

async function initializeLogin() {
  setLoginButtonsEnabled(false);

  try {
    const firebaseConfig = await loadFirebaseConfig();
    const app = initializeApp(firebaseConfig);
    auth = getAuth(app);

    await setPersistence(auth, browserLocalPersistence);

    onAuthStateChanged(auth, user => {
      if (user) {
        window.location.href = "/admin";
      }
    });

    setLoginButtonsEnabled(true);
    showLoginMessage("", "");
  } catch (error) {
    console.error(error);
    showLoginMessage(
      `${error.message} The host server cannot log in until its public Firebase bootstrap config is present. Check data/server-config.bootstrap.json or data/server-config.json.`,
      "error");
  }
}

loginButton?.addEventListener("click", async () => {
  if (!auth) {
    showLoginMessage("Firebase login is not initialized yet.", "error");
    return;
  }

  try {
    const { email, password } = readLoginFields();
    showLoginMessage("Logging in...", "");
    await signInWithEmailAndPassword(auth, email, password);
  } catch (error) {
    showLoginMessage(error.message, "error");
  }
});

createAccountButton?.addEventListener("click", async () => {
  if (!auth) {
    showLoginMessage("Firebase login is not initialized yet.", "error");
    return;
  }

  try {
    const { email, password } = readLoginFields();
    showLoginMessage("Creating account...", "");
    await createUserWithEmailAndPassword(auth, email, password);
  } catch (error) {
    showLoginMessage(error.message, "error");
  }
});

initializeLogin();
