import { defineStore } from 'pinia'
import { ref } from 'vue'
import memberApi from '../api/member.api'
import type { Member } from '../lib/interfaces/member.interface'

export const useMemberStore = defineStore('member', () => {
  const members = ref<Member[]>([])
  let _loaded = false

  async function fetch() {
    if (_loaded) return
    try {
      members.value = await memberApi.index()
      _loaded = true
    } catch (e) {
      console.error('Failed to load team members:', e)
    }
  }

  function resolvedAvatarUrl(member: Member): string {
    if (member.image_url) return member.image_url
    return new URL(`../assets/team/${member.avatar_filename}`, import.meta.url).href
  }

  return { members, fetch, resolvedAvatarUrl }
})
