import { ref, computed, watch } from 'vue'
import { useProjectsStore } from '../stores/projects'

/**
 * Composable для фильтрации по отделам
 * Автоматически сохраняет выбор в localStorage
 * Берёт departments из Pinia store
 * 
 * Использование:
 *   import { useDepartmentFilter } from '@/composables/useDepartmentFilter'
 *   const { activeDepartment, departmentOptions, resetFilter } = useDepartmentFilter()
 */
export function useDepartmentFilter() {
  const store = useProjectsStore()

  // Восстанавливаем из localStorage
  const savedDepartment = localStorage.getItem('activeDepartment')
  const activeDepartment = ref(savedDepartment ? parseInt(savedDepartment) : null)

  // Опции для MobileSelect
  const departmentOptions = computed(() => [
    { id: null, label: 'Все отделы' },
    ...store.departments.map(d => ({
      id: d.id,
      label: d.name_departments
    }))
  ])

  // Сохраняем в localStorage при изменении
  watch(activeDepartment, (newVal) => {
    if (newVal === null) {
      localStorage.removeItem('activeDepartment')
    } else {
      localStorage.setItem('activeDepartment', newVal.toString())
    }
  })

  // Сброс фильтра
  const resetFilter = () => {
    activeDepartment.value = null
  }

  return {
    activeDepartment,
    departmentOptions,
    resetFilter
  }
}
