/**
 * 个人偏好：只存在本地浏览器，不引入账号系统。
 */

const STORAGE_KEY = 'charger_preferences';
const VALID_CHARGER_TYPES = new Set(['all', 'AC', 'DC']);
const VALID_VENDORS = new Set(['all', 'nio', 'gongniu']);

export function normalizePreferences(raw = {}) {
  const chargerType = VALID_CHARGER_TYPES.has(raw.chargerType) ? raw.chargerType : 'all';
  const vendor = VALID_VENDORS.has(raw.vendor) ? raw.vendor : 'all';

  return {
    email: String(raw.email || '').trim().toLowerCase(),
    feishuName: String(raw.feishuName || '').trim(),
    chargerType,
    vendor,
  };
}

export function loadPreferences() {
  try {
    const saved = localStorage.getItem(STORAGE_KEY);
    if (!saved) return normalizePreferences();
    return normalizePreferences(JSON.parse(saved));
  } catch (e) {
    console.warn('[偏好] 加载失败', e);
    return normalizePreferences();
  }
}

export function savePreferences(preferences) {
  const normalized = normalizePreferences(preferences);
  localStorage.setItem(STORAGE_KEY, JSON.stringify(normalized));
  return normalized;
}
