<!--
|--------------------------------------------------------------------------
| Agência PSI
|--------------------------------------------------------------------------
| Criado e desenvolvido por Leonardo Nohama
|
| Tecnologia aplicada à escuta.
| Estrutura para o cuidado.
|
| Arquivo: src/components/notifications/NotificationDrawer.vue
| Data: 2026
| Local: São Carlos/SP — Brasil
|--------------------------------------------------------------------------
| © 2026 — Todos os direitos reservados
|--------------------------------------------------------------------------
-->
<script setup>
import { ref, computed, onMounted } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { useToast } from 'primevue/usetoast';
import { isToday, isYesterday, differenceInDays } from 'date-fns';
import {
    useNotificationStore,
    requestBrowserNotificationPermission,
    setBrowserNotificationEnabled,
    getBrowserNotificationEnabled
} from '@/stores/notificationStore';
import NotificationItem from './NotificationItem.vue';

const store = useNotificationStore();
const router = useRouter();
const route = useRoute();
const toast = useToast();

const filter = ref('unread'); // 'unread' | 'all'
const browserNotifOn = ref(false);

onMounted(() => {
    browserNotifOn.value = getBrowserNotificationEnabled();
});

async function toggleBrowserNotif() {
    if (browserNotifOn.value) {
        // desliga
        setBrowserNotificationEnabled(false);
        browserNotifOn.value = false;
        toast.add({ severity: 'info', summary: 'Notificações do browser desligadas', life: 2500 });
        return;
    }
    const granted = await requestBrowserNotificationPermission();
    if (granted) {
        setBrowserNotificationEnabled(true);
        browserNotifOn.value = true;
        toast.add({ severity: 'success', summary: 'Notificações do browser ativadas', life: 2500 });
    } else {
        toast.add({
            severity: 'warn',
            summary: 'Permissão negada',
            detail: 'Habilite nas configurações do browser se mudar de ideia.',
            life: 4000
        });
    }
}

const drawerOpen = computed({
    get: () => store.drawerOpen,
    set: (v) => {
        store.drawerOpen = v;
    }
});

const displayedItems = computed(() => (filter.value === 'unread' ? store.unreadItems : store.allItems));

// Agrupa por bucket temporal: Hoje / Ontem / Esta semana / Mais antigas.
// Mantém ordem original (já vem desc do store).
const groupedItems = computed(() => {
    const buckets = { hoje: [], ontem: [], semana: [], antigas: [] };
    const now = new Date();
    for (const item of displayedItems.value) {
        const d = new Date(item.created_at);
        if (isToday(d)) buckets.hoje.push(item);
        else if (isYesterday(d)) buckets.ontem.push(item);
        else if (differenceInDays(now, d) <= 7) buckets.semana.push(item);
        else buckets.antigas.push(item);
    }
    return [
        { key: 'hoje',     label: 'Hoje',          items: buckets.hoje     },
        { key: 'ontem',    label: 'Ontem',         items: buckets.ontem    },
        { key: 'semana',   label: 'Esta semana',   items: buckets.semana   },
        { key: 'antigas',  label: 'Mais antigas',  items: buckets.antigas  }
    ].filter((g) => g.items.length > 0);
});

function handleRead(id) {
    store.markRead(id);
    // Fecha o drawer e deixa a navegação acontecer
    store.drawerOpen = false;
}

function handleArchive(id) {
    store.archive(id);
}

function goToHistory() {
    // Se o user está em /melissa/*, navega pra equivalente Melissa
    // (preserva o overlay) — senão cai na rota do role.
    const target = route.path?.startsWith('/melissa') ? '/melissa/notificacoes' : '/therapist/notificacoes';
    router.push(target);
    store.drawerOpen = false;
}
</script>

