import {
  auth,
  db,
  signInWithEmailAndPassword,
  createUserWithEmailAndPassword,
  signOut,
  onAuthStateChanged,
  collection,
  addDoc,
  query,
  where,
  orderBy,
  getDocs,
  setDoc,
  doc
} from './firebase-config.js';

const emailInput = document.getElementById("email");
const passwordInput = document.getElementById("password");
const usernameInput = document.getElementById("username");
const authSection = document.getElementById("auth-section");
const userInfo = document.getElementById("user-info");
const logoutBtn = document.getElementById("logout-btn");
const cbtSection = document.getElementById("cbt-section");
const userEmailSpan = document.getElementById("user-email");

window.login = async function () {
  const email = emailInput.value.trim();
  const password = passwordInput.value.trim();
  if (!email || !password) return alert("Enter both email and password.");

  try {
    await signInWithEmailAndPassword(auth, email, password);
  } catch (err) {
    alert("Login failed: " + err.message);
  }
};

window.register = async function () {
  const email = emailInput.value.trim();
  const password = passwordInput.value.trim();
  const username = usernameInput.value.trim();
  const humanCheck = document.getElementById("human-check").checked;

  if (!email || !password || !username || password.length < 6 || !humanCheck) {
    return alert("Fill all fields and check robot box. Password 6+ chars.");
  }

  try {
    const userCred = await createUserWithEmailAndPassword(auth, email, password);
    await setDoc(doc(db, "users", userCred.user.uid), {
      username: username,
      email: email
    });
    alert("Registration successful!");
  } catch (err) {
    alert("Register failed: " + err.message);
  }
};

window.logout = async function () {
  try {
    await signOut(auth);
  } catch (err) {
    alert("Logout failed: " + err.message);
  }
};

onAuthStateChanged(auth, (user) => {
  if (user) {
    authSection.style.display = "none";
    userInfo.style.display = "block";
    logoutBtn.style.display = "inline";
    userEmailSpan.textContent = user.email;
    cbtSection.style.display = "block";
    loadCBTEntries();
  } else {
    authSection.style.display = "block";
    userInfo.style.display = "none";
    logoutBtn.style.display = "none";
    cbtSection.style.display = "none";
    document.getElementById("cbt-entries").innerHTML = "";
  }
});

const cbtForm = document.getElementById("cbt-form");
cbtForm.addEventListener("submit", async (e) => {
  e.preventDefault();
  if (!auth.currentUser) return;

  const data = {
    userId: auth.currentUser.uid,
    automaticThought: document.getElementById("automatic-thought").value,
    emotion: document.getElementById("emotion").value,
    evidenceFor: document.getElementById("evidence-for").value,
    evidenceAgainst: document.getElementById("evidence-against").value,
    balancedThought: document.getElementById("balanced-thought").value,
    timestamp: new Date()
  };

  try {
    await addDoc(collection(db, "cbt"), data);
    alert("CBT thought saved!");
    cbtForm.reset();
    loadCBTEntries();
  } catch (err) {
    alert("Error saving CBT entry: " + err.message);
  }
});

async function loadCBTEntries() {
  const entriesList = document.getElementById("cbt-entries");
  entriesList.innerHTML = "Loading...";
  try {
    const q = query(
      collection(db, "cbt"),
      where("userId", "==", auth.currentUser.uid),
      orderBy("timestamp", "desc")
    );
    const snapshot = await getDocs(q);
    entriesList.innerHTML = "";
    snapshot.forEach(doc => {
      const data = doc.data();
      const li = document.createElement("li");
      li.innerHTML = `
        <div><strong>Thought:</strong> ${data.automaticThought}</div>
        <div><strong>Emotion:</strong> ${data.emotion}</div>
        <div><strong>Evidence For:</strong> ${data.evidenceFor}</div>
        <div><strong>Evidence Against:</strong> ${data.evidenceAgainst}</div>
        <div><strong>Balanced Thought:</strong> ${data.balancedThought}</div>
        <div><em>${new Date(data.timestamp.toDate?.() || data.timestamp).toLocaleString()}</em></div>
      `;
      entriesList.appendChild(li);
    });
  } catch (err) {
    entriesList.innerHTML = "Failed to load entries.";
  }
}
