import { ref, watch } from 'vue'

/** Available page size options */
export const PAGE_SIZE_OPTIONS = [10, 20, 50, 100]

/** Default page size */
const DEFAULT_PAGE_SIZE = 20

/**
 * Composable for persisted per-table page size.
 *
 * @param {string} storageKey - localStorage key (e.g. 'mv_member_pagesize')
 * @returns {{ pageSize: import('vue').Ref<number>, setPageSize: (n: number) => void }}
 */
export function usePageSize(storageKey) {
	function load() {
		try {
			const stored = localStorage.getItem(storageKey)
			if (stored) {
				const val = parseInt(stored, 10)
				if (PAGE_SIZE_OPTIONS.includes(val)) {
					return val
				}
			}
		} catch {
			// ignore
		}
		return DEFAULT_PAGE_SIZE
	}

	const pageSize = ref(load())

	watch(pageSize, (val) => {
		localStorage.setItem(storageKey, String(val))
	})

	function setPageSize(n) {
		if (PAGE_SIZE_OPTIONS.includes(n)) {
			pageSize.value = n
		}
	}

	return { pageSize, setPageSize }
}
