import { DEFAULT_VOICE } from '../data/voices';

const KEY = 'jbot_settings';

export const DEFAULT_SETTINGS = {
  robotName:        'JBOT',
  robotPersonality: '你是一个友好、简洁、偶尔幽默的AI机器人助手。回复控制在80字以内。',
  language:         'auto',        // 'auto' | 'zh-CN' | 'en-US'
  voiceId:          DEFAULT_VOICE,
  customVoiceId:    '',            // overrides voiceId if non-empty
  responseMaxWords: 80,
  switchIntervalMs: 10000,         // micro-expression auto-rotate interval
};

export function getSettings() {
  try {
    const saved = JSON.parse(localStorage.getItem(KEY) || '{}');
    return { ...DEFAULT_SETTINGS, ...saved };
  } catch {
    return { ...DEFAULT_SETTINGS };
  }
}

export function saveSettings(patch) {
  const current = getSettings();
  const updated = { ...current, ...patch };
  localStorage.setItem(KEY, JSON.stringify(updated));
  return updated;
}

export function resetSettings() {
  localStorage.removeItem(KEY);
  return { ...DEFAULT_SETTINGS };
}

// Returns the effective voice ID (custom takes priority)
export function getEffectiveVoice(settings = null) {
  const s = settings || getSettings();
  return s.customVoiceId?.trim() || s.voiceId || DEFAULT_VOICE;
}
