import { defineStore } from 'pinia'
import axios from 'axios'
import type { Component } from '../types/component'

export const useComponentStore = defineStore('components', {
  state: () => ({
    components: [] as Array<Component>,
    locale: (localStorage.getItem('lang') || 'de')
  }),
  actions: {
    async getComponents(locale: string) {
      await this.setLocale(locale)
      return this.components

    },

    async setLocale(locale: string) {
      if (this.components.length == 0 || this.locale != locale) {
        this.locale = locale
        await this.fetchComponents()
      }
    },

    async fetchComponents() {
      const response = await axios.get(import.meta.env.VITE_STRAPI_URL + '/components?locale=' + this.locale, {
        headers: {
          Authorization: "Bearer " + import.meta.env.VITE_STRAPI_TOKEN,
        },
      })
      this.components = response.data.data
    },
  }
})


