<script lang="ts">
    import { toast } from '$lib/toast.svelte';
    import X from '@lucide/svelte/icons/x';

    // Errors get an assertive `alert` role so screen readers interrupt;
    // success/info use the polite `status` role.
    const roleFor = (kind: string) => (kind === 'error' ? 'alert' : 'status');
</script>

<div class="toaster" data-testid="toaster">
    {#each toast.toasts as t (t.id)}
        <div class="toast {t.kind}" role={roleFor(t.kind)} data-testid="toast" data-kind={t.kind}>
            <span class="message">{t.message}</span>
            <button
                type="button"
                class="dismiss"
                aria-label="Dismiss notification"
                onclick={() => toast.dismiss(t.id)}
            >
                <X size={16} aria-hidden="true" />
            </button>
        </div>
    {/each}
</div>

<style>
    .toaster {
        position: fixed;
        left: 0;
        right: 0;
        bottom: calc(var(--safe-bottom) + var(--space-4));
        z-index: var(--z-toast);
        display: flex;
        flex-direction: column-reverse;
        align-items: center;
        gap: var(--space-2);
        padding: 0 var(--space-4);
        /* Let clicks fall through the gaps; individual toasts opt back in. */
        pointer-events: none;
    }

    /* Sit above the mobile bottom nav so a toast never hides behind it. */
    @media (max-width: 640px) {
        .toaster {
            bottom: calc(var(--app-bottom-nav-h) + var(--safe-bottom) + var(--space-3));
        }
    }

    .toast {
        pointer-events: auto;
        display: flex;
        align-items: center;
        gap: var(--space-3);
        width: 100%;
        max-width: 30rem;
        padding: var(--space-3) var(--space-3) var(--space-3) var(--space-4);
        border: 1px solid var(--border);
        border-left-width: 4px;
        border-radius: var(--radius-md);
        background: var(--surface-elevated);
        color: var(--text);
        box-shadow: var(--shadow-md);
        font-size: var(--font-sm);
    }

    .toast.error {
        border-color: var(--danger);
        background: var(--danger-soft-bg);
    }

    .toast.success {
        border-color: var(--success);
        background: var(--success-soft-bg);
    }

    .toast.info {
        border-color: var(--primary);
    }

    .message {
        flex: 1;
        min-width: 0;
    }

    .dismiss {
        flex-shrink: 0;
        display: inline-flex;
        align-items: center;
        justify-content: center;
        width: 28px;
        height: 28px;
        padding: 0;
        border: 0;
        border-radius: var(--radius-sm);
        background: transparent;
        color: var(--text-muted);
        cursor: pointer;
    }

    .dismiss:hover {
        background: rgb(0 0 0 / 0.06);
        color: var(--text);
    }
</style>
