/* =========================================================
   ZA-FARM-KH — Auth System
   Features: Login, Register, Forgot Password, Google Sign-In
   Notifications: Telegram on register
   ========================================================= */

const API_BASE = window.location.hostname === "localhost"
  ? "http://localhost:3000/zapi"
  : "/zapi";

/* ---------- Toast ---------- */
function showToast(msg, isError = false) {
  const t = document.getElementById("toast");
  if (!t) return alert(msg);
  t.textContent = msg;
  t.className = "toast-msg show" + (isError ? " error" : "");
  setTimeout(() => t.classList.remove("show"), 3000);
}

/* ---------- Password Toggle ---------- */
const togglePass = document.getElementById("togglePass");
if (togglePass) {
  togglePass.addEventListener("click", () => {
    const input = document.getElementById("password");
    input.type = input.type === "password" ? "text" : "password";
  });
}

/* ---------- Password Strength ---------- */
const passInput = document.getElementById("password");
const strengthFill = document.getElementById("strengthFill");
const strengthText = document.getElementById("strengthText");

if (passInput && strengthFill) {
  passInput.addEventListener("input", () => {
    const val = passInput.value;
    let score = 0;
    if (val.length >= 6) score++;
    if (val.length >= 10) score++;
    if (/[A-Z]/.test(val) && /[0-9]/.test(val)) score++;

    strengthFill.className = "strength-fill";
    if (score === 0) {
      strengthFill.className = "strength-fill";
      strengthText.textContent = "";
    } else if (score === 1) {
      strengthFill.className = "strength-fill weak";
      strengthText.textContent = "ខ្សោយ";
    } else if (score === 2) {
      strengthFill.className = "strength-fill medium";
      strengthText.textContent = "មធ្យម";
    } else {
      strengthFill.className = "strength-fill strong";
      strengthText.textContent = "រឹងមាំ";
    }
  });
}

/* ---------- Handle Google OAuth Callback ---------- */
(function handleGoogleCallback() {
  const params = new URLSearchParams(window.location.search);
  const token = params.get("token");
  const userStr = params.get("user");
  if (token && userStr) {
    try {
      const user = JSON.parse(decodeURIComponent(userStr));
      localStorage.setItem("zafarm_token", token);
      localStorage.setItem("zafarm_user", JSON.stringify(user));
      window.location.href = "/";
    } catch {}
  }
  const error = params.get("error");
  if (error === "google_failed") {
    setTimeout(() => showToast("Google Sign-In បរាជ័យ — សូមព្យាយាមម្តងទៀត", true), 500);
  }
})();

/* ---------- Google Sign-In ---------- */
const googleSignIn = document.getElementById("googleSignIn");
const googleSignUp = document.getElementById("googleSignUp");

if (googleSignIn) {
  googleSignIn.addEventListener("click", () => {
    // Redirect to server Google OAuth endpoint
    window.location.href = `${API_BASE}/auth/google`;
  });
}
if (googleSignUp) {
  googleSignUp.addEventListener("click", () => {
    window.location.href = `${API_BASE}/auth/google`;
  });
}

/* ---------- Login ---------- */
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;

    if (!email || !password) { showToast("សូមបំពេញគ្រប់ field", true); return; }

    const btn = loginForm.querySelector(".submit-btn");
    btn.disabled = true;
    btn.textContent = "កំពុងចូល...";

    try {
      const res = await fetch(`${API_BASE}/auth/login`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ email, password }),
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.message || "Login failed");

      localStorage.setItem("zafarm_token", data.token);
      localStorage.setItem("zafarm_user", JSON.stringify(data.user));
      showToast("ចូលបានជោគជ័យ ✅");
      setTimeout(() => window.location.href = "/", 800);
    } catch (err) {
      if (err.message.includes("fetch")) {
        demoLogin(email, password);
      } else {
        showToast(err.message, true);
      }
      btn.disabled = false;
      btn.textContent = "ចូលគណនី";
    }
  });
}

