<script setup lang="ts">
import { ref, watch, onMounted } from 'vue'
import { useClaudeHooksStore } from '../stores/claude-hooks'
import { useCanvasStore } from '../stores/canvas'

interface LogEntry {
  id: string
  source: 'hook' | 'canvas' | 'response'
  type: 'info' | 'success' | 'warning' | 'error'
  title: string
  detail: string
  timestamp: number
}

const STORAGE_KEY = 'notification-log'
const MAX_ENTRIES = 500

const hooksStore = useClaudeHooksStore()
const canvasStore = useCanvasStore()

const isOpen = ref(false)
const entries = ref<LogEntry[]>(loadFromStorage())
const filter = ref<'all' | 'hook' | 'canvas' | 'response'>('all')

// Track what we've already logged to avoid duplicates
const seenHookIds = new Set<string>()
const seenCanvasIds = new Set<number>()

// Seed seen IDs from existing entries on load
entries.value.forEach(e => {
  if (e.source === 'hook') seenHookIds.add(e.id)
})

function loadFromStorage(): LogEntry[] {
  try {
    const raw = localStorage.getItem(STORAGE_KEY)
    return raw ? JSON.parse(raw) : []
  } catch {
    return []
  }
}

function saveToStorage() {
  try {
    localStorage.setItem(STORAGE_KEY, JSON.stringify(entries.value.slice(-MAX_ENTRIES)))
  } catch { /* quota exceeded — silently ignore */ }
}

function addEntry(entry: LogEntry) {
  entries.value.push(entry)
  if (entries.value.length > MAX_ENTRIES) {
    entries.value = entries.value.slice(-MAX_ENTRIES)
  }
  saveToStorage()
}

function clearAll() {
  entries.value = []
  seenHookIds.clear()
  seenCanvasIds.clear()
  localStorage.removeItem(STORAGE_KEY)
}

function formatTime(ts: number): string {
  return new Date(ts).toLocaleTimeString('es', { hour: '2-digit', minute: '2-digit', second: '2-digit' })
}

function formatDate(ts: number): string {
  return new Date(ts).toLocaleDateString('es', { day: '2-digit', month: 'short' })
}

// Group entries by date
function getFilteredEntries() {
  if (filter.value === 'all') return entries.value
  return entries.value.filter(e => e.source === filter.value)
}

// Watch hook notifications
watch(() => hooksStore.notifications, (notifs) => {
  for (const n of notifs) {
    if (seenHookIds.has(n.id)) continue
    seenHookIds.add(n.id)
    addEntry({
      id: n.id,
      source: 'hook',
      type: n.type,
      title: n.title,
      detail: n.detail,
      timestamp: n.timestamp
    })
  }
}, { deep: true })

// Watch canvas notifications
watch(() => canvasStore.notifications, (notifs) => {
  for (const n of notifs) {
    if (seenCanvasIds.has(n.id)) continue
    seenCanvasIds.add(n.id)
    addEntry({
      id: `canvas_${n.id}`,
      source: 'canvas',
      type: n.type as LogEntry['type'],
      title: 'App',
      detail: n.message,
      timestamp: Date.now()
    })
  }
}, { deep: true })

// Expose addResponseEntry for external use (FloatingResponse)
function addResponseEntry(message: string, type: 'info' | 'success' | 'warning' | 'error' = 'info') {
  addEntry({
    id: `resp_${Date.now()}_${Math.random().toString(36).slice(2, 5)}`,
    source: 'response',
    type,
    title: 'Agent Response',
    detail: message.length > 300 ? message.slice(0, 300) + '...' : message,
    timestamp: Date.now()
  })
}

defineExpose({ addResponseEntry })

const count = ref(0)
watch(entries, (e) => { count.value = e.length }, { immediate: true })

const sourceLabels: Record<string, string> = {
  hook: 'Hook',
  canvas: 'App',
  response: 'Response'
}

const typeColors: Record<string, string> = {
  info: '#6366f1',
  success: '#10b981',
  warning: '#f59e0b',
  error: '#ef4444'
}
</script>

