<!--
|--------------------------------------------------------------------------
| Agência PSI
|--------------------------------------------------------------------------
| Arquivo: src/layout/melissa/MelissaAgendaHistoricoCard.vue
| Data: 2026-05-04
|
| Card de histórico de ações na agenda — mostra movimentações, criações,
| status e edições recentes do owner_id logado. Útil quando o user move
| várias sessões e quer revisar o que fez.
|
| Lê de audit_logs via useMelissaAgendaHistorico (já agrega + classifica).
| Agrupa por dia (Hoje, Ontem, X dias atrás) pra leitura cronológica.
|--------------------------------------------------------------------------
-->
<script setup>
import { computed, onMounted } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { useMelissaAgendaHistorico } from './composables/useMelissaAgendaHistorico';

const emit = defineEmits(['open-evento']);

// days=1 já cobre "hoje" no servidor (last 24h); o filtro abaixo refina
// pra início do dia local — entradas das últimas 24h que cruzam meia-noite
// não devem aparecer no card "de hoje".
const { entries, loading, refetch } = useMelissaAgendaHistorico({ limit: 30, days: 1 });

const router = useRouter();
const route = useRoute();

onMounted(refetch);

// Filtra estritamente pro dia atual (00:00 → agora). Audit logs vêm em UTC,
// new Date(iso) já normaliza pra timezone local — comparar com início do
// dia local (setHours 0,0,0,0) garante consistência.
const todaysEntries = computed(() => {
    const startOfDay = new Date();
    startOfDay.setHours(0, 0, 0, 0);
    const startMs = startOfDay.getTime();
    return entries.value.filter((e) => new Date(e.when).getTime() >= startMs);
});

// Sem agrupamento por dia — só exibe entradas de hoje (sem header de grupo).
const items = computed(() => todaysEntries.value);

function goToHistoricoCompleto() {
    const target = route.path?.startsWith('/melissa') ? '/melissa/cfg-auditoria' : '/configuracoes/auditoria';
    router.push(target);
}

const KIND_META = {
    create: { icon: 'pi pi-plus-circle', color: '#4ade80', label: 'Criou' },
    move:   { icon: 'pi pi-arrows-alt',  color: '#60a5fa', label: 'Moveu' },
    status: { icon: 'pi pi-tag',         color: '#f59e0b', label: 'Status' },
    edit:   { icon: 'pi pi-pencil',      color: '#a78bfa', label: 'Editou' },
    delete: { icon: 'pi pi-trash',       color: '#f87171', label: 'Removeu' }
};

function fmtRelative(iso) {
    if (!iso) return '';
    const diff = Date.now() - new Date(iso).getTime();
    const min = Math.round(diff / 60000);
    if (min < 1) return 'agora';
    if (min < 60) return `${min} min`;
    const h = Math.round(min / 60);
    if (h < 24) return `${h}h`;
    return new Date(iso).toLocaleTimeString('pt-BR', { hour: '2-digit', minute: '2-digit' });
}

function onClickEntry(entry) {
    if (entry.kind === 'delete') return; // evento não existe mais
    if (entry.evento_id) emit('open-evento', { id: entry.evento_id });
}

defineExpose({ refetch });
</script>

<template>
    <section class="hist-card">
        <header class="hist-card__head">
            <div class="hist-card__title">
                <i class="pi pi-history" />
                <span>Histórico</span>
            </div>
            <button
                type="button"
                class="hist-card__refresh"
                :disabled="loading"
                v-tooltip.top="'Atualizar'"
                @click="refetch"
            >
                <i class="pi pi-refresh" :class="{ 'pi-spin': loading }" />
            </button>
        </header>

        <div v-if="loading && !items.length" class="hist-card__empty">
            <i class="pi pi-spin pi-spinner" /> Carregando…
        </div>
        <div v-else-if="!items.length" class="hist-card__empty">
            <i class="pi pi-inbox" />
            <span>Sem ações hoje.</span>
        </div>

        <ol v-else class="hist-card__list">
            <li
                v-for="e in items" :key="e.id"
                class="hist-card__item"
                :class="{ 'is-clickable': e.kind !== 'delete' }"
                :data-kind="e.kind"
                @click="onClickEntry(e)"
            >
                <span class="hist-card__icon" :style="{ color: KIND_META[e.kind]?.color, background: `${KIND_META[e.kind]?.color}1f` }">
                    <i :class="KIND_META[e.kind]?.icon" />
                </span>
                <div class="hist-card__body">
                    <div class="hist-card__row1">
                        <span class="hist-card__paciente" v-if="e.paciente">{{ e.paciente }}</span>
                        <span class="hist-card__paciente hist-card__paciente--anon" v-else>—</span>
                        <span class="hist-card__when">{{ fmtRelative(e.when) }}</span>
                    </div>
                    <div class="hist-card__label">{{ e.label }}</div>
                </div>
            </li>
        </ol>

        <!-- Atalho pra página de Auditoria completa (todas as entidades,
             não só agenda — documentos, pacientes, financeiro, etc). -->
        <button
            type="button"
            class="hist-card__more"
            v-tooltip.top="'Ver auditoria completa'"
            @click="goToHistoricoCompleto"
        >
            <i class="pi pi-external-link" />
            <span>Ver histórico completo</span>
        </button>
    </section>
</template>