/* ---------- Register ---------- */
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 telegram = document.getElementById("telegram").value.trim();
    const password = document.getElementById("password").value;
    const confirmPassword = document.getElementById("confirmPassword").value;

    if (!username || !email || !password) {
      showToast("សូមបំពេញគ្រប់ field ទាំងអស់", true); return;
    }
    if (password !== confirmPassword) {
      showToast("ពាក្យសម្ងាត់មិនត្រូវគ្នា", true); return;
    }
    if (password.length < 6) {
      showToast("ពាក្យសម្ងាត់ត្រូវមានយ៉ាងតិច 6 តួអក្សរ", true); return;
    }

    const btn = registerForm.querySelector(".submit-btn");
    btn.disabled = true;
    btn.textContent = "កំពុងបង្កើត...";

    try {
      const res = await fetch(`${API_BASE}/auth/register`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ username, email, telegram, password }),
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.message || "Registration failed");

      showToast("គណនីបង្កើតរួច ✅ សូមចូលគណនី");
      setTimeout(() => window.location.href = "/login", 1200);
    } catch (err) {
      if (err.message.includes("fetch")) {
        demoRegister(username, email, telegram, password);
      } else {
        showToast(err.message, true);
      }
      btn.disabled = false;
      btn.textContent = "បង្កើតគណនី";
    }
  });
}

/* ---------- Forgot Password ---------- */
const forgotForm = document.getElementById("forgotForm");
if (forgotForm) {
  forgotForm.addEventListener("submit", async (e) => {
    e.preventDefault();
    const email = document.getElementById("email").value.trim();

    if (!email) { showToast("សូមបញ្ចូល email", true); return; }

    const btn = forgotForm.querySelector(".submit-btn");
    btn.disabled = true;
    btn.textContent = "កំពុងផ្ញើ...";

    try {
      const res = await fetch(`${API_BASE}/auth/forgot`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ email }),
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.message || "Failed");
      showToast("Reset link ត្រូវបានផ្ញើទៅ Telegram ✅");
    } catch (err) {
      showToast(err.message, true);
    }
    btn.disabled = false;
    btn.textContent = "ផ្ញើ Reset Link";
  });
}

/* ---------- Reset Password ---------- */
const resetForm = document.getElementById("resetForm");
if (resetForm) {
  resetForm.addEventListener("submit", async (e) => {
    e.preventDefault();
    
    // Get token from URL query params
    const params = new URLSearchParams(window.location.search);
    const token = params.get("token");
    
    if (!token) {
      showToast("Token មិនត្រឹមត្រូវ ឬបាត់!", true);
      return;
    }

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

    if (password !== confirmPassword) {
      showToast("ពាក្យសម្ងាត់មិនត្រូវគ្នាទេ", true);
      return;
    }
    if (password.length < 6) {
      showToast("ពាក្យសម្ងាត់ត្រូវមានយ៉ាងហោចណាស់ 6 តួអក្សរ", true);
      return;
    }

    const btn = resetForm.querySelector(".submit-btn");
    btn.disabled = true;
    btn.textContent = "កំពុងផ្លាស់ប្ដូរ...";

    try {
      const res = await fetch(`${API_BASE}/auth/reset`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ token, password }),
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.message || "Failed to reset password");
      
      showToast("ប្ដូរពាក្យសម្ងាត់ជោគជ័យ ✅");
      setTimeout(() => {
        window.location.href = "/login";
      }, 1500);
    } catch (err) {
      showToast(err.message, true);
      btn.disabled = false;
      btn.textContent = "ផ្លាស់ប្ដូរពាក្យសម្ងាត់";
    }
  });
}

/* ---------- Demo Fallback REMOVED for security ---------- */
/* Demo mode ត្រូវបានលុបចេញ ដើម្បីសុវត្ថិភាព — ត្រូវការ server ដើម្បីចុះឈ្មោះ/ចូល */
function demoLogin() {
  showToast("មិនអាចភ្ជាប់ server បាន — សូមពិនិត្យថា server កំពុងដំណើរការ", true);
}
function demoRegister() {
  showToast("មិនអាចភ្ជាប់ server បាន — សូមពិនិត្យថា server កំពុងដំណើរការ", true);
}
