import { ref, computed, watch } from 'vue'

/**
 * Composable for persisted column visibility.
 *
 * @param {string} storageKey - localStorage key
 * @param {Array} allColumns - Column definitions with { key, label, ... }
 * @param {string[]} defaultVisible - Keys visible by default
 * @returns {{ visibleKeys, visibleColumns, setVisibleKeys }}
 */
export function useColumnVisibility(storageKey, allColumns, defaultVisible) {
	function load() {
		try {
			const stored = localStorage.getItem(storageKey)
			if (stored) {
				const parsed = JSON.parse(stored)
				if (Array.isArray(parsed) && parsed.length > 0) {
					return parsed
				}
			}
		} catch {
			// ignore
		}
		return [...defaultVisible]
	}

	const visibleKeys = ref(load())

	const visibleColumns = computed(() =>
		allColumns.filter(col => visibleKeys.value.includes(col.key)),
	)

	watch(visibleKeys, (val) => {
		localStorage.setItem(storageKey, JSON.stringify(val))
	}, { deep: true })

	function setVisibleKeys(newKeys) {
		visibleKeys.value = newKeys
	}

	return { visibleKeys, visibleColumns, setVisibleKeys }
}