<template>
  <Teleport to="body">
    <!-- Toggle button -->
    <button
      class="notif-log-toggle"
      :class="{ open: isOpen }"
      @click="isOpen = !isOpen"
      title="Notification Log"
    >
      <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
        <path d="M18 8A6 6 0 0 0 6 8c0 7-3 9-3 9h18s-3-2-3-9"/>
        <path d="M13.73 21a2 2 0 0 1-3.46 0"/>
      </svg>
      <span v-if="count > 0" class="notif-badge">{{ count > 99 ? '99+' : count }}</span>
    </button>

    <!-- Panel -->
    <Transition name="notif-slide">
      <div v-if="isOpen" class="notif-log-panel">
        <div class="notif-log-header">
          <span class="notif-log-title">Notifications ({{ getFilteredEntries().length }})</span>
          <div class="notif-log-actions">
            <select v-model="filter" class="notif-filter">
              <option value="all">All</option>
              <option value="hook">Hooks</option>
              <option value="canvas">App</option>
              <option value="response">Response</option>
            </select>
            <button @click="clearAll" class="notif-clear" title="Clear all">Clear</button>
            <button @click="isOpen = false" class="notif-close">&times;</button>
          </div>
        </div>
        <div class="notif-log-body">
          <template v-if="getFilteredEntries().length">
            <div
              v-for="entry in [...getFilteredEntries()].reverse()"
              :key="entry.id"
              class="notif-entry"
            >
              <div class="notif-entry-accent" :style="{ background: typeColors[entry.type] }"></div>
              <div class="notif-entry-content">
                <div class="notif-entry-top">
                  <span class="notif-source" :class="entry.source">{{ sourceLabels[entry.source] || entry.source }}</span>
                  <span class="notif-type-dot" :style="{ background: typeColors[entry.type] }"></span>
                  <span class="notif-entry-title">{{ entry.title }}</span>
                  <span class="notif-entry-time">{{ formatTime(entry.timestamp) }}</span>
                  <span class="notif-entry-date">{{ formatDate(entry.timestamp) }}</span>
                </div>
                <div v-if="entry.detail" class="notif-entry-detail">{{ entry.detail }}</div>
              </div>
            </div>
          </template>
          <div v-else class="notif-empty">No notifications yet</div>
        </div>
      </div>
    </Transition>
  </Teleport>
</template>

<style scoped>
.notif-log-toggle {
  position: fixed;
  top: 8px;
  right: 80px;
  width: 30px;
  height: 30px;
  border-radius: 8px;
  background: rgba(40, 40, 50, 0.85);
  border: 1px solid rgba(255, 255, 255, 0.1);
  color: #999;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 10003;
  transition: all 0.2s ease;
  -webkit-app-region: no-drag;
  app-region: no-drag;
}

.notif-log-toggle:hover {
  background: rgba(60, 60, 75, 0.95);
  color: #ddd;
  border-color: rgba(99, 102, 241, 0.4);
}

.notif-log-toggle.open {
  background: rgba(99, 102, 241, 0.25);
  color: #a5b4fc;
  border-color: rgba(99, 102, 241, 0.5);
}

.notif-badge {
  position: absolute;
  top: -4px;
  right: -4px;
  background: #ef4444;
  color: white;
  font-size: 8px;
  font-weight: 700;
  padding: 1px 4px;
  border-radius: 10px;
  min-width: 14px;
  text-align: center;
  line-height: 1.3;
}

/* Panel */
.notif-log-panel {
  position: fixed;
  top: 44px;
  right: 12px;
  width: 380px;
  max-height: calc(100vh - 100px);
  background: rgba(18, 18, 24, 0.98);
  border: 1px solid rgba(255, 255, 255, 0.1);
  border-radius: 12px;
  z-index: 10003;
  display: flex;
  flex-direction: column;
  backdrop-filter: blur(12px);
  box-shadow: 0 12px 40px rgba(0, 0, 0, 0.6);
}

