import { type CompanionMessage, type CompanionSettings, type DialogueContext, type PrincessEmotion, type TowerProgress, DEFAULT_COMPANION_SETTINGS, PRINCESS_EMOTIONS, SCRIPTED_DIALOGUES, TOWER_CHAPTERS, } from '../data/companionData'; import { supabase } from '../firebaseClient'; const SETTINGS_KEY = 'companion_settings'; const PROGRESS_KEY = 'tower_progress'; export function getCompanionSettings(): CompanionSettings { try { const saved = localStorage.getItem(SETTINGS_KEY); if (!saved) return DEFAULT_COMPANION_SETTINGS; return { ...DEFAULT_COMPANION_SETTINGS, ...JSON.parse(saved) }; } catch { return DEFAULT_COMPANION_SETTINGS; } } export function saveCompanionSettings(settings: CompanionSettings): void { try { localStorage.setItem(SETTINGS_KEY, JSON.stringify(settings)); } catch (err) { console.error('Failed to save companion settings:', err); } } export function getTowerProgress(): TowerProgress { try { const saved = localStorage.getItem(PROGRESS_KEY); if (!saved) { return { currentFloor: 0, maxFloor: 150, totalSolved: 0, unlockedMilestones: [0], }; } return JSON.parse(saved); } catch { return { currentFloor: 0, maxFloor: 150, totalSolved: 0, unlockedMilestones: [0], }; } } export function saveTowerProgress(progress: TowerProgress): void { try { localStorage.setItem(PROGRESS_KEY, JSON.stringify(progress)); } catch (err) { console.error('Failed to save tower progress:', err); } } export function resetTowerProgress(): TowerProgress { const initial: TowerProgress = { currentFloor: 0, maxFloor: 150, totalSolved: 0, unlockedMilestones: [0], }; saveTowerProgress(initial); return initial; } export async function syncWithBackendJourneyProgress(): Promise { try { const { data: { session } } = await supabase.auth.getSession(); const token = session ? session.access_token : 'sandbox'; const headers = { Authorization: `Bearer ${token}` }; const res = await fetch(`${import.meta.env.VITE_API_BASE_URL}/api/journey-progress`, { headers }); if (res.ok) { const completedList: number[] = await res.json(); const count = Array.isArray(completedList) ? completedList.length : 0; const newFloor = Math.min(150, count); // Determine milestones const milestones = [30, 60, 90, 120, 150]; const unlocked = [0]; milestones.forEach((m) => { if (newFloor >= m) unlocked.push(m); }); const updated: TowerProgress = { currentFloor: newFloor, maxFloor: 150, totalSolved: count, unlockedMilestones: unlocked, }; saveTowerProgress(updated); return updated; } } catch (err) { console.error('Failed to sync companion progress with backend journey:', err); } return getTowerProgress(); } export function advanceTowerProgress(isCorrect: boolean = true): { progress: TowerProgress; leveledUp: boolean; newMilestone?: number; } { const current = getTowerProgress(); const newSolved = isCorrect ? current.totalSolved + 1 : current.totalSolved; // Journey calculation: each correct review advances 1 league towards the Tower of the Elixir (up to 150) let newFloor = current.currentFloor; let leveledUp = false; let newMilestone: number | undefined = undefined; if (isCorrect && current.currentFloor < current.maxFloor) { newFloor = Math.min(current.maxFloor, current.currentFloor + 1); leveledUp = true; // Check milestones: 30, 60, 90, 120, 150 const milestones = [30, 60, 90, 120, 150]; if (milestones.includes(newFloor) && !current.unlockedMilestones.includes(newFloor)) { current.unlockedMilestones.push(newFloor); newMilestone = newFloor; } } const updated: TowerProgress = { ...current, currentFloor: newFloor, totalSolved: newSolved, unlockedMilestones: current.unlockedMilestones, }; saveTowerProgress(updated); return { progress: updated, leveledUp, newMilestone }; } export function getCurrentChapter(floor: number) { const chapter = TOWER_CHAPTERS.find( (c) => floor >= c.floorRange[0] && floor <= c.floorRange[1] ); return chapter || TOWER_CHAPTERS[0]; } export function getRandomScriptedDialogue( context: DialogueContext, floorRequirement?: number ): CompanionMessage { const pool = SCRIPTED_DIALOGUES[context] || SCRIPTED_DIALOGUES.idle_motivation; if (floorRequirement && context === 'tower_milestone') { const specific = pool.find((m) => m.floorRequirement === floorRequirement); if (specific) return specific; } const randomIndex = Math.floor(Math.random() * pool.length); return pool[randomIndex] || pool[0]; } export interface CompanionAIRequest { userMessage?: string; context: DialogueContext; currentFloor: number; streakDays?: number; problemTitle?: string; problemPattern?: string; } export interface CompanionAIResponse { text: string; emotion: PrincessEmotion; provider_used?: string; } export async function askCompanionAI( req: CompanionAIRequest ): Promise { const settings = getCompanionSettings(); const customKey = localStorage.getItem('algospaced_custom_api_key') || localStorage.getItem('sandbox_gemini_api_key') || ''; const customProvider = localStorage.getItem('algospaced_custom_ai_provider') || 'default'; try { const { data: { session }, } = await supabase.auth.getSession(); const token = session?.access_token || 'sandbox'; const headers: Record = { 'Content-Type': 'application/json', Authorization: `Bearer ${token}`, }; if (customKey.trim() && customProvider !== 'default') { headers['x-custom-api-key'] = customKey.trim(); headers['x-gemini-api-key'] = customKey.trim(); headers['x-ai-provider'] = customProvider; } const payload = { princess_name: settings.name, princess_backstory: settings.backstory, user_message: req.userMessage || '', context: req.context, current_floor: req.currentFloor, streak_days: req.streakDays || 0, problem_title: req.problemTitle || '', problem_pattern: req.problemPattern || '', }; const res = await fetch(`${import.meta.env.VITE_API_BASE_URL || ''}/api/companion/chat`, { method: 'POST', headers, body: JSON.stringify(payload), }); if (res.ok) { const data = await res.json(); if (data.text && data.emotion && PRINCESS_EMOTIONS[data.emotion as PrincessEmotion]) { return { text: data.text, emotion: data.emotion as PrincessEmotion, provider_used: data.provider_used, }; } } } catch (err) { console.warn('Companion AI endpoint unavailable, using offline RPG script:', err); } // Graceful fallback to rich offline scripted library const fallback = getRandomScriptedDialogue(req.context); return { text: fallback.text, emotion: fallback.emotion, provider_used: 'Offline RPG Script', }; } export function triggerCompanionEvent(event: { text: string; emotion: PrincessEmotion; title?: string; context?: string; autoCloseDelay?: number; }): void { if (typeof window === 'undefined') return; const settings = getCompanionSettings(); if (!settings.enabled || !settings.autoPopupEnabled) return; window.dispatchEvent( new CustomEvent('companion:dialogue', { detail: event, }) ); } export async function triggerReviewResultEvent( rating: 'Correct' | 'Mixed' | 'Incorrect', problemTitle?: string, problemPattern?: string ): Promise { const isCorrect = rating === 'Correct'; const { progress, newMilestone } = advanceTowerProgress(isCorrect); if (newMilestone) { const milestoneMsg = getRandomScriptedDialogue('tower_milestone', newMilestone); triggerCompanionEvent({ text: milestoneMsg.text, emotion: milestoneMsg.emotion, title: `🏰 Journey Landmark: League ${newMilestone}!`, context: 'tower_milestone', autoCloseDelay: 10000, }); return; } const context = isCorrect ? 'problem_correct' : 'problem_incorrect'; // Try AI generation if configured, otherwise instant fallback try { const aiResp = await askCompanionAI({ context, currentFloor: progress.currentFloor, problemTitle, problemPattern, userMessage: `I just graded my review as ${rating} for the waypoint: ${problemTitle || 'our latest trial on the road'}.`, }); triggerCompanionEvent({ text: aiResp.text, emotion: aiResp.emotion, title: isCorrect ? '✨ Trail Victory!' : '🛡️ Keep Striving!', context, autoCloseDelay: 8000, }); } catch { const script = getRandomScriptedDialogue(context); triggerCompanionEvent({ text: script.text, emotion: script.emotion, title: isCorrect ? '✨ Trail Victory!' : '🛡️ Keep Striving!', context, autoCloseDelay: 8000, }); } }