/**
 * App Store - Global Application State
 * 
 * Pinia store for managing global app state, loading, and errors
 * Platform-neutral design for Android/iOS/Electron
 * 
 * Note: This file uses the centralized logger utility (logger) instead of
 * direct console usage. Console usage is whitelisted only in src/lib/logger.ts
 * 
 * @author Matthew Raymer
 * @version 1.0.0
 */

import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { logger } from '../lib/logger'

export interface AppState {
  isLoading: boolean
  errorMessage: string | null
  platform: string
  isNative: boolean
  notificationStatus: NotificationStatus | null
}

export interface NotificationStatus {
  canScheduleNow: boolean
  postNotificationsGranted: boolean
  channelEnabled: boolean
  channelImportance: number
  channelId: string
  exactAlarmsGranted: boolean
  exactAlarmsSupported: boolean
  androidVersion: number
  nextScheduledAt: number
}

export const useAppStore = defineStore('app', () => {
  // State
  const isLoading = ref(false)
  const errorMessage = ref<string | null>(null)
  const platform = ref('web')
  const isNative = ref(false)
  const notificationStatus = ref<NotificationStatus | null>(null)
  
  // Getters
  const hasError = computed(() => errorMessage.value !== null)
  const isNotificationReady = computed(() => 
    notificationStatus.value?.canScheduleNow ?? false
  )
  
  // Actions
  function setLoading(loading: boolean): void {
    isLoading.value = loading
  }
  
  function setError(message: string): void {
    errorMessage.value = message
    logger.error('App Error:', message)
  }
  
  function clearError(): void {
    errorMessage.value = null
  }
  
  function setPlatform(platformName: string, native: boolean): void {
    platform.value = platformName
    isNative.value = native
  }
  
  function setNotificationStatus(status: NotificationStatus): void {
    notificationStatus.value = status
  }
  
  function updateNotificationStatus(status: Partial<NotificationStatus>): void {
    if (notificationStatus.value) {
      notificationStatus.value = { ...notificationStatus.value, ...status }
    } else {
      notificationStatus.value = status as NotificationStatus
    }
  }
  
  // Reset store
  function $reset(): void {
    isLoading.value = false
    errorMessage.value = null
    platform.value = 'web'
    isNative.value = false
    notificationStatus.value = null
  }
  
  return {
    // State
    isLoading,
    errorMessage,
    platform,
    isNative,
    notificationStatus,
    
    // Getters
    hasError,
    isNotificationReady,
    
    // Actions
    setLoading,
    setError,
    clearError,
    setPlatform,
    setNotificationStatus,
    updateNotificationStatus,
    $reset
  }
})
