// --- 3. auth.js ---
function getDeviceId() {
let did = localStorage.getItem('xv_device_id');
if (!did) {
did = 'dev_' + Math.random().toString(36).substring(2, 15) + Date.now().toString(36);
localStorage.setItem('xv_device_id', did);
}
return did;
}
async function checkSession() {
const { data: { session } } = await supabaseClient.auth.getSession();
if (session) {
currentUser = session.user;
document.getElementById('form-login').classList.add('hidden');
document.getElementById('form-vip').classList.remove('hidden');
const { data } = await supabaseClient.from('profiles').select('*').eq('id', currentUser.id).single();
const now = new Date();
const expiryDate = data?.expiry_date ? new Date(data.expiry_date) : null;
isVipActive = data?.is_vip && (!expiryDate || expiryDate > now);
const userInfo = document.getElementById('user-info');
if (isVipActive) {
const expiryText = expiryDate ? `Hết hạn: ${expiryDate.toLocaleDateString('vi-VN')}` : "Vĩnh viễn";
userInfo.innerHTML = `Tài khoản: ${currentUser.email}
✓ VIP ACTIVE
${expiryText}`;
document.getElementById('vip-floating-btn').style.background = "linear-gradient(135deg, #22ff99, #00cc77)";
} else {
userInfo.innerHTML = `Tài khoản: ${currentUser.email}
Tài khoản thường`;
document.getElementById('vip-floating-btn').style.background = "linear-gradient(135deg, #6c757d, #495057)";
}
} else {
document.getElementById('form-login').classList.remove('hidden');
document.getElementById('form-vip').classList.add('hidden');
currentUser = null; isVipActive = false;
}
}
async function handleLogin() {
const email = document.getElementById('u_email').value.trim();
const password = document.getElementById('u_password').value.trim();
const btn = document.getElementById('btn-login');
btn.innerText = "Đang xử lý...";
let { error } = await supabaseClient.auth.signInWithPassword({ email, password });
if (error) {
const { error: signUpErr } = await supabaseClient.auth.signUp({ email, password });
if (!signUpErr) saveCredentials(email, password);
} else {
saveCredentials(email, password);
}
btn.innerText = "ĐĂNG NHẬP / ĐĂNG KÝ";
checkSession();
}
function saveCredentials(email, pass) {
localStorage.setItem('xv_vip_email', email);
localStorage.setItem('xv_vip_pass', pass);
}