<template>
    <Drawer
        v-model:visible="drawerOpen"
        position="right"
        :style="{ width: '420px' }"
        :pt="{ header: { class: 'notification-drawer__header' } }"
    >
        <!-- Header -->
        <template #header>
            <div class="notification-drawer__header-content">
                <div class="notification-drawer__title-wrap">
                    <span class="notification-drawer__title">Notificações</span>
                    <span v-if="store.unreadCount > 0" class="notification-drawer__count-pill">
                        {{ store.unreadCount > 99 ? '99+' : store.unreadCount }} não lida{{ store.unreadCount === 1 ? '' : 's' }}
                    </span>
                </div>
                <button
                    type="button"
                    class="notification-drawer__icon-btn"
                    :class="{ 'notification-drawer__icon-btn--active': browserNotifOn }"
                    :title="browserNotifOn ? 'Desativar notificações do browser' : 'Ativar notificações do browser'"
                    @click="toggleBrowserNotif"
                >
                    <i :class="['pi', browserNotifOn ? 'pi-bell' : 'pi-bell-slash']" />
                </button>
            </div>
        </template>

        <!-- Corpo -->
        <div class="notification-drawer__body">
            <!-- Toolbar: tabs + mark-all -->
            <div class="notification-drawer__toolbar">
                <div class="notification-drawer__tabs" role="tablist">
                    <button
                        class="notification-drawer__tab"
                        :class="{ 'notification-drawer__tab--active': filter === 'unread' }"
                        role="tab"
                        :aria-selected="filter === 'unread'"
                        @click="filter = 'unread'"
                    >
                        Não lidas
                        <span v-if="store.unreadCount > 0" class="notification-drawer__tab-count">
                            {{ store.unreadCount }}
                        </span>
                    </button>
                    <button
                        class="notification-drawer__tab"
                        :class="{ 'notification-drawer__tab--active': filter === 'all' }"
                        role="tab"
                        :aria-selected="filter === 'all'"
                        @click="filter = 'all'"
                    >Todas</button>
                </div>

                <button
                    v-if="store.unreadCount > 0"
                    type="button"
                    class="notification-drawer__mark-all"
                    @click="store.markAllRead()"
                >
                    <i class="pi pi-check-square" />
                    <span>Marcar todas</span>
                </button>
            </div>

            <!-- Lista agrupada por data -->
            <div v-if="displayedItems.length > 0" class="notification-drawer__list">
                <section
                    v-for="group in groupedItems"
                    :key="group.key"
                    class="notification-drawer__group"
                >
                    <header class="notification-drawer__group-head">
                        <span class="notification-drawer__group-label">{{ group.label }}</span>
                        <span class="notification-drawer__group-line" />
                        <span class="notification-drawer__group-count">{{ group.items.length }}</span>
                    </header>
                    <NotificationItem
                        v-for="item in group.items"
                        :key="item.id"
                        :item="item"
                        @read="handleRead"
                        @archive="handleArchive"
                    />
                </section>
            </div>

            <!-- Empty state -->
            <div v-else class="notification-drawer__empty">
                <div class="notification-drawer__empty-art" aria-hidden="true">
                    <i class="pi pi-check-circle" />
                </div>
                <p class="notification-drawer__empty-text">Tudo em dia por aqui</p>
                <p class="notification-drawer__empty-sub">
                    {{ filter === 'unread' ? 'Nenhuma notificação não lida no momento.' : 'Nenhuma notificação ainda.' }}
                </p>
                <button
                    v-if="filter === 'unread' && store.allItems.length > 0"
                    type="button"
                    class="notification-drawer__empty-link"
                    @click="filter = 'all'"
                >
                    Ver tudo
                </button>
            </div>
        </div>

        <!-- Footer -->
        <template #footer>
            <div class="notification-drawer__footer">
                <button class="notification-drawer__history-link" @click="goToHistory">
                    <i class="pi pi-history" />
                    <span>Ver histórico completo</span>
                    <i class="pi pi-arrow-right notification-drawer__history-arrow" />
                </button>
            </div>
        </template>
    </Drawer>
</template>

