<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { invoke } from '@tauri-apps/api/core'
import { emit, listen } from '@tauri-apps/api/event'
import type { UnlistenFn } from '@tauri-apps/api/event'
import { Square, Maximize2 } from 'lucide-vue-next'
import { loadAndApplyTimerFont } from '../utils/fonts'
import { loadAndApplyUIFont } from '../utils/uiFonts'
import { useAnnouncer } from '../composables/useAnnouncer'

interface TimerSyncPayload {
  projectId: number | null
  timerState: string
  elapsedSeconds: number
}

const projectId = ref<number | null>(null)
const timerState = ref('STOPPED')
const elapsedSeconds = ref(0)
const projects = ref<Array<{ id: number; name: string; color: string }>>([])
const theme = ref<{ theme_mode?: string; accent_color?: string }>({})

const { announcement: miniAnnouncement, announce } = useAnnouncer()
let previousTimerState = 'STOPPED'
let unlisten: UnlistenFn | null = null

const isRunning = computed(() => timerState.value === 'RUNNING')
const isPausedManual = computed(() => timerState.value === 'PAUSED_MANUAL')
const isActive = computed(() => timerState.value !== 'STOPPED')

const formattedTime = computed(() => {
  const h = Math.floor(elapsedSeconds.value / 3600)
  const m = Math.floor((elapsedSeconds.value % 3600) / 60)
  const s = elapsedSeconds.value % 60
  return `${h.toString().padStart(2, '0')}:${m.toString().padStart(2, '0')}:${s.toString().padStart(2, '0')}`
})

const projectName = computed(() => {
  if (!projectId.value) return 'No project'
  return projects.value.find(p => p.id === projectId.value)?.name || 'Unknown'
})

const projectColor = computed(() => {
  if (!projectId.value) return '#6B7280'
  return projects.value.find(p => p.id === projectId.value)?.color || '#6B7280'
})

onMounted(async () => {
  // Fetch projects and settings for display
  try {
    const [p, s] = await Promise.all([
      invoke<Array<{ id: number; name: string; color: string }>>('get_projects'),
      invoke<Record<string, string>>('get_settings'),
    ])
    projects.value = p
    theme.value = s
    loadAndApplyTimerFont(s.timer_font || 'JetBrains Mono')
    const dyslexia = s.dyslexia_mode === 'true'
    const uiFont = dyslexia ? 'OpenDyslexic' : (s.ui_font || 'Inter')
    if (uiFont !== 'Inter') loadAndApplyUIFont(uiFont)
  } catch (e) {
    console.error('Mini-timer init error:', e)
  }

  // Apply theme
  const el = document.documentElement
  const mode = theme.value.theme_mode || 'dark'
  if (mode === 'system') {
    const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches
    el.setAttribute('data-theme', prefersDark ? 'dark' : 'light')
  } else {
    el.setAttribute('data-theme', mode)
  }
  el.setAttribute('data-accent', theme.value.accent_color || 'amber')

  // Listen for timer state from main window
  unlisten = await listen<TimerSyncPayload>('timer-sync', (event) => {
    const newState = event.payload.timerState
    if (newState !== previousTimerState) {
      if (newState === 'RUNNING' && previousTimerState !== 'STOPPED') {
        announce('Timer resumed')
      } else if (newState === 'RUNNING') {
        announce('Timer started')
      } else if (newState === 'PAUSED_MANUAL') {
        announce('Timer paused')
      } else if (newState === 'PAUSED_IDLE') {
        announce('Idle detected - timer paused')
      } else if (newState === 'PAUSED_APP') {
        announce('App not visible - timer paused')
      } else if (newState === 'STOPPED' && previousTimerState !== 'STOPPED') {
        announce('Timer stopped')
      }
      previousTimerState = newState
    }
    projectId.value = event.payload.projectId
    timerState.value = event.payload.timerState
    elapsedSeconds.value = event.payload.elapsedSeconds
  })

  // Request current state
  await emit('mini-timer-ready')
})

onUnmounted(() => {
  if (unlisten) unlisten()
})

async function stopTimer() {
  await emit('mini-timer-stop')
}

async function pauseTimer() {
  await emit('mini-timer-pause')
}

async function resumeTimer() {
  await emit('mini-timer-resume')
}

async function expandToMain() {
  try {
    await invoke('close_mini_timer')
  } catch (e) {
    console.error(e)
  }
}
</script>

<template>
  <div class="h-full w-full flex items-center gap-3 px-4 bg-bg-base select-none" style="-webkit-app-region: drag">
    <span class="w-2.5 h-2.5 rounded-full shrink-0" :style="{ backgroundColor: projectColor }" aria-hidden="true" />
    <span class="text-[0.75rem] text-text-primary truncate flex-1">{{ projectName }}</span>
    <span role="timer" :aria-label="'Elapsed time: ' + formattedTime" class="text-[1rem] font-[family-name:var(--font-timer)] text-accent-text font-medium tracking-tight">{{ formattedTime }}</span>
    <div class="flex items-center gap-1" style="-webkit-app-region: no-drag">
      <!-- Pause button (when running) -->
      <button
        v-if="isRunning"
        @click="pauseTimer"
        class="w-6 h-6 flex items-center justify-center rounded text-text-tertiary hover:text-status-warning transition-colors"
        aria-label="Pause"
        v-tooltip="'Pause'"
      >
        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" fill="currentColor" class="w-3 h-3" aria-hidden="true">
          <rect x="3" y="2" width="3.5" height="12" rx="1" />
          <rect x="9.5" y="2" width="3.5" height="12" rx="1" />
        </svg>
      </button>
      <!-- Resume button (when manually paused) -->
      <button
        v-else-if="isPausedManual"
        @click="resumeTimer"
        class="w-6 h-6 flex items-center justify-center rounded text-text-tertiary hover:text-accent-text transition-colors"
        aria-label="Resume"
        v-tooltip="'Resume'"
      >
        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" fill="currentColor" class="w-3 h-3" aria-hidden="true">
          <path d="M4 2.5a.5.5 0 01.77-.42l9 5.5a.5.5 0 010 .84l-9 5.5A.5.5 0 014 13.5V2.5z" />
        </svg>
      </button>
      <!-- Stop button -->
      <button
        v-if="isActive"
        @click="stopTimer"
        class="w-6 h-6 flex items-center justify-center rounded-full bg-status-error hover:bg-status-error/80 transition-colors"
        aria-label="Stop timer"
        v-tooltip="'Stop'"
      >
        <Square class="w-2.5 h-2.5 text-white" fill="white" aria-hidden="true" />
      </button>
      <button
        @click="expandToMain"
        class="w-6 h-6 flex items-center justify-center rounded text-text-tertiary hover:text-text-secondary transition-colors"
        aria-label="Expand to main window"
        v-tooltip="'Expand'"
      >
        <Maximize2 class="w-3 h-3" aria-hidden="true" />
      </button>
    </div>
    <div class="sr-only" aria-live="assertive" aria-atomic="true">{{ miniAnnouncement }}</div>
  </div>
</template>
