function template(id, title, footer) {
	return `
		<div class="modal" aria-hidden="true" id="${id}">
      <div class="modal-backdrop"></div>

      <div class="modal-panel" role="dialog" aria-modal="true" aria-labelledby="modal-title-basic">
        <header class="modal-header">
          <h4 class="modal-title" id="modal-title-basic">${title}</h4>
          <button class="btn-icon modal-close" type="button" aria-label="Close">✕</button>
        </header>

        <div class="modal-body"></div>
        <footer class="modal-footer">${footer}</footer>
      </div>
    </div>
	`;
}

function init(modal, onready) {
	modal.show = function() {
		document.querySelector("body").append(modal);

		setTimeout(() => {
			modal.classList.add("a-show");
		}, 10);
	}

	modal.close = function() {
		modal.classList.add("a-hide");
		setTimeout(() => {
			modal.remove();
		}, 300);
	}

	modal.querySelector(".modal-close").addEventListener("click", e => {
		modal.close();
	});

	if(typeof onready == "function") {
		onready(modal);
	}

	return modal;
}

	/**
	 * Create new modal window;
	 * @param  {string} id    Uniq id (selector)
	 * @param  {string} title Display title
	 * @param  {object} props { body: modal => {}, actions => modal => {} }
	 * @return {object}       DOM object
	 */
function create(id, props) {
	const title = props.title || "";
	const footer = props.footer || "";

	const div = document.createElement("div");
	div.innerHTML = template(id, title, footer);
	const modal = div.childNodes[1];

	const modalBody = modal.querySelector(".modal-body");
	const modalFooter = modal.querySelector(".modal-footer");

	if(typeof props.actions == "function") {
		const actionsResult = props.actions(modal);

		if(typeof actionsResult[0] == "object") {
			const actions = document.createElement("div");
			actions.classList.add("actions");
			for(let actionElement of actionsResult) {
				actions.append(actionElement);
			}

			modalFooter.append(actions);
		}
	}

	if(typeof props.body == "function") {
		const bodyResult = props.body(modal);

		if(typeof bodyResult == "object") {
			modalBody.append(bodyResult);
		} else if(typeof bodyResult == "string") {
			modalBody.innerHTML = bodyResult;
		}
	}

	return init(modal, props?.onready);
}

export default {
	create
}