import { defineComponent, h, Teleport } from "vue";
import { iconNode } from "../utils.js";

let modalId = 0;

export default defineComponent({
	name: "GnModal",
	props: {
		open: { type: Boolean, default: false },
		title: { type: String, default: "" },
		closeOnBackdrop: { type: Boolean, default: true }
	},
	emits: ["update:open", "close"],
	setup(props, { emit, slots }) {
		const titleId = `gn-modal-title-${++modalId}`;
		const close = () => {
			emit("update:open", false);
			emit("close");
		};

		return () => props.open ? h(Teleport, { to: "body" }, [
			h("div", { class: "modal a-show", "aria-hidden": "false" }, [
				h("div", {
					class: "modal-backdrop",
					onClick: () => props.closeOnBackdrop && close()
				}),
				h("div", {
					class: "modal-dialog",
					role: "dialog",
					"aria-modal": "true",
					"aria-labelledby": titleId
				}, [
					h("header", { class: "modal-header" }, [
						h("h4", { class: "modal-title", id: titleId }, slots.title?.() || props.title),
						h("button", {
							class: "btn-icon modal-close",
							type: "button",
							"aria-label": "Close",
							onClick: close
						}, [iconNode("ph-x")])
					]),
					h("div", { class: "modal-panel" }, [
						h("div", { class: "modal-body" }, slots.default?.()),
						(slots.footer || slots.actions) && h("footer", { class: "modal-footer" }, [
							slots.footer?.(),
							slots.actions && h("div", { class: "actions" }, slots.actions({ close }))
						])
					])
				])
			])
		]) : null;
	}
});
