import { computed } from "vue";
import { useState, useRoute } from "#imports";
import { useLocalStorageModel } from "./localStorageModel.js";
function safeRoutePath() {
  try {
    const route = useRoute();
    return route?.path || "";
  } catch {
    return "";
  }
}
const DEFAULT_TTL_SECONDS = 90 * 24 * 60 * 60;
export function usePerPagePreference(perPage, options = {}) {
  const authState = useState("authentication", () => ({}));
  const username = computed(() => {
    const profile = authState.value?.userProfile;
    return profile?.username?.trim() || "anon";
  });
  const routePath = computed(() => safeRoutePath());
  const persistKey = computed(() => {
    const key = options.storageKey?.trim();
    if (!key || options.enabled === false) return "";
    return `${username.value}:${routePath.value}:${key}`;
  });
  return useLocalStorageModel(
    perPage,
    {
      persist: !!persistKey.value,
      persistKey: persistKey.value,
      persistPrefix: "nuxt-commons:perPage",
      persistEncrypt: options.encrypt ?? true,
      persistSecret: options.secret,
      persistTtl: options.ttlSeconds ?? DEFAULT_TTL_SECONDS,
      persistDebounce: options.debounceMs ?? 200,
      persistClearOnEmpty: false,
      // A stored preference should win over the component's prop default
      // (which often runs `immediate: true` on mount and populates the ref
      // before onMounted hydrates).
      persistAlwaysHydrate: true
    },
    {
      isEmpty: (v) => v === void 0 || v === null || v === "",
      // useLocalStorageModel hydrates whenever stored !== undefined, but
      // localstorage-slim returns `null` for missing keys. Without this filter
      // a first-time render with no stored entry would clobber the prop default
      // (e.g. `itemsPerPage: 12`) with `null`.
      deserializer: (raw) => {
        if (raw === null || raw === void 0) {
          throw new Error("skip hydration: no stored preference");
        }
        return raw;
      }
    }
  );
}
