const PREFIX = 'caseorion-pref';

function storageKey(userId, suffix) {
  return `${PREFIX}-${userId}-${suffix}`;
}

export function loadPref(userId, suffix, fallback = null) {
  if (!userId || typeof window === 'undefined') return fallback;
  try {
    const raw = localStorage.getItem(storageKey(userId, suffix));
    return raw ?? fallback;
  } catch {
    return fallback;
  }
}

export function savePref(userId, suffix, value) {
  if (!userId || typeof window === 'undefined') return;
  try {
    localStorage.setItem(storageKey(userId, suffix), String(value));
  } catch {
    /* ignore quota / private mode */
  }
}

export function loadInventorySort(userId) {
  const v = loadPref(userId, 'inventory-sort');
  return v === 'value' || v === 'recent' ? v : null;
}

export function saveInventorySort(userId, sort) {
  if (sort === 'value' || sort === 'recent') {
    savePref(userId, 'inventory-sort', sort);
  }
}

export function loadCaseOpenQty(userId, caseId) {
  const id = Number(caseId);
  if (!Number.isFinite(id)) return null;
  const raw = loadPref(userId, `case-qty-${id}`);
  if (raw == null) return null;
  const n = Number(raw);
  return Number.isFinite(n) && n >= 1 ? Math.floor(n) : null;
}

export function saveCaseOpenQty(userId, caseId, qty) {
  const id = Number(caseId);
  if (!Number.isFinite(id)) return;
  savePref(userId, `case-qty-${id}`, Math.floor(qty));
}

/** Pick best allowed open qty from saved preference. */
export function resolveOpenQty(saved, openOptions, maxAffordable) {
  const affordable = Math.max(1, maxAffordable || 1);
  const allowed = openOptions.filter((n) => n <= affordable);
  if (!allowed.length) return 1;
  if (saved == null) {
    return allowed.includes(1) ? 1 : allowed[0];
  }
  if (allowed.includes(saved)) return saved;
  const below = allowed.filter((n) => n <= saved);
  return below.length ? below[below.length - 1] : allowed[0];
}
