class Import extends Master {
    constructor() {
        super();
        this.importWordBtns = document.querySelectorAll('.import-file-submit-btn'); 
    }

    initializeImport() {
        this.importWordsUtil(); 
    }

    importWordsUtil() {
        const btns = this.importWordBtns;
        if (!btns?.length) return;
    
        btns.forEach((btn) => {
            btn.addEventListener('click', async (event) => {
                event.preventDefault();
    
                disableElement(btn);
                toggleButtonContent(btn);
    
                const form = resolveClosestForm(btn);
                if (!form) {
                    toast('error', 3000, 'An error occurred. Please try again.');
                    enableElement(btn);
                    toggleButtonContent(btn, '', true);
                    return;
                }
    
                const data = new FormData(form);
                const action = formRouteParser(form);
    
                try {
                    const response = await fetch(action, {
                        method: "POST",
                        headers: {
                            'X-Requested-With': 'XMLHttpRequest'
                        },
                        body: data
                    });
    
                    const result = await response.json();
    
                    if (result.status === 'success') {
                        resetFormAndCloseModal(form);
                        toast('success', 5000, result.message || 'Words imported successfully.');
    
                        setTimeout(() => {
                            if (result.route) route(result.route);
                        }, 2000);
    
                        (new Import()).getWordResource?.();
                    } else {
                        toast('error', 5000, result.message || 'An error occurred. Please try again.');
                    }
    
                } catch (error) {
                    console.error(error.message || error);
                    toast('error', 5000, error.message || 'Server error. Please contact the administrator.');
                } finally { 
                    enableElement(btn);
                    toggleButtonContent(btn, '', true);
                }
            });
        });
    }
}

// Initialize when DOM is loaded
document.addEventListener('DOMContentLoaded', () => {
    const importInst = new Import();
    importInst.initializeImport();
});
