// ig-datapool.js

class Datapool {
    constructor() {
	this.forms = new Map();
	this.plugins = new Map();
	this.ckeditors = {}; // Storage for CKEditor instances
	
        const elements = document.querySelectorAll('.dp-form, .dp-form-search');
        elements.forEach((form, index) => {
            this.addForm(form, index);
        });
    }
    addForm(form, name) {
        this.forms.set(name, form);
        this.formPreventSubmitOnEnter(form);

        // Attach helper methods to the form instance
        form.initDPForm = () => {
            this.plugins.forEach(plugin => plugin.init?.(form));
        };

        form.initFields = () => {
            this.plugins.forEach(plugin => plugin.initFields?.(form));
        };
    }
    addPlugin(name, plugin) {
	//console.log('add plugin: ' + name);
        this.plugins.set(name, plugin);
        // Map.forEach passes (value, key)
        this.forms.forEach((form) => {
            plugin.init?.(form);
        });
    }
/**
 * Prevents Enter key from submitting the form (excluding search forms and textareas)
 */
    formPreventSubmitOnEnter = (form) => {
	if (form.classList.contains('dp-searchform')) return;

	['keypress', 'keyup'].forEach(eventType => {
            form.addEventListener(eventType, (e) => {
		const tagName = e.target.tagName;
		if (tagName === 'TEXTAREA' || (tagName === 'DIV' && e.target.isContentEditable)) return;

		if (e.key === 'Enter' || e.keyCode === 13) {
                    e.preventDefault();
		}
            });
	});
    }    
}

const IGDATAPOOLFE = new Datapool();

export default IGDATAPOOLFE;