import { showModal, setupModalOk, setupOutsideClose } from "./Modal_Login.js";
import { loginRequest } from "./Login_Request.js";

// ✅ PENTING: Setup modal saat halaman load
document.addEventListener('DOMContentLoaded', function() {
    setupModalOk();
    setupOutsideClose();
});

document.getElementById('loginForm').addEventListener('submit', async function(e) {
    e.preventDefault();

    const username = document.getElementById('username').value.trim();
    const password = document.getElementById('password').value.trim();

    if (!username || !password) {
        showModal('error', 'Login Gagal!', 'Username dan password tidak boleh kosong.');
        return;
    }

    const submitBtn = this.querySelector('button[type="submit"]');
    submitBtn.disabled = true;

    try {
        const data = await loginRequest(username, password);
        
        console.log('Response dari server:', data); // Debug

        if (data.success) {
            localStorage.setItem('authToken', data.token);
            localStorage.setItem('username', data.username);
            
            showModal('success', 'Login Berhasil!', `Selamat datang, ${data.username}!`);
        } else {
            showModal('error', 'Login Gagal!', data.message || 'Username atau password salah.');
        }
    } catch (error) {
        console.error('Login Error:', error);
        
        let errorMessage = 'Terjadi kesalahan koneksi ke server.';
        
        if (error.message === 'Failed to fetch') {
            errorMessage = 'Tidak dapat terhubung ke server. Periksa koneksi internet Anda.';
        }
        
        showModal('error', 'Error!', errorMessage);
    } finally {
        submitBtn.disabled = false;
    }
});

document.getElementById('username').addEventListener('input', function() {
    this.style.borderColor = '';
});

document.getElementById('password').addEventListener('input', function() {
    this.style.borderColor = '';
});