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

// ✅ 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 Failed', 'Username and password cannot be empty');
        return;
    }

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

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

        if (data.success) {
            // ✅ PERBAIKAN: Gunakan sessionStorage (sama dengan logout.js)
            sessionStorage.setItem('authToken', data.token);
            sessionStorage.setItem('loggedInUser', data.username);
            
            showModal('success', 'Login Successful', `Welcome, ${data.username}!`);
            
        } else {
            showModal('error', 'Login Failed', data.message || 'Incorrect username or password');
        }
    } catch (error) {
        console.error('Login Error:', error);
        
        let errorMessage = 'A server connection error occurred';
        
        if (error.message === 'Failed to fetch') {
            errorMessage = 'Unable to connect to the server. Please check your internet connection';
        }
        
        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 = '';
});