import signService from '../../apis/sign-api.js';

document.addEventListener('DOMContentLoaded', () => {
    initializeElements();
    setupEventListeners();
});

const initializeElements = () => {
    window.signupModal = new bootstrap.Modal(document.getElementById('signupModal'));
    window.changePasswordModal = new bootstrap.Modal(document.getElementById('changePasswordModal'));
};

const setupEventListeners = () => {
    const eventMap = {
        'signIn': { event: 'click', handler: handleSignIn },
        'signUp': { event: 'click', handler: () => signupModal.show() },
        'signupForm': { event: 'submit', handler: handleSignUp },
        'signupModal': { event: 'hidden.bs.modal', handler: resetForm },
        'changePassword': { event: 'click', handler: () => changePasswordModal.show() },
        'changePasswordForm': { event: 'submit', handler: handleChangePassword },
        'changePasswordModal': { event: 'hidden.bs.modal', handler: resetForm }
    };

    Object.entries(eventMap).forEach(([id, { event, handler }]) => {
        document.getElementById(id)?.addEventListener(event, handler);
    });
};

const handleSignIn = async () => {
    const username = document.getElementById('username').value;
    const password = document.getElementById('password').value;
    const { status, redirectUrl } = await signService.signIn(username, password);
    if (status) window.location.href = redirectUrl;
};

const handleSignUp = async (e) => {
    e.preventDefault();
    const userId = document.getElementById('userId').value;
    const isConflict = await signService.isConflictUserId(userId);
    if (!isConflict) {
        const params = Object.fromEntries(new FormData(e.target));
        await signService.signUp(params);
        alert('회원가입이 완료되었습니다.');
        signupModal.hide();
    }
};

const handleChangePassword = async (e) => {
    e.preventDefault();
    const [userId, newPassword] = ['changePasswordUserId', 'newPassword'].map(id => document.getElementById(id).value);
    await signService.changePassword(userId, newPassword);
    alert('비밀번호가 변경되었습니다.');
    changePasswordModal.hide();
};

const resetForm = ({ target }) => target.querySelector('form').reset();