<script lang="ts" setup>
import type { BtnOptions } from '@bagelink/vue'
import type { SetupContext } from 'vue'
import {
	Btn,
	Card,
	Title
} from '@bagelink/vue'
import {
	computed,
	ref,
	useSlots,
	watch
} from 'vue'
import '../styles/modal.css'

interface ModalProps {
	thin?: boolean
	side?: boolean
	title?: string
	width?: string
	dismissable?: boolean
	actions?: BtnOptions[]
	visible?: boolean
	zIndex?: number
	closePlacement?: 'header' | 'header-end' | 'overlay' | 'overlay-end' | 'none' | 'footer'
}
const props = withDefaults(defineProps<ModalProps>(), {
	thin: false,
	side: false,
	dismissable: true,
	visible: false,
	zIndex: 100,
	closePlacement: 'header'
})

const emit = defineEmits(['update:visible'])

const slots: SetupContext['slots'] = useSlots()

const isVisible = ref<boolean>(false)

watch(
	() => props.visible,
	(val) => {
		if (val === isVisible.value || val === undefined) { return }
		if (val) { openModal() }
		else { closeModal() }
	},
	{ immediate: true },
)

const maxWidth = computed(() => {
	const { width } = props
	if (width?.match(/px|em|rem|vw|vh|%/)) { return { 'max-width': width } }
	if (width?.match(/\d+/)) { return { 'max-width': `${width}px` } }
	return { 'max-width': '720px' }
})

// Computed properties for close button placement
const isOverlay = computed(() => props.closePlacement === 'overlay' || props.closePlacement === 'overlay-end')
const isHeader = computed(() => props.closePlacement === 'header' || props.closePlacement === 'header-end')
const isFooter = computed(() => props.closePlacement === 'footer')

const overlayCloseClass = computed(() => {
	if (props.closePlacement === 'overlay-end') { return 'top-1 end-1' }
	return 'top-1 start-1'
})

function closeModal() {
	isVisible.value = false
	setTimeout(() => { emit('update:visible', false) }, 200)
}

defineExpose({ closeModal })

function openModal() {
	setTimeout(() => (isVisible.value = true), 1)
}

// Note: ESC key handling is now done centrally in ModalPlugin for proper stacking behavior
</script>

<template>
	<div
		class="bg-dark" :style="{ zIndex }" :class="{ 'is-side': side, 'is-active': isVisible, 'bg-lignt': false }"
		@click="() => (dismissable ? closeModal() : '')" @keydown.esc="closeModal"
	>
		<!-- Overlay close button -->
		<Btn
			v-if="dismissable && isOverlay" icon="close" icon-mobile-size="1.4" class="fixed"
			:class="overlayCloseClass" @click="closeModal"
		/>

		<Card
			class="modal m_pt-0" :style="{ ...maxWidth, '--bgl-box-bg': 'var(--bgl-popup-bg)' }" :thin="thin"
			:class="{ 'pt-0': thin, 'pt-1': !thin, 'm_mt-5': isOverlay, 'display-flex column': side }" @click.stop
		>
			<header v-if="slots.toolbar || title" class="tool-bar w-100p flex space-between sticky z-3 py-1">
				<!-- Header close button -->
				<Btn
					v-if="dismissable && isHeader && closePlacement === 'header'" :style="{ float: side ? '' : '' }"
					flat icon="close" thin icon-mobile-size="1.4" @click="closeModal"
				/>
				<slot name="toolbar" />
				<Title
					v-if="title" class="modal-title txt-center txt20 medium my-0 w-100p ellipsis-1" tag="h3"
					:label="title"
					:class="{ 'me-1-5': isHeader && dismissable && closePlacement === 'header', 'ms-1-5': isHeader && dismissable && closePlacement === 'header-end' }"
				/>
				<!-- Header-end close button -->
				<Btn
					v-if="dismissable && isHeader && closePlacement === 'header-end'"
					:style="{ float: side ? '' : '' }" flat icon="close" thin icon-mobile-size="1.4"
					@click="closeModal"
				/>
			</header>

			<header
				v-else class="tool-bar w-100p flex space-between sticky z-3"
				:class="{ 'py-1': !isOverlay, 'pt-1': isOverlay }"
			>
				<!-- Header close button (no title) -->
				<Btn
					v-if="dismissable && isHeader && closePlacement === 'header'" :style="{ float: side ? '' : '' }"
					flat icon="close" thin icon-mobile-size="1.4" @click="closeModal"
				/>
				<slot name="toolbar" />
				<!-- Header-end close button (no title) -->
				<Btn
					v-if="dismissable && isHeader && closePlacement === 'header-end'"
					:style="{ float: side ? '' : '' }" flat icon="close" thin icon-mobile-size="1.4" class="ms-auto"
					@click="closeModal"
				/>
			</header>

			<slot />
			<footer
				v-if="slots.footer || actions?.length" class="modal-footer gap-1 flex space-between"
				:class="{ 'mt-1': !side, 'mt-auto': side }"
			>
				<Btn v-for="(action, i) in actions" :key="i" color="gray" v-bind="action" @click="closeModal" />
				<slot name="footer" />
				<!-- Footer close button -->
			</footer>
			<Btn
				v-if="dismissable && isFooter" icon="close" label="Close"
				class="mx-auto absolute start-0 end-0 modalFooterBtn" @click="closeModal"
			/>
		</Card>
	</div>
</template>

<style>
.modal {
	color: var(--bgl-popup-text);
}

.modal .bgl_btn.bgl_btn_flat {
	color: var(--bgl-popup-text) !important;
}

.modal .rich-text-editor .bgl_btn.bgl_btn_flat.active {
	color: var(--bgl-white) !important;
}
.modal-footer>div {
	gap: 1rem;
	display: flex;
	justify-content: space-between;
	align-items: center;
}

.modal-no-title {
	width: calc(100% + 2rem);
	border-radius: var(--card-border-radius);
}

.modalFooterBtn {
	bottom: calc(var(--btn-height) / 2 * -1);

}
</style>
