import { defineStore } from 'pinia'
import { useDataStore } from '~/store/data'
import type { Box } from '~/../types/types'

export const useUiStore = defineStore('ui', {
  state: () => ({
    // UI-only state can live here later
    showSearch: false,
    searchQuery: ''
  }),

  actions: {
    openSearch() {
      this.showSearch = true
      // reset query on open to avoid stale state
      this.searchQuery = ''
    },

    closeSearch() {
      this.showSearch = false
      this.searchQuery = ''
    },

    setSearchQuery(q: string) {
      this.searchQuery = q
    },

    listBoxes() {
      const dataStore = useDataStore()
      dataStore.boxes.forEach((box) => {
        box.state = 'box-list'
      })
    },

    selectBox(id: string) {
      const dataStore = useDataStore()
      dataStore.boxes.forEach((box) => {
        box.state = box.id === id ? 'box-selected' : 'box-hidden'
      })
    },

    closeBox() {
      const selectedBox = this.getSelectedBox
      const dataStore = useDataStore()
      dataStore.boxes.forEach((box) => {
        box.state = 'box-list'
      })
      // Scroll back to the unselected box in the list
      if (selectedBox) this.scrollToBox(selectedBox)
    },

    scrollToBox(box: Box) {
      if (box) {
        const boxElement = document.getElementById(box.id)
        if (boxElement) {
          setTimeout(() => {
            boxElement.scrollIntoView({ behavior: 'smooth' })
          }, 333)
        }
      }
    }
  },

  getters: {
    getSelectedBox: () => {
      const dataStore = useDataStore()
      return (dataStore.boxes as Box[]).find((box) => box.state === 'box-selected') || null
    }
  }
})
