import {useEvent} from "../../../core/useEvent";

export class Dialog {
    constructor({content = '', className = '', onClose = null} = {}) {
        this.onClose = onClose;
        this.dialog = document.createElement('dialog');
        this.dialog.className = className;
        this.dialog.innerHTML = `
      <form method="dialog" class="${className}-content">
        ${content}
        <button class="${className}-close" value="close">×</button>
      </form>
    `;

        useEvent(this.dialog, 'click', (e) => {
            const isOutside = !e.target.closest(className+'-content');
            if (isOutside) this.close();
        })

        useEvent(this.dialog, 'cancel', (e) => {
            e.preventDefault();
            this.close();
        })

    }

    open()
    {
        document.body.appendChild(this.dialog);
        this.dialog.showModal?.() || this.dialog.setAttribute('open', '');
        document.documentElement.dataset[`${this.dialog.className}Open`] = 'true';
    }

    close()
    {
        this.dialog.close?.() || this.dialog.removeAttribute('open');
        this.dialog.remove();
        delete document.documentElement.dataset[`${this.dialog.className}Open`];
        this.onClose?.();
    }
}
