<script setup lang="ts">
import { useToastStore } from '@/stores/toast'

function onBeforeLeave(el: Element) {
	const htmlEl = el as HTMLElement
	const { offsetTop, offsetLeft, offsetWidth } = htmlEl
	htmlEl.style.top = `${offsetTop}px`
	htmlEl.style.left = `${offsetLeft}px`
	htmlEl.style.width = `${offsetWidth}px`
}
const toast = useToastStore()
</script>

<template>
	<Transition tag="div" name="stack">
		<div v-if="toast.toasts.length" class="toast-stack">
			<TransitionGroup name="toast" @before-leave="onBeforeLeave">
				<div
					v-for="t in toast.toasts"
					:key="t.id"
					:class="['toast', t.type]"
					@click="toast.handleClick(t.id)"
				>
					<div class="icon">
						<component :is="t.icon" />
					</div>
					<span class="message">{{ t.message }}</span>
				</div>
			</TransitionGroup>
		</div>
	</Transition>
</template>

<style scoped lang="scss">
.toast-stack {
	position: absolute;
	bottom: calc(5rem + env(safe-area-inset-bottom));
	left: 0.5rem;
	z-index: 1000;

	display: flex;
	flex-direction: column;
	align-items: flex-start;
	gap: 0.75rem;

	width: 100%;
	pointer-events: none;
}
@media (min-width: 800px) {
	.toast-stack {
		position: fixed;
		bottom: 1.5rem;
	}
}

.toast {
	--accent-colour: var(--accent);
	max-width: var(--content-width);
	background-color: hsla(var(--surface0) / 1);

	display: inline-flex;
	align-items: center;
	justify-content: center;

	padding: 0.25rem 0.5rem;
	padding-right: 1rem;
	gap: 0.5rem;
	border-radius: 2rem;

	cursor: pointer;
	pointer-events: all;
	user-select: none;

	max-height: 5rem;
	overflow: hidden;

	border: 1px solid hsla(var(--accent-colour) / 0.25);

	.icon {
		font-size: 1.5rem;
		display: flex;
		align-items: center;
		justify-content: center;
		color: hsl(var(--accent-colour));
	}

	&.success {
		--accent-colour: var(--green);
	}
	&.error {
		--accent-colour: var(--red);
	}
	&.info {
		--accent-colour: var(--blue);
	}
}

.stack-enter-active,
.stack-leave-active {
	transition: opacity 0.2s ease;
}
.stack-enter-from,
.stack-leave-to {
	opacity: 0;
}

.toast-move,
.toast-enter-active,
.toast-leave-active {
	transition: all 0.25s ease;
}

.toast-enter-from {
	opacity: 0;
	transform: translateY(1rem) scale(0.95);
}

.toast-leave-to {
	opacity: 0;
	transform: translateX(-2rem) scale(0.95);
	filter: blur(2px);
	max-height: 0;
	padding-top: 0;
	padding-bottom: 0;
	margin-top: -0.75rem;
	border-width: 0;
}
</style>