.notif-log-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 10px 14px;
  border-bottom: 1px solid rgba(255, 255, 255, 0.08);
  flex-shrink: 0;
}

.notif-log-title {
  font-size: 12px;
  font-weight: 600;
  color: #ccc;
}

.notif-log-actions {
  display: flex;
  align-items: center;
  gap: 6px;
}

.notif-filter {
  background: rgba(255, 255, 255, 0.08);
  border: 1px solid rgba(255, 255, 255, 0.1);
  border-radius: 4px;
  color: #aaa;
  font-size: 10px;
  padding: 2px 4px;
  cursor: pointer;
  outline: none;
}

.notif-filter option {
  background: #1a1a24;
}

.notif-clear,
.notif-close {
  background: rgba(255, 255, 255, 0.08);
  border: none;
  border-radius: 4px;
  color: #888;
  font-size: 10px;
  padding: 3px 8px;
  cursor: pointer;
  transition: all 0.15s;
}

.notif-close {
  font-size: 16px;
  padding: 0 6px;
  line-height: 1;
}

.notif-clear:hover { background: rgba(239, 68, 68, 0.25); color: #fca5a5; }
.notif-close:hover { background: rgba(255, 255, 255, 0.15); color: #ddd; }

/* Body */
.notif-log-body {
  flex: 1;
  overflow-y: auto;
  padding: 6px;
  max-height: calc(100vh - 180px);
}

.notif-log-body::-webkit-scrollbar {
  width: 4px;
}

.notif-log-body::-webkit-scrollbar-track {
  background: transparent;
}

.notif-log-body::-webkit-scrollbar-thumb {
  background: rgba(255, 255, 255, 0.1);
  border-radius: 2px;
}

/* Entry */
.notif-entry {
  display: flex;
  gap: 0;
  margin-bottom: 2px;
  border-radius: 6px;
  overflow: hidden;
  background: rgba(255, 255, 255, 0.03);
  transition: background 0.15s;
}

.notif-entry:hover {
  background: rgba(255, 255, 255, 0.06);
}

.notif-entry-accent {
  width: 3px;
  flex-shrink: 0;
}

.notif-entry-content {
  flex: 1;
  padding: 6px 8px;
  min-width: 0;
}

.notif-entry-top {
  display: flex;
  align-items: center;
  gap: 5px;
  font-size: 11px;
}

.notif-source {
  font-size: 9px;
  font-weight: 600;
  padding: 1px 5px;
  border-radius: 3px;
  text-transform: uppercase;
  letter-spacing: 0.3px;
  flex-shrink: 0;
}

.notif-source.hook {
  background: rgba(99, 102, 241, 0.2);
  color: #a5b4fc;
}

.notif-source.canvas {
  background: rgba(16, 185, 129, 0.2);
  color: #6ee7b7;
}

.notif-source.response {
  background: rgba(245, 158, 11, 0.2);
  color: #fcd34d;
}

.notif-type-dot {
  width: 5px;
  height: 5px;
  border-radius: 50%;
  flex-shrink: 0;
}

.notif-entry-title {
  color: #ccc;
  font-weight: 500;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  flex: 1;
}

.notif-entry-time {
  color: #555;
  font-size: 10px;
  flex-shrink: 0;
  font-family: 'Consolas', 'Monaco', monospace;
}

.notif-entry-date {
  color: #444;
  font-size: 9px;
  flex-shrink: 0;
}

.notif-entry-detail {
  color: #777;
  font-size: 10px;
  margin-top: 2px;
  word-break: break-word;
  line-height: 1.4;
}

.notif-empty {
  text-align: center;
  color: #555;
  padding: 40px 20px;
  font-size: 12px;
}

/* Transitions */
.notif-slide-enter-active,
.notif-slide-leave-active {
  transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);
}

.notif-slide-enter-from,
.notif-slide-leave-to {
  opacity: 0;
  transform: translateY(-10px) scale(0.97);
}

@media (max-width: 480px) {
  .notif-log-panel {
    left: 8px;
    right: 8px;
    width: auto;
  }
}
</style>
