import { ref } from 'vue'

const STORAGE_KEY = 'mv_saved_filters'

/**
 * Composable for persisted user-defined filters.
 *
 * Each saved filter stores a name and a snapshot of the activeFilters object.
 * Data lives in localStorage so it survives app updates and page reloads.
 *
 * @returns {{ savedFilters, addFilter, removeFilter, updateFilter }}
 */
export function useSavedFilters() {
	function load() {
		try {
			const raw = localStorage.getItem(STORAGE_KEY)
			if (raw) {
				const parsed = JSON.parse(raw)
				if (Array.isArray(parsed)) {
					return parsed
				}
			}
		} catch {
			// ignore corrupt data
		}
		return []
	}

	const savedFilters = ref(load())

	function persist() {
		localStorage.setItem(STORAGE_KEY, JSON.stringify(savedFilters.value))
	}

	/**
	 * Save the current filter combination under a name.
	 *
	 * @param {string} name - Human-readable label
	 * @param {{ status: string|null, rolle: string|null, birthdayThisMonth: boolean, unpaidFees: boolean }} filters
	 */
	function addFilter(name, filters) {
		savedFilters.value.push({
			id: Date.now().toString(36) + Math.random().toString(36).slice(2, 6),
			name,
			filters: { ...filters },
		})
		persist()
	}

	/**
	 * Delete a saved filter by ID.
	 *
	 * @param {string} id
	 */
	function removeFilter(id) {
		savedFilters.value = savedFilters.value.filter(f => f.id !== id)
		persist()
	}

	/**
	 * Rename or update filters of an existing saved filter.
	 *
	 * @param {string} id
	 * @param {{ name?: string, filters?: object }} patch
	 */
	function updateFilter(id, patch) {
		const entry = savedFilters.value.find(f => f.id === id)
		if (!entry) return
		if (patch.name !== undefined) entry.name = patch.name
		if (patch.filters !== undefined) entry.filters = { ...patch.filters }
		persist()
	}

	return { savedFilters, addFilter, removeFilter, updateFilter }
}
