/*!
 * Custom elements for Nanopore-Digital Web applications
 */
import { transformTag } from "../../utils/renderer";
/**
 * `nano-dialog` helper to create dialog modals imperatively.
 * @param body - a JS template string e.g. `<h4>Hello</h4> ${aVariable}`
 * @param buttons - { classes: string; content: string; handler: () => {} }[]
 * @param dialogOptions - { noUserDismiss: boolean, noHeader?: boolean, noFooter?: boolean, label: string }
 * @returns `Promise<void>`
 */
export function nanoCreateDialog(body, buttons = [], dialogOptions) {
    const opts = {
        noUserDismiss: false,
        label: 'Dialog',
        ...dialogOptions,
    };
    const dialog = Object.assign(document.createElement(transformTag('nano-dialog')), {
        ...opts,
        open: false,
        innerHTML: `
      ${body}
      ${buttons.length
            ? `<nano-cta group="balanced" slot="footer">` +
                buttons
                    .map((btn, i) => `<button 
                  data-btn="${i}" 
                  class="${btn.classes}"
                  theme="${btn.theme}"
                  secondary="${btn.secondary ? 'true' : 'false'}"
                >${btn.content}</button>`)
                    .join('') +
                `</nano-cta>`
            : ''}`,
    });
    if (buttons.length) {
        Array.from(dialog.querySelectorAll('nano-cta[slot="footer"] button')).map((btn) => {
            const foundBtn = buttons.find((_fb, i) => btn.dataset.btn === i.toString());
            if (foundBtn && foundBtn.handler) {
                btn.addEventListener('click', foundBtn.handler);
            }
        });
    }
    document.body.appendChild(dialog);
    return new Promise((resolve) => {
        requestAnimationFrame(async (_) => {
            await dialog.show();
            resolve(dialog);
        });
    });
}
