import { addEvents } from '../../common/common.js';
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 = {
        'signinForm': { event: 'submit', 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 }
    };
    addEvents(eventMap);
};

const handleSignIn = async (e) => {
    const params = Object.fromEntries(new FormData(e.target));
    const { status, redirectUrl } = await signService.signIn(params);
    if (status) window.location.href = redirectUrl;
};

const handleSignUp = async (e) => {
    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) => {
    const params = Object.fromEntries(new FormData(e.target));
    await signService.changePassword(params);
    alert('비밀번호가 변경되었습니다.');
    changePasswordModal.hide();
};

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