// 🔥 IMPORT
import { initializeApp } from "https://www.gstatic.com/firebasejs/10.12.2/firebase-app.js";

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

import {
  getDatabase,
  ref,
  set
} from "https://www.gstatic.com/firebasejs/10.12.2/firebase-database.js";


// 🔥 CONFIG (FIX SEMUA)
const firebaseConfig = {
  apiKey: "AIzaSyC-Wdu6vNC0dRyF33S3_C2wpVt9I6wnp0w",
  authDomain: "smartoven-f9fdd.firebaseapp.com",
  databaseURL: "https://smartoven-f9fdd-default-rtdb.firebaseio.com/",
  projectId: "smartoven-f9fdd",
  appId: "1:1005261996032:web:1bcb483b922275f08f98e5"
};


// 🔥 INIT
const app = initializeApp(firebaseConfig);
const auth = getAuth(app);
const db = getDatabase(app);


// =====================
// 🔥 REGISTER
// =====================
const registerForm = document.getElementById("registerForm");

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

    const username = document.querySelector('[name="reg_username"]').value;
    const email = document.querySelector('[name="reg_email"]').value;
    const password = document.querySelector('[name="reg_password"]').value;
    const confirm = document.querySelector('[name="reg_confirm"]').value;

    if (password !== confirm) {
      alert("Password tidak sama!");
      return;
    }

    try {
      const userCred = await createUserWithEmailAndPassword(auth, email, password);
      const user = userCred.user;

      // 🔥 SIMPAN USER KE DATABASE
      await set(ref(db, "users/" + user.uid), {
        username: username,
        email: email
      });

      alert("Registrasi berhasil!");
      window.location.href = "index.php";

    } catch (err) {
      alert("Error: " + err.message);
    }
  });
}


// =====================
// 🔥 LOGIN
// =====================
const loginForm = document.getElementById("loginForm");

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

    const email = document.querySelector('[name="username"]').value;
    const password = document.querySelector('[name="password"]').value;

    try {
      await signInWithEmailAndPassword(auth, email, password);

      // 🔥 KIRIM SESSION KE PHP
      await fetch("login_process.php", {
        method: "POST",
        headers: {
          "Content-Type": "application/x-www-form-urlencoded"
        },
        body: `email=${email}`
      });

      window.location.href = "dashboard.php";

    } catch (err) {
      alert("Login gagal: " + err.message);
    }
  });
}
