Daily Wealth Alignment

import { useState, useEffect, useCallback, useRef } from 'react'; import { type UserData, loadUserData, saveUserData, createNewUser, getLevelInfo, isCompletedToday, completeSession, getStreakStatus, getToday, getSoundLabel, getTimerLabel, clearAllData, } from './lib/storage'; import { getAffirmationsForLevel } from './lib/affirmations'; import { soundEngine, type SoundMode } from './lib/soundEngine'; import { getRandomMessage, welcomeBackMessages, completionMessages } from './lib/galaxyMessages'; import { generateRitualReport } from './lib/pdfGenerator'; import TimerRing from './components/TimerRing'; import Particles from './components/Particles'; import LevelUpOverlay from './components/LevelUpOverlay'; import StreakProgress from './components/StreakProgress'; import GalaxyGuide from './components/GalaxyGuide'; import SoundVisualizer from './components/SoundVisualizer'; import IntroOverlay from './components/IntroOverlay'; import InsightsSection from './components/InsightsSection'; import TimerSelector from './components/TimerSelector'; import SaveBookmarkModal from './components/SaveBookmarkModal'; type AppScreen = 'loading' | 'intro' | 'dashboard' | 'ritual' | 'complete'; export default function App() { const [userData, setUserData] = useState(null); const [screen, setScreen] = useState('loading'); const [timeLeft, setTimeLeft] = useState(180); const [currentAffirmation, setCurrentAffirmation] = useState(0); const [affirmationFade, setAffirmationFade] = useState(true); const [showLevelUp, setShowLevelUp] = useState(false); const [newLevelNum, setNewLevelNum] = useState(1); const [completedToday, setCompletedToday] = useState(false); const [volume, setVolume] = useState(0.4); const [analyserNode, setAnalyserNode] = useState(null); const [welcomeMsg, setWelcomeMsg] = useState(''); const [showInsights, setShowInsights] = useState(false); const [showBookmark, setShowBookmark] = useState(false); const [screenFading, setScreenFading] = useState(false); const [showSoundDropdown, setShowSoundDropdown] = useState(false); const [showResetConfirm, setShowResetConfirm] = useState(false); const [audioError, setAudioError] = useState(false); const [featureToast, setFeatureToast] = useState(''); const timerRef = useRef | null>(null); const affirmationTimerRef = useRef | null>(null); const screenHistory = useRef([]); const soundDropdownRef = useRef(null); // Smooth screen transition const transitionTo = useCallback((nextScreen: AppScreen, saveHistory = true) => { if (saveHistory && screen !== 'loading') { screenHistory.current.push(screen); } setScreenFading(true); setTimeout(() => { setScreen(nextScreen); setScreenFading(false); }, 350); }, [screen]); // Initialize user data useEffect(() => { const timer = setTimeout(() => { try { const saved = loadUserData(); if (saved && saved.userName) { saved.lastVisit = getToday(); saveUserData(saved); setUserData(saved); setCompletedToday(isCompletedToday(saved)); setWelcomeMsg(getRandomMessage(welcomeBackMessages, saved.userName)); setScreen('dashboard'); } else { setScreen('intro'); } } catch { // If localStorage fails, start fresh setScreen('intro'); } }, 1200); return () => clearTimeout(timer); }, []); // Close sound dropdown on outside click useEffect(() => { const handler = (e: MouseEvent) => { if (soundDropdownRef.current && !soundDropdownRef.current.contains(e.target as Node)) { setShowSoundDropdown(false); } }; document.addEventListener('mousedown', handler); return () => document.removeEventListener('mousedown', handler); }, []); // Get affirmations based on level const affirmations = userData ? getAffirmationsForLevel(userData.level) : getAffirmationsForLevel(1); // Affirmation rotation during ritual useEffect(() => { if (screen === 'ritual') { affirmationTimerRef.current = setInterval(() => { setAffirmationFade(false); setTimeout(() => { setCurrentAffirmation((prev) => (prev + 1) % affirmations.length); setAffirmationFade(true); }, 600); }, 6000); } return () => { if (affirmationTimerRef.current) clearInterval(affirmationTimerRef.current); }; }, [screen, affirmations.length]); // Timer logic useEffect(() => { if (screen === 'ritual' && timeLeft > 0) { timerRef.current = setInterval(() => { setTimeLeft((prev) => { if (prev <= 1) { clearInterval(timerRef.current!); handleRitualComplete(); return 0; } return prev - 1; }); }, 1000); } return () => { if (timerRef.current) clearInterval(timerRef.current); }; // eslint-disable-next-line react-hooks/exhaustive-deps }, [screen]); const handleRitualComplete = useCallback(() => { if (!userData) return; // Stop sound soundEngine.stop(); setAnalyserNode(null); const { newData, leveledUp, newLevel } = completeSession(userData); setUserData(newData); setCompletedToday(true); setScreenFading(true); setTimeout(() => { setScreen('complete'); setScreenFading(false); }, 500); if (leveledUp) { setNewLevelNum(newLevel); setTimeout(() => setShowLevelUp(true), 1200); } }, [userData]); const handleIntroComplete = (name: string) => { // Default sound is 'binaural' β€” user can change during ritual const newUser = createNewUser(name, 'binaural'); saveUserData(newUser); setUserData(newUser); transitionTo('dashboard', false); }; const ritualDuration = userData?.selectedTimer || 180; const startRitual = () => { if (completedToday || !userData) return; setTimeLeft(ritualDuration); setCurrentAffirmation(0); setAffirmationFade(true); setAudioError(false); transitionTo('ritual'); // Start sound after screen transition setTimeout(() => { soundEngine.volume = volume; soundEngine.start(userData.selectedSound as SoundMode); // Check if audio failed setTimeout(() => { if (soundEngine.audioFailed) { setAudioError(true); } else { setAnalyserNode(soundEngine.getAnalyser()); } }, 300); }, 400); }; const handleVolumeChange = (v: number) => { setVolume(v); soundEngine.volume = v; }; const handleSoundChange = (sound: string) => { if (!userData) return; const wasPlaying = soundEngine.getIsPlaying(); // If sound is playing, stop it and restart with new sound if (wasPlaying) { soundEngine.forceStop(); // Small delay before starting new sound setTimeout(() => { soundEngine.volume = volume; soundEngine.start(sound as SoundMode); setTimeout(() => { if (!soundEngine.audioFailed) { setAnalyserNode(soundEngine.getAnalyser()); } }, 300); }, 200); } const updated = { ...userData, selectedSound: sound }; setUserData(updated); saveUserData(updated); setShowSoundDropdown(false); }; const handleTimerChange = (seconds: number) => { if (!userData) return; const updated = { ...userData, selectedTimer: seconds }; setUserData(updated); saveUserData(updated); }; const handleBackFromDashboard = () => { transitionTo('intro', false); }; const handleDownloadReport = () => { if (!userData) return; generateRitualReport(userData); showFeatureToast('✨ Report downloaded successfully'); }; // === GLOBAL CONTROL BAR HANDLERS === const handleGlobalStop = () => { soundEngine.forceStop(); setAnalyserNode(null); if (screen === 'ritual') { // Stop the timer if (timerRef.current) clearInterval(timerRef.current); if (affirmationTimerRef.current) clearInterval(affirmationTimerRef.current); // Go back to dashboard transitionTo('dashboard', false); } }; const handleGlobalBack = () => { // Stop any audio soundEngine.forceStop(); setAnalyserNode(null); if (timerRef.current) clearInterval(timerRef.current); if (affirmationTimerRef.current) clearInterval(affirmationTimerRef.current); if (screenHistory.current.length > 0) { const prev = screenHistory.current.pop()!; setScreenFading(true); setTimeout(() => { setScreen(prev); setScreenFading(false); }, 350); } else { transitionTo('dashboard', false); } }; const handleGlobalReset = () => { setShowResetConfirm(true); }; const confirmReset = () => { soundEngine.forceStop(); setAnalyserNode(null); if (timerRef.current) clearInterval(timerRef.current); if (affirmationTimerRef.current) clearInterval(affirmationTimerRef.current); clearAllData(); setUserData(null); setCompletedToday(false); setShowResetConfirm(false); setShowInsights(false); screenHistory.current = []; transitionTo('intro', false); }; const showFeatureToast = useCallback((msg: string) => { setFeatureToast(msg); setTimeout(() => setFeatureToast(''), 2500); }, []); const handleRetryAudio = () => { if (!userData) return; setAudioError(false); soundEngine.volume = volume; soundEngine.start(userData.selectedSound as SoundMode); setTimeout(() => { if (soundEngine.audioFailed) { setAudioError(true); } else { setAnalyserNode(soundEngine.getAnalyser()); } }, 300); }; // Loading screen if (screen === 'loading') { return (

Preparing your alignment…

); } // Intro screen (new user) if (screen === 'intro') { return ; } if (!userData) return null; const levelInfo = getLevelInfo(userData.level); const streakStatus = getStreakStatus(userData); const journeyDay = userData.totalDays + (completedToday ? 0 : 1); return (
{/* Background */}
{/* Particles */} {/* Galaxy Guide during ritual */} {/* Level Up Overlay */} {showLevelUp && ( setShowLevelUp(false)} /> )} {/* Save/Bookmark Modal */} setShowBookmark(false)} /> {/* Reset Confirmation Modal */} {showResetConfirm && (
setShowResetConfirm(false)} >
e.stopPropagation()} >
⚠️

