const FALLBACK = {
  title: 'A Day in Your Journey',
  summary: 'Today you showed up. That alone matters more than you think.',
  quote: 'Small steps still move you forward.',
};

export default function safeParseJournal(raw) {
  if (!raw || typeof raw !== 'string') return { ...FALLBACK };

  try {
    let cleaned = raw.trim();
    cleaned = cleaned.replace(/```json\s*/gi, '').replace(/```\s*/gi, '');

    const start = cleaned.indexOf('{');
    const end = cleaned.lastIndexOf('}');
    if (start === -1 || end === -1) return { ...FALLBACK };

    const parsed = JSON.parse(cleaned.slice(start, end + 1));

    return {
      title: (typeof parsed.title === 'string' && parsed.title.trim()) || FALLBACK.title,
      summary: (typeof parsed.summary === 'string' && parsed.summary.trim()) || FALLBACK.summary,
      quote: (typeof parsed.quote === 'string' && parsed.quote.trim()) || FALLBACK.quote,
    };
  } catch (_) {
    return { ...FALLBACK };
  }
}

export { FALLBACK };
