import { atom } from 'nanostores'
import { ChatMessage, Choice } from '../types'

// Authentication state
export const isLoggedInStore = atom<boolean>(false)

// VN Interface state
export const isStandbyStore = atom<boolean>(false)
export const currentTimeStore = atom<Date>(new Date())
export const weatherStore = atom<string>('Tokyo - Sunny 22°C')
export const showChoicesStore = atom<boolean>(false)
export const showSettingsModalStore = atom<boolean>(false)
export const isVisibleStore = atom<boolean>(false)
export const yenBalanceStore = atom<number>(15000)

// VN Page state
export const loadingStore = atom<boolean>(true)
export const loadingCompleteStore = atom<boolean>(false)
export const messagesStore = atom<ChatMessage[]>([
  { id: 'm1', role: 'assistant', content: 'A warm CRT glow fills the room. A figure turns towards you...' },
])
export const choicesStore = atom<Choice[]>([
  { id: 'greet', label: '"Hello?"' },
  { id: 'who', label: '"Who are you?"' },
  { id: 'silence', label: '(Stay silent)' },
])
export const statusStore = atom<string>('OFFLINE')
export const nameStore = atom<string>('???')
export const backgroundStore = atom<string>('/__gaogao__56242cbde8f18ac64522e410bad04e68_waifu2x_art_noise2.png')
export const locationStore = atom<string>('Tokyo')
export const configModalOpenStore = atom<boolean>(false)
export const skipIntroStore = atom<boolean>(
  (() => {
    const saved = localStorage.getItem('skipIntro')
    return saved === 'true'
  })()
)

// Actions
export const login = () => {
  isLoggedInStore.set(true)
}

export const logout = () => {
  isLoggedInStore.set(false)
}

export const toggleStandby = () => {
  isStandbyStore.set(!isStandbyStore.get())
}

export const toggleShowChoices = () => {
  showChoicesStore.set(!showChoicesStore.get())
}

export const updateTime = () => {
  currentTimeStore.set(new Date())
}

export const addMessage = (message: ChatMessage) => {
  messagesStore.set([...messagesStore.get(), message])
}

export const setChoices = (choices: Choice[]) => {
  choicesStore.set(choices)
}

export const clearChoices = () => {
  choicesStore.set([])
}

export const setBackground = (src: string) => {
  backgroundStore.set(src)
}

export const setName = (name: string) => {
  nameStore.set(name)
}

export const setStatus = (status: string) => {
  statusStore.set(status)
}

export const setSkipIntro = (skip: boolean) => {
  skipIntroStore.set(skip)
  localStorage.setItem('skipIntro', skip.toString())
}

export const setLoadingComplete = (complete: boolean) => {
  loadingCompleteStore.set(complete)
  if (complete) {
    loadingStore.set(false)
  }
}