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: '',
    showCardSharer: false
  }),

  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) => {
        id = id.replace(/[AB]$/, '')
        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'
      })
    },

    openCardSharer() {
      this.showCardSharer = true
    },

    scrollToBox(box: Box) {
      if (box) {
        const boxElement = document.getElementById(box.id)
        if (boxElement) {
          setTimeout(() => {
            // Récupérer la position de l'élément
            const elementRect = boxElement.getBoundingClientRect()
            // Calculer la position de défilement (une boîte plus haut)
            const offsetPosition = elementRect.top + window.pageYOffset - elementRect.height * 1.5
            // Faire défiler à la nouvelle position
            window.scrollTo({
              top: offsetPosition,
              behavior: 'smooth'
            })
          }, 333)
        }
      }
    }
  },

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