import React, { useState, useEffect } from 'react'; import { usePredictiveCaching } from '../hooks/usePredictiveCaching'; import { MediaItem } from '../types/mediaTypes'; import './PredictiveCachingDemo.css'; interface PredictiveCachingDemoProps { className?: string; } const PredictiveCachingDemo: React.FC = ({ className }) => { const { state, recordListeningEvent, getPredictions, refreshPredictions, clearAllData } = usePredictiveCaching(); const [currentSong, setCurrentSong] = useState(null); const [simulationRunning, setSimulationRunning] = useState(false); const [predictions, setPredictions] = useState(state.predictions); // Mock songs for demonstration const mockSongs: MediaItem[] = [ { id: 'song1', title: 'Morning Vibes', artist: 'Chill Artist', albumId: 'album1', artistId: 'artist1', duration: 180, type: 'song' }, { id: 'song2', title: 'Afternoon Energy', artist: 'Pop Artist', albumId: 'album2', artistId: 'artist2', duration: 200, type: 'song' }, { id: 'song3', title: 'Evening Relaxation', artist: 'Ambient Artist', albumId: 'album3', artistId: 'artist3', duration: 240, type: 'song' }, { id: 'song4', title: 'Night Beats', artist: 'Electronic Artist', albumId: 'album4', artistId: 'artist4', duration: 190, type: 'song' }, { id: 'song5', title: 'Workout Pump', artist: 'Rock Artist', albumId: 'album1', artistId: 'artist1', duration: 160, type: 'song' }, { id: 'song6', title: 'Study Focus', artist: 'Instrumental Artist', albumId: 'album5', artistId: 'artist5', duration: 300, type: 'song' }, { id: 'song7', title: 'Party Time', artist: 'Dance Artist', albumId: 'album6', artistId: 'artist6', duration: 180, type: 'song' }, { id: 'song8', title: 'Commute Companion', artist: 'Podcast Artist', albumId: 'album7', artistId: 'artist7', duration: 220, type: 'song' } ]; useEffect(() => { setPredictions(getPredictions(currentSong, mockSongs)); }, [state.analytics, currentSong, getPredictions]); const simulateListening = (song: MediaItem, completed: boolean = true) => { const duration = completed ? song.duration : Math.random() * song.duration * 0.5; const context = ['playlist', 'album', 'shuffle', 'search'][Math.floor(Math.random() * 4)] as any; recordListeningEvent( song.id, duration, song.duration, !completed, context, song.albumId, song.artistId ); setCurrentSong(song); }; const runSimulation = async () => { setSimulationRunning(true); // Simulate different listening patterns const patterns = [ // Morning routine (7-9 AM) { songs: ['song1', 'song6'], time: 8, completionRate: 0.9 }, // Commute (8-9 AM, 5-6 PM) { songs: ['song8', 'song2'], time: 8.5, completionRate: 0.7 }, // Work focus (9 AM - 5 PM) { songs: ['song6', 'song3'], time: 11, completionRate: 0.8 }, // Workout (6-7 PM) { songs: ['song5', 'song7'], time: 18, completionRate: 0.95 }, // Evening relaxation (8-10 PM) { songs: ['song3', 'song4'], time: 20, completionRate: 0.85 }, // Weekend party (Friday/Saturday night) { songs: ['song7', 'song4', 'song2'], time: 22, completionRate: 0.9 } ]; for (let day = 0; day < 7; day++) { for (const pattern of patterns) { for (const songId of pattern.songs) { const song = mockSongs.find(s => s.id === songId); if (song) { const completed = Math.random() < pattern.completionRate; simulateListening(song, completed); // Small delay to show progression await new Promise(resolve => setTimeout(resolve, 100)); } } } } setSimulationRunning(false); refreshPredictions(); }; const getReasonColor = (reason: string) => { switch (reason) { case 'pattern': return '#4CAF50'; case 'album': return '#2196F3'; case 'artist': return '#FF9800'; case 'time': return '#9C27B0'; case 'hybrid': return '#607D8B'; default: return '#757575'; } }; const getTimeSlotName = () => { const hour = new Date().getHours(); if (hour >= 6 && hour < 12) return 'Morning'; if (hour >= 12 && hour < 17) return 'Afternoon'; if (hour >= 17 && hour < 22) return 'Evening'; return 'Night'; }; return (

🧠 Predictive Caching System

AI-powered music caching based on listening patterns

📊 Analytics

Listening Patterns: {state.analytics.totalPatterns}
Album Predictions: {state.analytics.albumPredictions}
Artist Predictions: {state.analytics.artistPredictions}
Time Predictions: {state.analytics.timeSlotPredictions}
Avg Confidence: {(state.analytics.averageConfidence * 100).toFixed(1)}%
Current Time Slot: {getTimeSlotName()}

🎵 Mock Songs (Click to Simulate Listening)

{mockSongs.map(song => (
simulateListening(song)} >
{song.title}
{song.artist}
{Math.floor(song.duration / 60)}:{(song.duration % 60).toString().padStart(2, '0')}
))}

🔮 Predictive Cache Recommendations ({predictions.length})

{predictions.length === 0 ? (

No predictions yet. Try the simulation or manually play some songs!

) : (
{predictions.slice(0, 10).map((prediction, index) => { const song = mockSongs.find(s => s.id === prediction.songId); return (
#{index + 1}
{song ? song.title : `Song ${prediction.songId}`}
{prediction.reason} Priority: {prediction.priority} Confidence: {(prediction.confidence * 100).toFixed(1)}%
{prediction.estimatedPlayTime > Date.now() ? `ETA: ${Math.round((prediction.estimatedPlayTime - Date.now()) / 60000)}m` : 'Ready now' }
); })}
)}

📈 Algorithm Insights

🎯 Pattern Analysis

Tracks play frequency, completion rates, and skip patterns to predict future listening behavior.

💿 Album Completion

Predicts when you'll listen to remaining songs in an album based on current listening patterns.

🎤 Artist Exploration

Suggests similar artists and songs when you show interest in a particular artist.

⏰ Time-Based Caching

Learns your daily music preferences and pre-caches songs for different time periods.

{state.isAnalyzing && (
🧠

Analyzing listening patterns...

)}
); }; export default PredictiveCachingDemo;