<script lang="ts">
	import { t } from '$lib/i18n';
	import { dismissMessage, messages } from '$lib/stores/messages.store';
	import Icon from './icons/Icon.svelte';
</script>

<div class="messages-wrapper" aria-live="assertive">
	{#each $messages as msg}
		<div class="appear message message--{msg.type}" role="alertdialog">
			<div class="message-title">
				<span>{$t(`common.${msg.type}`)}!</span>
				<button onclick={() => dismissMessage(msg)} class="message-close">
					<Icon icon="Close" />
					<span class="visually-hidden">{$t('common.close')}</span>
				</button>
			</div>
			<span>{msg.text}</span>
			{#if msg.actions}
				<div class="message-actions">
					{#each msg.actions as action}
						<button onclick={action.action}>{action.label}</button>
					{/each}
				</div>
			{/if}
		</div>
	{/each}
</div>

<style>
	.messages-wrapper {
		position: fixed;
		z-index: 30;
		left: auto;
		width: 100%;
		right: auto;
		bottom: 0;
		display: flex;
		flex-direction: column;
		gap: 8px;
		padding: 16px;
		pointer-events: none;
	}

	.message {
		pointer-events: all;
		background-color: var(--in-alert-color);
		box-shadow: var(--in-alert-shadow);
		padding: 16px;
		border-radius: 8px;
		display: flex;
		flex-direction: column;
		gap: 8px;
		overflow-wrap: anywhere;
		max-width: 28rem;
		margin: auto;

		& > span {
			font-size: 1.25rem;
		}
	}

	.message-title {
		display: flex;
		justify-content: space-between;
		align-items: flex-start;
		gap: 8px;

		& > span {
			font-weight: bold;
			font-size: 1.5rem;
		}
	}

	.message-close,
	.message-actions > button {
		appearance: none;
		border: 0;
		padding: 0;
		background: transparent;
		color: var(--in-link-color);
		font-size: 1rem;
		width: 2rem;
		height: 2rem;
		margin-top: -0.5rem;
		margin-right: -0.5rem;
		cursor: pointer;

		&:focus-visible {
			outline: var(--in-focus-outline);
		}
	}

	.message-actions > button {
		text-decoration: underline;
	}

	.message-actions {
		display: flex;
		justify-content: flex-end;
		gap: 8px;
	}

	.message--error {
		background-color: var(--in-error-color);
	}

	.message--success {
		background-color: var(--in-success-color);
	}

	.appear {
		animation: popup 0.3s cubic-bezier(0.34, 1.56, 0.64, 1);
	}
	@keyframes popup {
		from {
			transform: scale(0.6);
		}
		to {
			transform: scale(1);
		}
	}
</style>
