<script setup>
import { ref, computed } from 'vue';
import { useSupportDebugStore } from '@/support/supportDebugStore';
import AgendaDevDocs from '@/features/agenda/components/dev/AgendaDevDocs.vue';

const docsVisible = ref(false);

const store = useSupportDebugStore();

const panelOpen = ref(false);
const activeLevel = ref(null);
const searchQuery = ref('');
const expandedIds = ref(new Set());
const logListRef = ref(null);

const levels = [
    { label: 'Eventos', value: 'event' },
    { label: 'API', value: 'api' },
    { label: 'Agenda', value: 'agenda' },
    { label: 'Recorrência', value: 'recurrence' },
    { label: 'Tenant', value: 'tenant' },
    { label: 'Menu', value: 'menu' },
    { label: 'Perfil', value: 'profile' },
    { label: 'Auth', value: 'auth' },
    { label: 'Guard', value: 'guard' },
    { label: 'Perf', value: 'perf' },
    { label: 'Erros', value: 'error' }
];

const filteredLogs = computed(() => {
    let all = store.recentLogs;
    if (activeLevel.value) all = all.filter((l) => l.level === activeLevel.value);
    if (searchQuery.value.trim()) {
        const q = searchQuery.value.toLowerCase();
        all = all.filter((l) => l.message?.toLowerCase().includes(q) || l.source?.toLowerCase().includes(q) || (l.data ? JSON.stringify(l.data).toLowerCase().includes(q) : false));
    }
    return all;
});

function countByLevel(level) {
    return store.logs.filter((l) => l.level === level).length;
}

function toggleData(id) {
    const s = new Set(expandedIds.value);
    if (s.has(id)) s.delete(id);
    else s.add(id);
    expandedIds.value = s;
}

function formatTime(iso) {
    return new Date(iso).toLocaleTimeString('pt-BR', {
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
    });
}

function highlightSearch(text) {
    if (!searchQuery.value.trim() || !text) return escHtml(text || '');
    const q = searchQuery.value.trim();
    const re = new RegExp(`(${q.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')})`, 'gi');
    return escHtml(text).replace(re, '<mark class="sbh">$1</mark>');
}

function escHtml(s) {
    return String(s).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
}