<style scoped>
/* ─── Header ─────────────────────────────────────────────────── */
.notification-drawer__header-content {
    display: flex;
    align-items: center;
    gap: 0.6rem;
    width: 100%;
}
.notification-drawer__title-wrap {
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    gap: 0.2rem;
    flex: 1;
    min-width: 0;
}
.notification-drawer__title {
    font-size: 1.05rem;
    font-weight: 700;
    letter-spacing: -0.01em;
    color: var(--text-color);
    line-height: 1.2;
}
.notification-drawer__count-pill {
    display: inline-flex;
    align-items: center;
    padding: 1px 8px;
    border-radius: 9999px;
    background: color-mix(in srgb, var(--primary-color) 12%, transparent);
    color: var(--primary-color);
    font-size: 0.65rem;
    font-weight: 700;
    letter-spacing: 0.02em;
}

.notification-drawer__icon-btn {
    width: 2rem;
    height: 2rem;
    border-radius: 50%;
    border: 1px solid var(--surface-border);
    background: var(--surface-card, transparent);
    color: var(--text-color-secondary);
    display: grid;
    place-items: center;
    cursor: pointer;
    flex-shrink: 0;
    font-size: 0.78rem;
    transition: background-color 140ms ease, color 140ms ease, border-color 140ms ease;
}
.notification-drawer__icon-btn:hover {
    background: var(--surface-hover);
    color: var(--text-color);
}
.notification-drawer__icon-btn--active {
    background: color-mix(in srgb, var(--primary-color) 14%, transparent);
    color: var(--primary-color);
    border-color: color-mix(in srgb, var(--primary-color) 35%, transparent);
}