<style scoped>
.hist-card {
    background: var(--m-bg-soft, rgba(255, 255, 255, 0.04));
    border: 1px solid var(--m-border, rgba(255, 255, 255, 0.08));
    border-radius: 14px;
    backdrop-filter: blur(18px) saturate(140%);
    -webkit-backdrop-filter: blur(18px) saturate(140%);
    padding: 12px 14px;
    color: var(--m-text, white);
    font-family: 'Segoe UI', system-ui, sans-serif;
    /* Toma o espaço restante do aside (.ma-widgets é flex column).
       min-height: 0 é necessário pra flex calcular shrink corretamente
       quando feriados expande (confirmação inline) e empurra o histórico. */
    flex: 1 1 0;
    min-height: 0;
    display: flex;
    flex-direction: column;
}
.hist-card__head {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 8px;
}
.hist-card__title {
    display: inline-flex;
    align-items: center;
    gap: 7px;
    font-size: 0.75rem;
    font-weight: 600;
    text-transform: uppercase;
    letter-spacing: 0.06em;
    color: var(--m-text-muted, rgba(255, 255, 255, 0.7));
}
.hist-card__title i { font-size: 0.78rem; opacity: 0.8; }
.hist-card__refresh {
    width: 24px;
    height: 24px;
    display: grid;
    place-items: center;
    background: transparent;
    border: none;
    border-radius: 6px;
    color: var(--m-text-muted, rgba(255, 255, 255, 0.55));
    cursor: pointer;
    font-size: 0.7rem;
    transition: background-color 140ms ease, color 140ms ease;
}
.hist-card__refresh:hover:not(:disabled) {
    background: rgba(255, 255, 255, 0.06);
    color: var(--m-text, white);
}
.hist-card__refresh:disabled {
    opacity: 0.5;
    cursor: not-allowed;
}

.hist-card__empty {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    gap: 6px;
    padding: 18px 8px;
    color: var(--m-text-muted, rgba(255, 255, 255, 0.5));
    font-size: 0.78rem;
    text-align: center;
}
.hist-card__empty .pi { font-size: 1.2rem; opacity: 0.5; }

.hist-card__list {
    list-style: none;
    margin: 0;
    padding: 0;
    /* Toma todo o restante do card. min-height:0 destrava shrink dentro
       de flex column. Sem max-height fixo: a lista cresce/encolhe junto
       com o card (que por sua vez balanceia com o feriados acima). */
    flex: 1 1 0;
    min-height: 0;
    overflow-y: auto;
    overflow-x: hidden;
    scrollbar-width: thin;
}
.hist-card__list::-webkit-scrollbar { width: 4px; }
.hist-card__list::-webkit-scrollbar-thumb {
    background: rgba(255, 255, 255, 0.15);
    border-radius: 2px;
}

.hist-card__item {
    display: flex;
    gap: 10px;
    padding: 8px 4px;
    border-radius: 8px;
    transition: background-color 140ms ease, transform 140ms ease;
    overflow: hidden;
    min-width: 0;
}
.hist-card__item.is-clickable {
    cursor: pointer;
}
.hist-card__item.is-clickable:hover {
    background: rgba(255, 255, 255, 0.05);
    transform: translateX(1px);
}
.hist-card__item[data-kind="delete"] {
    opacity: 0.7;
}
.hist-card__icon {
    flex-shrink: 0;
    width: 26px;
    height: 26px;
    border-radius: 50%;
    display: grid;
    place-items: center;
    font-size: 0.72rem;
}
.hist-card__body {
    flex: 1;
    min-width: 0;
    display: flex;
    flex-direction: column;
    gap: 2px;
}
.hist-card__row1 {
    display: flex;
    align-items: baseline;
    gap: 6px;
}
.hist-card__paciente {
    font-size: 0.78rem;
    font-weight: 600;
    color: var(--m-text, white);
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    flex: 1;
    min-width: 0;
}
.hist-card__paciente--anon { font-style: italic; opacity: 0.55; font-weight: 400; }
.hist-card__when {
    font-size: 0.68rem;
    color: var(--m-text-muted, rgba(255, 255, 255, 0.5));
    flex-shrink: 0;
    font-variant-numeric: tabular-nums;
}
.hist-card__label {
    font-size: 0.7rem;
    color: var(--m-text-muted, rgba(255, 255, 255, 0.7));
    line-height: 1.4;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

/* Botão "Ver histórico completo" — vai pra AuditoriaPage central
   (mesmo destino em /melissa/cfg-auditoria ou /configuracoes/auditoria). */
.hist-card__more {
    margin-top: 10px;
    width: 100%;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    gap: 6px;
    padding: 8px 10px;
    background: transparent;
    border: 1px dashed var(--m-border, rgba(255, 255, 255, 0.18));
    border-radius: 10px;
    color: var(--m-text-muted, rgba(255, 255, 255, 0.7));
    font-family: inherit;
    font-size: 0.72rem;
    font-weight: 500;
    letter-spacing: 0.01em;
    cursor: pointer;
    transition: background-color 140ms ease, color 140ms ease, border-color 140ms ease;
}
.hist-card__more:hover {
    background: rgba(255, 255, 255, 0.04);
    color: var(--m-text, white);
    border-color: var(--m-border-strong, rgba(255, 255, 255, 0.25));
    border-style: solid;
}
.hist-card__more i { font-size: 0.7rem; opacity: 0.85; }

/* Light mode adjusts contrast */
html:not(.app-dark) .hist-card {
    background: rgba(255, 255, 255, 0.7);
    border-color: rgba(15, 23, 42, 0.08);
}
html:not(.app-dark) .hist-card__group-label {
    background: rgba(248, 250, 252, 0.95);
}
html:not(.app-dark) .hist-card__item.is-clickable:hover {
    background: rgba(15, 23, 42, 0.04);
}
</style>