function exportLogs() {
    const blob = new Blob([JSON.stringify(store.logs, null, 2)], { type: 'application/json' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `support-logs-${Date.now()}.json`;
    a.click();
    URL.revokeObjectURL(url);
    console.log('[SupportDebugBanner] logs exportados:', store.logs.length);
}
</script>

<template>
    <Teleport to="body">
        <Transition name="support-slide">
            <div v-if="store.isActive" class="support-banner">
                <!-- ── Barra superior ─────────────────────────────────────── -->
                <div class="support-banner__bar">
                    <div class="support-banner__bar-left">
                        <span class="support-banner__pulse" />
                        <strong>MODO SUPORTE ATIVO</strong>
                        <span class="support-banner__tenant" :title="store.tenantId"> tenant: {{ store.tenantId }} </span>
                        <span class="support-banner__count"> {{ store.logs.length }} log{{ store.logs.length !== 1 ? 's' : '' }} </span>
                    </div>

                    <div class="support-banner__bar-right">
                        <button class="support-banner__toggle" @click="panelOpen = !panelOpen">
                            <i :class="panelOpen ? 'pi pi-chevron-up' : 'pi pi-chevron-down'" />
                            {{ panelOpen ? 'Ocultar' : 'Ver Logs' }}
                            <span v-if="store.errorLogs.length" class="support-banner__err-badge"> {{ store.errorLogs.length }} erro(s) </span>
                        </button>
                        <button class="support-banner__icon-btn" title="Documentação técnica" @click="docsVisible = true">
                            <i class="pi pi-book" />
                        </button>
                        <button class="support-banner__icon-btn" title="Exportar logs (JSON)" @click="exportLogs">
                            <i class="pi pi-download" />
                        </button>
                        <button class="support-banner__icon-btn" title="Limpar logs" @click="store.clearLogs()">
                            <i class="pi pi-trash" />
                        </button>
                        <button class="support-banner__icon-btn" title="Desativar suporte" @click="store.deactivate()">
                            <i class="pi pi-times" />
                        </button>
                    </div>
                </div>

                <!-- ── Painel de logs ─────────────────────────────────────── -->
                <div v-if="panelOpen" class="support-banner__panel">
                    <!-- Toolbar: filtros + busca -->
                    <div class="support-banner__toolbar">
                        <div class="support-banner__filters">
                            <button
                                v-for="lvl in levels"
                                :key="lvl.value"
                                class="support-banner__filter-btn"
                                :class="{ 'support-banner__filter-btn--active': activeLevel === lvl.value }"
                                @click="activeLevel = activeLevel === lvl.value ? null : lvl.value"
                            >
                                {{ lvl.label }}
                                <span class="support-banner__filter-count">{{ countByLevel(lvl.value) }}</span>
                            </button>
                        </div>

                        <div class="support-banner__search-wrap">
                            <i class="pi pi-search support-banner__search-icon" />
                            <input v-model="searchQuery" type="text" placeholder="Buscar nos logs…" class="support-banner__search" />
                            <button v-if="searchQuery" class="support-banner__search-clear" @click="searchQuery = ''" title="Limpar busca">
                                <i class="pi pi-times" />
                            </button>
                        </div>
                    </div>

                    <!-- Lista -->
                    <div ref="logListRef" class="support-banner__logs">
                        <div v-if="filteredLogs.length === 0" class="support-banner__empty">
                            <span v-if="searchQuery">Nenhum resultado para "{{ searchQuery }}"</span>
                            <span v-else>Nenhum log capturado ainda. Os eventos aparecerão aqui.</span>
                        </div>

                        <div v-for="log in filteredLogs" :key="log.id" class="support-banner__log-entry" :class="`support-banner__log-entry--${log.level}`">
                            <span class="support-banner__log-time">{{ formatTime(log.timestamp) }}</span>
                            <span class="support-banner__log-level">{{ log.level }}</span>
                            <span class="support-banner__log-source">[{{ log.source }}]</span>
                            <span class="support-banner__log-msg" v-html="highlightSearch(log.message)" />
                            <button v-if="log.data" class="support-banner__log-expand" @click="toggleData(log.id)">{ }</button>
                            <pre v-if="log.data && expandedIds.has(log.id)" class="support-banner__log-data">{{ JSON.stringify(log.data, null, 2) }}</pre>
                        </div>
                    </div>

                    <!-- Rodapé -->
                    <div class="support-banner__footer">
                        <span>{{ filteredLogs.length }} / {{ store.logs.length }} entrada(s)</span>
                        <span>·</span>
                        <span :class="store.errorLogs.length ? 'text-red-400' : ''"> {{ store.errorLogs.length }} erro(s) </span>
                        <span v-if="searchQuery">· filtro: "{{ searchQuery }}"</span>
                    </div>
                </div>
            </div>
        </Transition>

        <!-- Dialog de documentação técnica -->
        <AgendaDevDocs v-model:visible="docsVisible" />
    </Teleport>
</template>

<style scoped>
.support-banner {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    z-index: 9999;
    font-family: 'JetBrains Mono', 'Fira Code', monospace, sans-serif;
    font-size: 12px;
}

/* ── Barra ───────────────────────────────────────────────── */
.support-banner__bar {
    display: flex;
    align-items: center;
    justify-content: space-between;
    background: #92400e;
    color: #fff;
    padding: 5px 14px;
    gap: 12px;
}

.support-banner__bar-left {
    display: flex;
    align-items: center;
    gap: 10px;
    font-weight: 600;
    letter-spacing: 0.05em;
    min-width: 0;
    overflow: hidden;
}

.support-banner__bar-right {
    display: flex;
    align-items: center;
    gap: 5px;
    flex-shrink: 0;
}

.support-banner__pulse {
    display: inline-block;
    width: 7px;
    height: 7px;
    border-radius: 50%;
    background: #fcd34d;
    flex-shrink: 0;
    animation: pulse 1.4s ease-in-out infinite;
}

@keyframes pulse {
    0%,
    100% {
        opacity: 1;
        transform: scale(1);
    }
    50% {
        opacity: 0.5;
        transform: scale(1.4);
    }
}

.support-banner__tenant {
    font-weight: 400;
    opacity: 0.7;
    font-size: 11px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    max-width: 260px;
}

.support-banner__count {
    font-weight: 400;
    opacity: 0.55;
    font-size: 10px;
    flex-shrink: 0;
}

.support-banner__toggle {
    background: rgba(255, 255, 255, 0.14);
    border: none;
    color: #fff;
    cursor: pointer;
    padding: 3px 10px;
    border-radius: 4px;
    font-size: 12px;
    display: flex;
    align-items: center;
    gap: 5px;
    transition: background 0.15s;
}
.support-banner__toggle:hover {
    background: rgba(255, 255, 255, 0.26);
}

.support-banner__icon-btn {
    width: 26px;
    height: 26px;
    background: rgba(255, 255, 255, 0.1);
    border: none;
    color: #fff;
    cursor: pointer;
    border-radius: 4px;
    display: grid;
    place-items: center;
    transition: background 0.15s;
}
.support-banner__icon-btn:hover {
    background: rgba(255, 255, 255, 0.25);
}

.support-banner__err-badge {
    background: #ef4444;
    color: #fff;
    border-radius: 10px;
    padding: 0 6px;
    font-size: 10px;
    font-weight: 700;
}

/* ── Painel ──────────────────────────────────────────────── */
.support-banner__panel {
    background: #0f172a;
    border-top: 2px solid #92400e;
    display: flex;
    flex-direction: column;
    max-height: 380px;
}

/* ── Toolbar ─────────────────────────────────────────────── */
.support-banner__toolbar {
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 7px 10px;
    border-bottom: 1px solid #1e293b;
    flex-shrink: 0;
    flex-wrap: wrap;
}

.support-banner__filters {
    display: flex;
    gap: 4px;
    flex-wrap: wrap;
    flex: 1;
}

.support-banner__filter-btn {
    background: #1e293b;
    border: 1px solid #334155;
    color: #94a3b8;
    border-radius: 4px;
    padding: 2px 9px;
    font-size: 11px;
    cursor: pointer;
    display: flex;
    align-items: center;
    gap: 4px;
    transition: all 0.12s;
    white-space: nowrap;
}
.support-banner__filter-btn--active {
    background: #92400e;
    border-color: #92400e;
    color: #fff;
}

.support-banner__filter-count {
    background: rgba(255, 255, 255, 0.13);
    border-radius: 8px;
    padding: 0 4px;
    font-size: 10px;
}

/* ── Search ──────────────────────────────────────────────── */
.support-banner__search-wrap {
    position: relative;
    flex-shrink: 0;
    display: flex;
    align-items: center;
}

.support-banner__search-icon {
    position: absolute;
    left: 7px;
    color: #475569;
    font-size: 11px;
    pointer-events: none;
}

.support-banner__search {
    background: #1e293b;
    border: 1px solid #334155;
    border-radius: 4px;
    color: #e2e8f0;
    font-size: 11px;
    font-family: inherit;
    padding: 3px 24px 3px 24px;
    width: 180px;
    outline: none;
    transition: border-color 0.15s;
}
.support-banner__search:focus {
    border-color: #92400e;
}
.support-banner__search::placeholder {
    color: #475569;
}

.support-banner__search-clear {
    position: absolute;
    right: 5px;
    background: none;
    border: none;
    color: #475569;
    cursor: pointer;
    font-size: 10px;
    display: grid;
    place-items: center;
    padding: 2px;
}
.support-banner__search-clear:hover {
    color: #94a3b8;
}

/* ── Logs list ───────────────────────────────────────────── */
.support-banner__logs {
    overflow-y: auto;
    flex: 1;
    padding: 2px 0;
    scrollbar-width: thin;
    scrollbar-color: #1e293b transparent;
}

.support-banner__empty {
    color: #475569;
    text-align: center;
    padding: 20px;
    font-style: italic;
}

.support-banner__log-entry {
    display: flex;
    flex-wrap: wrap;
    align-items: baseline;
    gap: 5px;
    padding: 2px 12px;
    border-bottom: 1px solid #0f1829;
    transition: background 0.1s;
}
.support-banner__log-entry:hover {
    background: #1e293b;
}

.support-banner__log-entry--error {
    border-left: 3px solid #ef4444;
}
.support-banner__log-entry--api {
    border-left: 3px solid #3b82f6;
}
.support-banner__log-entry--recurrence {
    border-left: 3px solid #8b5cf6;
}
.support-banner__log-entry--guard {
    border-left: 3px solid #10b981;
}
.support-banner__log-entry--perf {
    border-left: 3px solid #f59e0b;
}
.support-banner__log-entry--tenant {
    border-left: 3px solid #06b6d4;
}
.support-banner__log-entry--menu {
    border-left: 3px solid #84cc16;
}
.support-banner__log-entry--profile {
    border-left: 3px solid #ec4899;
}
.support-banner__log-entry--auth {
    border-left: 3px solid #f97316;
}
.support-banner__log-entry--agenda {
    border-left: 3px solid #a78bfa;
}
.support-banner__log-entry--event {
    border-left: 3px solid #475569;
}

.support-banner__log-time {
    color: #334155;
    font-size: 10px;
    flex-shrink: 0;
}
.support-banner__log-level {
    color: #f59e0b;
    font-size: 10px;
    font-weight: 700;
    text-transform: uppercase;
    flex-shrink: 0;
}
.support-banner__log-source {
    color: #7c3aed;
    font-size: 10px;
    flex-shrink: 0;
}
.support-banner__log-msg {
    color: #cbd5e1;
    flex: 1;
}

.support-banner__log-expand {
    background: #1e293b;
    border: 1px solid #334155;
    color: #64748b;
    border-radius: 3px;
    padding: 0 5px;
    cursor: pointer;
    font-size: 10px;
    font-family: monospace;
    flex-shrink: 0;
}
.support-banner__log-expand:hover {
    color: #e2e8f0;
}

.support-banner__log-data {
    width: 100%;
    margin: 3px 0 2px;
    background: #020617;
    border: 1px solid #1e293b;
    color: #94a3b8;
    padding: 7px;
    border-radius: 4px;
    font-size: 10px;
    overflow-x: auto;
    white-space: pre-wrap;
    word-break: break-all;
}

/* mark de busca */
:deep(.sbh) {
    background: rgba(250, 204, 21, 0.3);
    color: #fde68a;
    border-radius: 2px;
    padding: 0 1px;
}

/* ── Footer ──────────────────────────────────────────────── */
.support-banner__footer {
    display: flex;
    gap: 8px;
    padding: 4px 12px;
    color: #334155;
    font-size: 10px;
    border-top: 1px solid #1e293b;
    flex-shrink: 0;
}

/* ── Transition ──────────────────────────────────────────── */
.support-slide-enter-active,
.support-slide-leave-active {
    transition: transform 0.25s ease;
}
.support-slide-enter-from,
.support-slide-leave-to {
    transform: translateY(100%);
}
</style>