Reset Your Journey?

Are you sure you want to reset your journey?
This will erase all your progress, streak, and level data.

)} {/* Feature Toast */} {featureToast && (
{featureToast}
)} {/* Main Content β€” with fade transition */}
{/* ================================ */} {/* DASHBOARD SCREEN */} {/* ================================ */} {screen === 'dashboard' && (
{/* Background ambient particles */} {/* Back button (to change name/sound) */} {/* Header */}
✨

Daily Wealth Alignment

Guided by Galaxy

{/* Welcome message */}

{welcomeMsg || `Welcome, ${userData.userName} ✨`}

Day {journeyDay} of your journey

{streakStatus === 'at_risk' && !completedToday && (

⚠️ Complete today's ritual to keep your streak alive!

)} {streakStatus === 'broken' && !completedToday && userData.totalDays > 0 && (

Your previous streak ended. Start a new one today!

)}
{/* Stats cards */}
{/* Level */}
{levelInfo.icon}
Level {userData.level}
{levelInfo.name}
{/* Streak */}
πŸ”₯
{userData.streak} Day{userData.streak !== 1 ? 's' : ''}
Streak
{/* Sound β€” now shows current selection */}
{userData.selectedSound === 'binaural' ? '🎧' : userData.selectedSound === 'calm' ? '🌊' : '⚑'}
{getSoundLabel(userData.selectedSound)}
Sound
{/* Level Progress */}
{/* ======================================= */} {/* START BUTTON β€” BELOW Progress Bar */} {/* ======================================= */}
{completedToday ? (
βœ…

Today's Ritual Complete

Return tomorrow to continue your streak, {userData.userName}

πŸ”₯ {userData.streak}-day streak
) : (
)}
{/* Timer Selector */}
{/* Step Navigation β€” Dashboard */}
{!completedToday ? ( ) : ( )}
{/* Secondary actions row */}
Β· Β·
{/* Insights Section */} {showInsights && (
)} {/* Level Map */}
YOUR PATH
{[1, 2, 3, 4].map((lvl) => { const info = getLevelInfo(lvl); const isActive = lvl === userData.level; const isCompleted = lvl < userData.level; return (
{isCompleted ? 'βœ“' : info.icon}
Level {info.level}: {info.name} {isActive && ( Current )}
{info.dayRange} Β· {info.subtitle}
); })}
)} {/* ================================ */} {/* RITUAL SCREEN */} {/* ================================ */} {screen === 'ritual' && (
{/* Level badge */}
{levelInfo.icon} Level {userData.level} β€” {levelInfo.name}

{getTimerLabel(ritualDuration)} Session Β· {getSoundLabel(userData.selectedSound)}

{/* Timer */}
{/* Sound Visualizer */}
{/* Audio error / retry */} {audioError && (
)} {/* Volume Control */}
πŸ”Š handleVolumeChange(Number(e.target.value) / 100)} className="volume-slider" /> {Math.round(volume * 100)}%
{/* ======================================= */} {/* SOUND SELECTION DROPDOWN β€” Session Control */} {/* ======================================= */}
Select Your Sound
{/* Dropdown menu */} {showSoundDropdown && (
{[ { id: 'binaural', label: 'Focus (Binaural)', desc: 'Om frequency · 136.1Hz · Alpha waves', icon: '🎧' }, { id: 'calm', label: 'Calm (Brown Noise)', desc: 'Warm bass-rich brown noise · Theta waves', icon: '🌊' }, { id: 'power', label: 'Power (Enhanced Tone)', desc: 'Energizing beta waves · Focused presence', icon: '⚑' }, ].map((s) => ( ))}
)}
{/* Headphones notice */}
🎧 Use headphones for best experience
{/* Guided instruction */}

Read this silently in your mind or softly aloud…

{/* Affirmation */}

"{affirmations[currentAffirmation]}"

{/* Personal touch */}

Stay present, {userData.userName}…

{/* Breathing guide */}

Breathe Β· Focus Β· Align

{/* Step Navigation β€” Ritual (back only) */}
)} {/* ================================ */} {/* COMPLETE SCREEN */} {/* ================================ */} {screen === 'complete' && (
✨

Beautiful work, {userData.userName}

{getRandomMessage(completionMessages, userData.userName)}

You are strengthening your alignment daily

{/* Results card */}
Current Streak πŸ”₯ {userData.streak} Day{userData.streak !== 1 ? 's' : ''}
Level {levelInfo.icon} {levelInfo.name}
Total Sessions {userData.totalDays}
Duration {getTimerLabel(ritualDuration)}
Sound Used {getSoundLabel(userData.selectedSound)}
{/* Progress */}
{/* Galaxy message */}
✨

{userData.streak >= 15 ? `"${userData.userName}, you have achieved Wealth Consciousness. Your abundance is limitless."` : userData.streak >= 8 ? `"The flow of abundance moves through you, ${userData.userName}. Keep going."` : userData.streak >= 4 ? `"Your energy is aligning, ${userData.userName}. Powerful shifts are happening."` : `"Every journey begins with the first step, ${userData.userName}. You have begun."`}

β€” Galaxy

{/* Primary action */} {/* Secondary actions */}
Β·
{/* Step Navigation β€” Complete */}
)} {/* Footer */}
{/* ============================================ */} {/* GLOBAL CONTROL BAR β€” Fixed bottom */} {/* ============================================ */} {(screen === 'dashboard' || screen === 'ritual' || screen === 'complete') && (
)}
); }