/* ─── Body ───────────────────────────────────────────────────── */
.notification-drawer__body {
    display: flex;
    flex-direction: column;
    height: 100%;
    overflow: hidden;
    background: color-mix(in srgb, var(--surface-ground, #f8fafc) 60%, var(--surface-card, #fff));
}

/* ─── Toolbar (tabs + mark-all) ───────────────────────────────── */
.notification-drawer__toolbar {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0.65rem 0.85rem;
    border-bottom: 1px solid var(--surface-border);
    flex-shrink: 0;
    gap: 0.5rem;
    background: var(--surface-card);
    position: sticky;
    top: 0;
    z-index: 1;
}
.notification-drawer__tabs {
    display: inline-flex;
    padding: 3px;
    gap: 2px;
    background: var(--surface-100, color-mix(in srgb, var(--text-color) 6%, transparent));
    border-radius: 9999px;
}
.notification-drawer__tab {
    display: inline-flex;
    align-items: center;
    gap: 0.4rem;
    padding: 0.3rem 0.85rem;
    border-radius: 9999px;
    border: 0;
    background: transparent;
    color: var(--text-color-secondary);
    font-size: 0.78rem;
    font-weight: 600;
    cursor: pointer;
    transition: background-color 140ms ease, color 140ms ease, box-shadow 140ms ease;
}
.notification-drawer__tab:hover { color: var(--text-color); }
.notification-drawer__tab--active {
    background: var(--surface-card, #fff);
    color: var(--primary-color);
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.08);
}
.notification-drawer__tab-count {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    min-width: 1.1rem;
    height: 1.1rem;
    padding: 0 0.3rem;
    border-radius: 9999px;
    background: color-mix(in srgb, var(--primary-color) 16%, transparent);
    color: var(--primary-color);
    font-size: 0.65rem;
    font-weight: 700;
}
.notification-drawer__tab--active .notification-drawer__tab-count {
    background: color-mix(in srgb, var(--primary-color) 22%, transparent);
}

.notification-drawer__mark-all {
    display: inline-flex;
    align-items: center;
    gap: 0.35rem;
    padding: 0.32rem 0.7rem;
    border: 0;
    border-radius: 9999px;
    background: transparent;
    color: var(--text-color-secondary);
    font-size: 0.74rem;
    font-weight: 600;
    cursor: pointer;
    transition: background-color 140ms ease, color 140ms ease;
}
.notification-drawer__mark-all:hover {
    background: color-mix(in srgb, var(--primary-color) 10%, transparent);
    color: var(--primary-color);
}
.notification-drawer__mark-all i { font-size: 0.78rem; }

/* ─── Lista + grupos por data ─────────────────────────────────── */
.notification-drawer__list {
    flex: 1;
    overflow-y: auto;
    padding-bottom: 0.5rem;
    scrollbar-width: thin;
    scrollbar-color: var(--surface-300, #cbd5e1) transparent;
}
.notification-drawer__list::-webkit-scrollbar { width: 6px; }
.notification-drawer__list::-webkit-scrollbar-thumb {
    background: var(--surface-300, #cbd5e1);
    border-radius: 9999px;
}

.notification-drawer__group {
    /* o NotificationItem já tem margin lateral */
    padding-top: 0.4rem;
}
.notification-drawer__group-head {
    display: flex;
    align-items: center;
    gap: 0.5rem;
    padding: 0.55rem 1rem 0.35rem;
}
.notification-drawer__group-label {
    font-size: 0.65rem;
    font-weight: 700;
    text-transform: uppercase;
    letter-spacing: 0.08em;
    color: var(--text-color-secondary);
    opacity: 0.85;
    flex-shrink: 0;
}
.notification-drawer__group-line {
    flex: 1;
    height: 1px;
    background: var(--surface-border);
}
.notification-drawer__group-count {
    font-size: 0.65rem;
    font-weight: 700;
    color: var(--text-color-secondary);
    opacity: 0.6;
    padding: 1px 7px;
    border-radius: 9999px;
    background: color-mix(in srgb, var(--text-color) 6%, transparent);
}

/* ─── Empty state ─────────────────────────────────────────────── */
.notification-drawer__empty {
    flex: 1;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    gap: 0.6rem;
    padding: 3rem 1.5rem;
    text-align: center;
}
.notification-drawer__empty-art {
    width: 72px;
    height: 72px;
    border-radius: 50%;
    background: color-mix(in srgb, var(--primary-color) 10%, transparent);
    color: var(--primary-color);
    display: grid;
    place-items: center;
    margin-bottom: 0.4rem;
}
.notification-drawer__empty-art i { font-size: 1.8rem; }
.notification-drawer__empty-text {
    font-size: 1rem;
    font-weight: 700;
    color: var(--text-color);
    margin: 0;
    letter-spacing: -0.01em;
}
.notification-drawer__empty-sub {
    font-size: 0.82rem;
    color: var(--text-color-secondary);
    margin: 0;
    line-height: 1.4;
}
.notification-drawer__empty-link {
    margin-top: 0.6rem;
    background: transparent;
    border: 0;
    color: var(--primary-color);
    font-size: 0.85rem;
    font-weight: 600;
    cursor: pointer;
    padding: 0.3rem 0.8rem;
    border-radius: 9999px;
    transition: background-color 140ms ease;
}
.notification-drawer__empty-link:hover {
    background: color-mix(in srgb, var(--primary-color) 10%, transparent);
}

/* ─── Footer ──────────────────────────────────────────────────── */
.notification-drawer__footer {
    display: flex;
    justify-content: center;
    padding: 0.75rem 1rem;
    border-top: 1px solid var(--surface-border);
    background: var(--surface-card);
    flex-shrink: 0;
}
.notification-drawer__history-link {
    display: inline-flex;
    align-items: center;
    gap: 0.5rem;
    background: transparent;
    border: 1px solid var(--surface-border);
    color: var(--text-color-secondary);
    font-size: 0.82rem;
    font-weight: 600;
    cursor: pointer;
    padding: 0.45rem 0.95rem;
    border-radius: 9999px;
    transition: background-color 140ms ease, color 140ms ease, border-color 140ms ease, transform 140ms ease;
}
.notification-drawer__history-link:hover {
    background: color-mix(in srgb, var(--primary-color) 10%, transparent);
    color: var(--primary-color);
    border-color: color-mix(in srgb, var(--primary-color) 30%, transparent);
}
.notification-drawer__history-arrow {
    font-size: 0.7rem;
    transition: transform 140ms ease;
}
.notification-drawer__history-link:hover .notification-drawer__history-arrow {
    transform: translateX(2px);
}
</style>
