Modern Apps git

← Modern-Apps.git

games: add games hub

Commit
178dff1588f1007f615a5e3d432d5dc02866f0e8
Author
Vayun Mathur <[email protected]>
When
2026-07-23 21:54 UTC (4 months ago)
Parents
10e6ab4

Diff

games/alchemist/build.gradle.kts
diff --git a/games/alchemist/build.gradle.kts b/games/alchemist/build.gradle.ktsindex 1ede2e7fce..97155097dc 100644--- a/games/alchemist/build.gradle.kts+++ b/games/alchemist/build.gradle.kts@@ -14,4 +14,5 @@ android { }  dependencies {+    implementation(project(":sdk:games")) }
games/chess/build.gradle.kts
diff --git a/games/chess/build.gradle.kts b/games/chess/build.gradle.ktsindex ebd2540e51..4f44cfcbe1 100644--- a/games/chess/build.gradle.kts+++ b/games/chess/build.gradle.kts@@ -12,16 +12,12 @@ android {         applicationId = "com.vayunmathur.games.chess"     }     androidResources {-        // Store the Stockfish NNUE uncompressed so it can be read in place from-        // the APK via AssetManager.openFd() (fd + offset), avoiding a copy into-        // internal storage on first launch.         noCompress += "nnue"     } }  dependencies {-    // Prebuilt Stockfish engine (native .so + Kotlin API), built once on JitPack.-    // 1.1.0 adds the "fd:<fd>:<offset>:<length>" EvalFile scheme used below.+    implementation(project(":sdk:games"))     implementation("com.github.vayun-mathur:Stockfish-Library:1.1.0")     testImplementation("junit:junit:4.13.2") }
games/hub/build.gradle.kts
diff --git a/games/hub/build.gradle.kts b/games/hub/build.gradle.ktsnew file mode 100644index 0000000000..2fa6311cb7--- /dev/null+++ b/games/hub/build.gradle.kts@@ -0,0 +1,23 @@+plugins {+    id("common-conventions-app")+    id("common-conventions-metadata")+}++launcherIcon {+    symbol = "stadia_controller"+}++android {+    defaultConfig {+        applicationId = "com.vayunmathur.games.hub"+    }+}++dependencies {+    implementation(project(":library"))+    implementation(project(":library:ui"))+    implementation(project(":library:room"))+    implementation(project(":sdk:games"))+    implementRoom(libs)+    implementation("androidx.compose.material:material-icons-extended")+}
games/hub/src/main/AndroidManifest.xml
diff --git a/games/hub/src/main/AndroidManifest.xml b/games/hub/src/main/AndroidManifest.xmlnew file mode 100644index 0000000000..e1cfda921c--- /dev/null+++ b/games/hub/src/main/AndroidManifest.xml@@ -0,0 +1,37 @@+<?xml version="1.0" encoding="utf-8"?>+<manifest xmlns:android="http://schemas.android.com/apk/res/android">++    <application+        android:allowBackup="true"+        android:backupAgent=".util.AppBackupAgent"+        android:dataExtractionRules="@xml/data_extraction_rules"+        android:icon="@mipmap/ic_launcher"+        android:label="@string/app_name"+        android:roundIcon="@mipmap/ic_launcher"+        android:supportsRtl="true"+        android:theme="@style/Theme.General">++        <activity+            android:name=".MainActivity"+            android:configChanges="mcc|mnc|colorMode|density|fontScale|fontWeightAdjustment|keyboard|keyboardHidden|layoutDirection|navigation|orientation|screenLayout|screenSize|smallestScreenSize|touchscreen|uiMode"+            android:exported="true"+            android:theme="@style/Theme.General">+            <intent-filter>+                <action android:name="android.intent.action.MAIN" />+                <category android:name="android.intent.category.LAUNCHER" />+            </intent-filter>+        </activity>++        <provider+            android:name=".provider.GamesHubProvider"+            android:authorities="com.vayunmathur.games.hub.provider"+            android:exported="true" />++        <provider+            android:name=".provider.GamesHubLegacyProvider"+            android:authorities="com.vayunmathur.games.provider"+            android:exported="true" />++    </application>++</manifest>
games/hub/src/main/java/com/vayunmathur/games/hub/MainActivity.kt
diff --git a/games/hub/src/main/java/com/vayunmathur/games/hub/MainActivity.kt b/games/hub/src/main/java/com/vayunmathur/games/hub/MainActivity.ktnew file mode 100644index 0000000000..92df92a51f--- /dev/null+++ b/games/hub/src/main/java/com/vayunmathur/games/hub/MainActivity.kt@@ -0,0 +1,176 @@+package com.vayunmathur.games.hub++import android.os.Bundle+import androidx.activity.ComponentActivity+import androidx.activity.compose.setContent+import androidx.activity.enableEdgeToEdge+import androidx.activity.viewModels+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.material.icons.Icons+import androidx.compose.material.icons.filled.Dashboard+import androidx.compose.material.icons.filled.EmojiEvents+import androidx.compose.material.icons.filled.Person+import androidx.compose.material.icons.filled.SportsEsports+import androidx.compose.material3.Icon+import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.setValue+import androidx.compose.ui.Modifier+import com.vayunmathur.games.hub.data.DB_NAME+import com.vayunmathur.games.hub.data.GamesHubDatabase+import com.vayunmathur.games.hub.ui.screens.AchievementsScreen+import com.vayunmathur.games.hub.ui.screens.ActivityFeedScreen+import com.vayunmathur.games.hub.ui.screens.DashboardScreen+import com.vayunmathur.games.hub.ui.screens.GameDetailScreen+import com.vayunmathur.games.hub.ui.screens.GamesListScreen+import com.vayunmathur.games.hub.ui.screens.ProfileScreen+import com.vayunmathur.games.hub.ui.screens.SettingsScreen+import com.vayunmathur.games.hub.viewmodel.GameHubViewModel+import com.vayunmathur.games.hub.viewmodel.GameHubViewModelFactory+import com.vayunmathur.library.room.buildDatabase+import com.vayunmathur.library.ui.DynamicTheme+import com.vayunmathur.library.util.BottomBarItem+import com.vayunmathur.library.util.BottomNavBar+import com.vayunmathur.library.util.DatabaseHelper+import com.vayunmathur.library.util.MainNavigation+import com.vayunmathur.library.util.NavKey+import com.vayunmathur.library.util.rememberNavBackStack+import kotlinx.serialization.Serializable++class MainActivity : ComponentActivity() {++    private var dbConfigs: List<Pair<String, String>> = emptyList()++    override fun onCreate(savedInstanceState: Bundle?) {+        super.onCreate(savedInstanceState)+        enableEdgeToEdge()++        var ready by mutableStateOf(false)++        val factory = GameHubViewModelFactory(+            application = application,+            database = application.buildDatabase<GamesHubDatabase>(dbName = DB_NAME).also {+                dbConfigs = try {+                    val pass = DatabaseHelper(this).getPassphrase()+                    listOf(DB_NAME to pass)+                } catch (_: Exception) {+                    emptyList()+                }+            }+        )+        val vm: GameHubViewModel by viewModels { factory }++        ready = true++        setContent {+            DynamicTheme {+                if (ready) {+                    HubNavigation(vm, dbConfigs)+                } else {+                    Box(Modifier.fillMaxSize())+                }+            }+        }+    }+}++@Serializable+sealed interface MainRoute : NavKey {+    @Serializable data object Dashboard : MainRoute+    @Serializable data object GamesList : MainRoute+    @Serializable data class GameDetail(val gameId: String) : MainRoute+    @Serializable data object Achievements : MainRoute+    @Serializable data class AchievementsForGame(val gameId: String) : MainRoute+    @Serializable data object Profile : MainRoute+    @Serializable data object Activity : MainRoute+    @Serializable data object Settings : MainRoute+}++@Composable+fun HubNavigation(+    viewModel: GameHubViewModel,+    dbConfigs: List<Pair<String, String>>+) {+    val backStack = rememberNavBackStack<MainRoute>(MainRoute.Dashboard)+    val current = backStack.last()++    val bottomBarItems: List<BottomBarItem<out MainRoute>> = listOf(+        BottomBarItem("Home", MainRoute.Dashboard) {+            Icon(Icons.Filled.Dashboard, contentDescription = "Home")+        },+        BottomBarItem("Games", MainRoute.GamesList) {+            Icon(Icons.Filled.SportsEsports, contentDescription = "Games")+        },+        BottomBarItem("Achievements", MainRoute.Achievements) {+            Icon(Icons.Filled.EmojiEvents, contentDescription = "Achievements")+        },+        BottomBarItem("Profile", MainRoute.Profile) {+            Icon(Icons.Filled.Person, contentDescription = "Profile")+        },+    )++    val showBottomBar = current is MainRoute.Dashboard+            || current is MainRoute.GamesList+            || current is MainRoute.Achievements+            || current is MainRoute.Profile++    MainNavigation(+        backStack = backStack,+        bottomBar = {+            if (showBottomBar) {+                BottomNavBar(backStack, bottomBarItems, current)+            }+        }+    ) {+        entry<MainRoute.Dashboard> {+            DashboardScreen(+                viewModel = viewModel,+                onGameClick = { gameId -> backStack.add(MainRoute.GameDetail(gameId)) },+                onProfileClick = { backStack.add(MainRoute.Profile) },+                onActivityClick = { backStack.add(MainRoute.Activity) },+                onGamesClick = { backStack.add(MainRoute.GamesList) },+                dbConfigs = dbConfigs,+                datastoreNames = listOf("datastore_default")+            )+        }+        entry<MainRoute.GamesList> {+            GamesListScreen(+                viewModel = viewModel,+                onGameClick = { gameId -> backStack.add(MainRoute.GameDetail(gameId)) }+            )+        }+        entry<MainRoute.GameDetail> { route ->+            GameDetailScreen(+                gameId = route.gameId,+                viewModel = viewModel,+                backStack = backStack+            )+        }+        entry<MainRoute.Achievements> {+            AchievementsScreen(viewModel = viewModel)+        }+        entry<MainRoute.AchievementsForGame> { route ->+            AchievementsScreen(viewModel = viewModel, initialGameFilter = route.gameId)+        }+        entry<MainRoute.Profile> {+            ProfileScreen(viewModel = viewModel)+        }+        entry<MainRoute.Activity> {+            ActivityFeedScreen(+                viewModel = viewModel,+                backStack = backStack,+                onGameClick = { gid -> backStack.add(MainRoute.GameDetail(gid)) }+            )+        }+        entry<MainRoute.Settings> {+            SettingsScreen(+                viewModel = viewModel,+                backStack = backStack,+                dbConfigs = dbConfigs,+                datastoreNames = listOf("datastore_default")+            )+        }+    }+}
games/hub/src/main/java/com/vayunmathur/games/hub/data/GamesHubDatabase.kt
diff --git a/games/hub/src/main/java/com/vayunmathur/games/hub/data/GamesHubDatabase.kt b/games/hub/src/main/java/com/vayunmathur/games/hub/data/GamesHubDatabase.ktnew file mode 100644index 0000000000..58c63dbfad--- /dev/null+++ b/games/hub/src/main/java/com/vayunmathur/games/hub/data/GamesHubDatabase.kt@@ -0,0 +1,37 @@+package com.vayunmathur.games.hub.data++import androidx.room.Database+import androidx.room.RoomDatabase+import com.vayunmathur.games.hub.data.dao.ActivityDao+import com.vayunmathur.games.hub.data.dao.AchievementDao+import com.vayunmathur.games.hub.data.dao.GameDao+import com.vayunmathur.games.hub.data.dao.ProfileDao+import com.vayunmathur.games.hub.data.dao.SessionDao+import com.vayunmathur.games.hub.data.entities.AchievementDefEntity+import com.vayunmathur.games.hub.data.entities.AchievementProgressEntity+import com.vayunmathur.games.hub.data.entities.ActivityEventEntity+import com.vayunmathur.games.hub.data.entities.HubGameEntity+import com.vayunmathur.games.hub.data.entities.PlaySessionEntity+import com.vayunmathur.games.hub.data.entities.PlayerProfileEntity++const val DB_NAME = "games-hub-db"++@Database(+    entities = [+        HubGameEntity::class,+        AchievementDefEntity::class,+        AchievementProgressEntity::class,+        PlaySessionEntity::class,+        PlayerProfileEntity::class,+        ActivityEventEntity::class+    ],+    version = 1,+    exportSchema = false+)+abstract class GamesHubDatabase : RoomDatabase() {+    abstract fun gameDao(): GameDao+    abstract fun achievementDao(): AchievementDao+    abstract fun sessionDao(): SessionDao+    abstract fun profileDao(): ProfileDao+    abstract fun activityDao(): ActivityDao+}
games/hub/src/main/java/com/vayunmathur/games/hub/data/dao/AchievementDao.kt
diff --git a/games/hub/src/main/java/com/vayunmathur/games/hub/data/dao/AchievementDao.kt b/games/hub/src/main/java/com/vayunmathur/games/hub/data/dao/AchievementDao.ktnew file mode 100644index 0000000000..60dc064e09--- /dev/null+++ b/games/hub/src/main/java/com/vayunmathur/games/hub/data/dao/AchievementDao.kt@@ -0,0 +1,122 @@+package com.vayunmathur.games.hub.data.dao++import androidx.room.Dao+import androidx.room.Query+import androidx.room.Upsert+import com.vayunmathur.games.hub.data.entities.AchievementDefEntity+import com.vayunmathur.games.hub.data.entities.AchievementProgressEntity+import kotlinx.coroutines.flow.Flow++data class AchievementWithProgress(+    val gameId: String,+    val achievementId: String,+    val name: String,+    val description: String,+    val xpReward: Int,+    val targetProgress: Int,+    val isSecret: Boolean,+    val tier: String,+    val iconResName: String?,+    val progress: Int,+    val isUnlocked: Boolean,+    val unlockedAt: Long?+)++@Dao+interface AchievementDao {++    @Upsert+    suspend fun upsertDef(def: AchievementDefEntity)++    @Upsert+    suspend fun upsertDefs(defs: List<AchievementDefEntity>)++    @Query("SELECT * FROM achievement_defs WHERE gameId = :gameId ORDER BY name ASC")+    fun flowDefsByGame(gameId: String): Flow<List<AchievementDefEntity>>++    @Query("SELECT * FROM achievement_defs ORDER BY gameId ASC, name ASC")+    fun flowAllDefs(): Flow<List<AchievementDefEntity>>++    @Query("SELECT * FROM achievement_defs WHERE gameId = :gameId AND achievementId = :achievementId LIMIT 1")+    suspend fun getDef(gameId: String, achievementId: String): AchievementDefEntity?++    @Query("SELECT COUNT(*) FROM achievement_defs")+    fun flowTotalDefsCount(): Flow<Int>++    @Upsert+    suspend fun upsertProgress(progress: AchievementProgressEntity)++    @Upsert+    suspend fun upsertProgresses(progresses: List<AchievementProgressEntity>)++    @Query("SELECT * FROM achievement_progress WHERE gameId = :gameId AND achievementId = :achievementId LIMIT 1")+    suspend fun getProgress(gameId: String, achievementId: String): AchievementProgressEntity?++    @Query("SELECT * FROM achievement_progress WHERE gameId = :gameId")+    fun flowProgressByGame(gameId: String): Flow<List<AchievementProgressEntity>>++    @Query("SELECT * FROM achievement_progress ORDER BY lastUpdated DESC")+    fun flowAllProgress(): Flow<List<AchievementProgressEntity>>++    @Query("SELECT * FROM achievement_progress WHERE isUnlocked = 1 ORDER BY unlockedAt DESC")+    fun flowUnlockedProgress(): Flow<List<AchievementProgressEntity>>++    @Query("""+        SELECT+            d.gameId, d.achievementId, d.name, d.description, d.xpReward,+            d.targetProgress, d.isSecret, d.tier, d.iconResName,+            COALESCE(p.progress, 0) as progress,+            COALESCE(p.isUnlocked, 0) as isUnlocked,+            p.unlockedAt as unlockedAt+        FROM achievement_defs d+        LEFT JOIN achievement_progress p+            ON p.gameId = d.gameId AND p.achievementId = d.achievementId+        ORDER BY d.gameId ASC, p.isUnlocked DESC, d.name ASC+    """)+    fun flowAllWithProgress(): Flow<List<AchievementWithProgress>>++    @Query("""+        SELECT+            d.gameId, d.achievementId, d.name, d.description, d.xpReward,+            d.targetProgress, d.isSecret, d.tier, d.iconResName,+            COALESCE(p.progress, 0) as progress,+            COALESCE(p.isUnlocked, 0) as isUnlocked,+            p.unlockedAt as unlockedAt+        FROM achievement_defs d+        LEFT JOIN achievement_progress p+            ON p.gameId = d.gameId AND p.achievementId = d.achievementId+        WHERE d.gameId = :gameId+        ORDER BY p.isUnlocked DESC, d.name ASC+    """)+    fun flowByGameWithProgress(gameId: String): Flow<List<AchievementWithProgress>>++    @Query("""+        SELECT+            d.gameId, d.achievementId, d.name, d.description, d.xpReward,+            d.targetProgress, d.isSecret, d.tier, d.iconResName,+            COALESCE(p.progress, 0) as progress,+            COALESCE(p.isUnlocked, 0) as isUnlocked,+            p.unlockedAt as unlockedAt+        FROM achievement_defs d+        LEFT JOIN achievement_progress p+            ON p.gameId = d.gameId AND p.achievementId = d.achievementId+        WHERE p.isUnlocked = 1+        ORDER BY p.unlockedAt DESC+    """)+    fun flowUnlockedWithProgress(): Flow<List<AchievementWithProgress>>++    @Query("""+        SELECT COALESCE(SUM(d.xpReward), 0)+        FROM achievement_defs d+        INNER JOIN achievement_progress p+            ON p.gameId = d.gameId AND p.achievementId = d.achievementId+        WHERE p.isUnlocked = 1+    """)+    fun flowTotalXp(): Flow<Int>++    @Query("DELETE FROM achievement_defs")+    suspend fun clearDefs()++    @Query("DELETE FROM achievement_progress")+    suspend fun clearProgress()+}
games/hub/src/main/java/com/vayunmathur/games/hub/data/dao/ActivityDao.kt
diff --git a/games/hub/src/main/java/com/vayunmathur/games/hub/data/dao/ActivityDao.kt b/games/hub/src/main/java/com/vayunmathur/games/hub/data/dao/ActivityDao.ktnew file mode 100644index 0000000000..6ccd0535a8--- /dev/null+++ b/games/hub/src/main/java/com/vayunmathur/games/hub/data/dao/ActivityDao.kt@@ -0,0 +1,29 @@+package com.vayunmathur.games.hub.data.dao++import androidx.room.Dao+import androidx.room.Query+import androidx.room.Upsert+import com.vayunmathur.games.hub.data.entities.ActivityEventEntity+import kotlinx.coroutines.flow.Flow++@Dao+interface ActivityDao {++    @Upsert+    suspend fun upsert(event: ActivityEventEntity)++    @Query("SELECT * FROM activity_events ORDER BY timestamp DESC LIMIT :limit")+    fun flowRecent(limit: Int = 50): Flow<List<ActivityEventEntity>>++    @Query("SELECT * FROM activity_events ORDER BY timestamp DESC")+    fun flowAll(): Flow<List<ActivityEventEntity>>++    @Query("SELECT * FROM activity_events WHERE gameId = :gameId ORDER BY timestamp DESC LIMIT :limit")+    fun flowByGame(gameId: String, limit: Int = 20): Flow<List<ActivityEventEntity>>++    @Query("DELETE FROM activity_events")+    suspend fun clearAll()++    @Query("DELETE FROM activity_events WHERE id NOT IN (SELECT id FROM activity_events ORDER BY timestamp DESC LIMIT :keep)")+    suspend fun trim(keep: Int = 500)+}
games/hub/src/main/java/com/vayunmathur/games/hub/data/dao/GameDao.kt
diff --git a/games/hub/src/main/java/com/vayunmathur/games/hub/data/dao/GameDao.kt b/games/hub/src/main/java/com/vayunmathur/games/hub/data/dao/GameDao.ktnew file mode 100644index 0000000000..54b1f754cf--- /dev/null+++ b/games/hub/src/main/java/com/vayunmathur/games/hub/data/dao/GameDao.kt@@ -0,0 +1,46 @@+package com.vayunmathur.games.hub.data.dao++import androidx.room.Dao+import androidx.room.Query+import androidx.room.Upsert+import com.vayunmathur.games.hub.data.entities.HubGameEntity+import kotlinx.coroutines.flow.Flow++@Dao+interface GameDao {+    @Query("SELECT * FROM hub_games ORDER BY lastPlayedAt DESC, displayName ASC")+    fun flowAll(): Flow<List<HubGameEntity>>++    @Query("SELECT * FROM hub_games WHERE gameId = :gameId LIMIT 1")+    fun flowById(gameId: String): Flow<HubGameEntity?>++    @Query("SELECT * FROM hub_games WHERE gameId = :gameId LIMIT 1")+    suspend fun getById(gameId: String): HubGameEntity?++    @Query("SELECT * FROM hub_games ORDER BY lastPlayedAt DESC")+    suspend fun getAll(): List<HubGameEntity>++    @Upsert+    suspend fun upsert(game: HubGameEntity)++    @Query("UPDATE hub_games SET lastSeenAt = :timestamp WHERE gameId = :gameId")+    suspend fun touchLastSeen(gameId: String, timestamp: Long = System.currentTimeMillis())++    @Query("UPDATE hub_games SET lastPlayedAt = :timestamp, totalSessions = totalSessions + 1 WHERE gameId = :gameId")+    suspend fun markPlayed(gameId: String, timestamp: Long = System.currentTimeMillis())++    @Query("UPDATE hub_games SET totalPlaytimeMs = totalPlaytimeMs + :increment WHERE gameId = :gameId")+    suspend fun addPlaytime(gameId: String, increment: Long)++    @Query("DELETE FROM hub_games WHERE gameId = :gameId")+    suspend fun delete(gameId: String)++    @Query("DELETE FROM hub_games")+    suspend fun clearAll()++    @Query("SELECT COALESCE(SUM(totalPlaytimeMs), 0) FROM hub_games")+    fun flowTotalPlaytimeMs(): Flow<Long>++    @Query("SELECT COALESCE(SUM(totalSessions), 0) FROM hub_games")+    fun flowTotalSessions(): Flow<Int>+}
games/hub/src/main/java/com/vayunmathur/games/hub/data/dao/ProfileDao.kt
diff --git a/games/hub/src/main/java/com/vayunmathur/games/hub/data/dao/ProfileDao.kt b/games/hub/src/main/java/com/vayunmathur/games/hub/data/dao/ProfileDao.ktnew file mode 100644index 0000000000..ed4863f948--- /dev/null+++ b/games/hub/src/main/java/com/vayunmathur/games/hub/data/dao/ProfileDao.kt@@ -0,0 +1,20 @@+package com.vayunmathur.games.hub.data.dao++import androidx.room.Dao+import androidx.room.Query+import androidx.room.Upsert+import com.vayunmathur.games.hub.data.entities.PlayerProfileEntity+import kotlinx.coroutines.flow.Flow++@Dao+interface ProfileDao {++    @Query("SELECT * FROM player_profile WHERE id = 0 LIMIT 1")+    fun flowProfile(): Flow<PlayerProfileEntity?>++    @Query("SELECT * FROM player_profile WHERE id = 0 LIMIT 1")+    suspend fun getProfile(): PlayerProfileEntity?++    @Upsert+    suspend fun upsert(profile: PlayerProfileEntity)+}
games/hub/src/main/java/com/vayunmathur/games/hub/data/dao/SessionDao.kt
diff --git a/games/hub/src/main/java/com/vayunmathur/games/hub/data/dao/SessionDao.kt b/games/hub/src/main/java/com/vayunmathur/games/hub/data/dao/SessionDao.ktnew file mode 100644index 0000000000..4616105e37--- /dev/null+++ b/games/hub/src/main/java/com/vayunmathur/games/hub/data/dao/SessionDao.kt@@ -0,0 +1,41 @@+package com.vayunmathur.games.hub.data.dao++import androidx.room.Dao+import androidx.room.Query+import androidx.room.Upsert+import com.vayunmathur.games.hub.data.entities.PlaySessionEntity+import kotlinx.coroutines.flow.Flow++@Dao+interface SessionDao {++    @Upsert+    suspend fun upsert(session: PlaySessionEntity)++    @Query("SELECT * FROM play_sessions WHERE sessionId = :sessionId LIMIT 1")+    suspend fun getBySessionId(sessionId: String): PlaySessionEntity?++    @Query("SELECT * FROM play_sessions WHERE gameId = :gameId ORDER BY startTime DESC")+    fun flowByGame(gameId: String): Flow<List<PlaySessionEntity>>++    @Query("SELECT * FROM play_sessions ORDER BY startTime DESC")+    fun flowAll(): Flow<List<PlaySessionEntity>>++    @Query("SELECT * FROM play_sessions ORDER BY startTime DESC LIMIT :limit")+    fun flowRecent(limit: Int = 50): Flow<List<PlaySessionEntity>>++    @Query("UPDATE play_sessions SET endTime = :endTime, durationMs = :durationMs WHERE sessionId = :sessionId")+    suspend fun endSession(sessionId: String, endTime: Long, durationMs: Long)++    @Query("SELECT COALESCE(SUM(durationMs), 0) FROM play_sessions WHERE endTime IS NOT NULL")+    fun flowTotalPlaytimeMs(): Flow<Long>++    @Query("SELECT COALESCE(SUM(durationMs), 0) FROM play_sessions WHERE gameId = :gameId AND endTime IS NOT NULL")+    fun flowPlaytimeByGame(gameId: String): Flow<Long>++    @Query("SELECT COUNT(*) FROM play_sessions")+    fun flowTotalCount(): Flow<Int>++    @Query("DELETE FROM play_sessions")+    suspend fun clearAll()+}
games/hub/src/main/java/com/vayunmathur/games/hub/data/entities/AchievementDefEntity.kt
diff --git a/games/hub/src/main/java/com/vayunmathur/games/hub/data/entities/AchievementDefEntity.kt b/games/hub/src/main/java/com/vayunmathur/games/hub/data/entities/AchievementDefEntity.ktnew file mode 100644index 0000000000..a5ba2d5af4--- /dev/null+++ b/games/hub/src/main/java/com/vayunmathur/games/hub/data/entities/AchievementDefEntity.kt@@ -0,0 +1,16 @@+package com.vayunmathur.games.hub.data.entities++import androidx.room.Entity++@Entity(tableName = "achievement_defs", primaryKeys = ["gameId", "achievementId"])+data class AchievementDefEntity(+    val gameId: String,+    val achievementId: String,+    val name: String,+    val description: String,+    val xpReward: Int = 25,+    val targetProgress: Int = 1,+    val isSecret: Boolean = false,+    val tier: String = "BRONZE",+    val iconResName: String? = null+)
games/hub/src/main/java/com/vayunmathur/games/hub/data/entities/AchievementProgressEntity.kt
diff --git a/games/hub/src/main/java/com/vayunmathur/games/hub/data/entities/AchievementProgressEntity.kt b/games/hub/src/main/java/com/vayunmathur/games/hub/data/entities/AchievementProgressEntity.ktnew file mode 100644index 0000000000..bb377ec16d--- /dev/null+++ b/games/hub/src/main/java/com/vayunmathur/games/hub/data/entities/AchievementProgressEntity.kt@@ -0,0 +1,13 @@+package com.vayunmathur.games.hub.data.entities++import androidx.room.Entity++@Entity(tableName = "achievement_progress", primaryKeys = ["gameId", "achievementId"])+data class AchievementProgressEntity(+    val gameId: String,+    val achievementId: String,+    val progress: Int = 0,+    val isUnlocked: Boolean = false,+    val unlockedAt: Long? = null,+    val lastUpdated: Long = System.currentTimeMillis()+)
games/hub/src/main/java/com/vayunmathur/games/hub/data/entities/ActivityEventEntity.kt
diff --git a/games/hub/src/main/java/com/vayunmathur/games/hub/data/entities/ActivityEventEntity.kt b/games/hub/src/main/java/com/vayunmathur/games/hub/data/entities/ActivityEventEntity.ktnew file mode 100644index 0000000000..8a8c9b5765--- /dev/null+++ b/games/hub/src/main/java/com/vayunmathur/games/hub/data/entities/ActivityEventEntity.kt@@ -0,0 +1,24 @@+package com.vayunmathur.games.hub.data.entities++import androidx.room.Entity+import androidx.room.PrimaryKey++@Entity(tableName = "activity_events")+data class ActivityEventEntity(+    @PrimaryKey(autoGenerate = true) val id: Long = 0,+    val timestamp: Long = System.currentTimeMillis(),+    val type: String,+    val gameId: String? = null,+    val title: String,+    val description: String? = null,+    val payloadJson: String? = null+) {+    companion object {+        const val TYPE_ACHIEVEMENT_UNLOCKED = "ACHIEVEMENT_UNLOCKED"+        const val TYPE_SESSION_COMPLETED = "SESSION_COMPLETED"+        const val TYPE_LEVEL_UP = "LEVEL_UP"+        const val TYPE_GAME_REGISTERED = "GAME_REGISTERED"+        const val TYPE_FIRST_PLAY = "FIRST_PLAY"+        const val TYPE_GAME_LAUNCHED = "GAME_LAUNCHED"+    }+}
games/hub/src/main/java/com/vayunmathur/games/hub/data/entities/HubGameEntity.kt
diff --git a/games/hub/src/main/java/com/vayunmathur/games/hub/data/entities/HubGameEntity.kt b/games/hub/src/main/java/com/vayunmathur/games/hub/data/entities/HubGameEntity.ktnew file mode 100644index 0000000000..19799f24ff--- /dev/null+++ b/games/hub/src/main/java/com/vayunmathur/games/hub/data/entities/HubGameEntity.kt@@ -0,0 +1,19 @@+package com.vayunmathur.games.hub.data.entities++import androidx.room.Entity+import androidx.room.PrimaryKey++@Entity(tableName = "hub_games")+data class HubGameEntity(+    @PrimaryKey val gameId: String,+    val packageName: String,+    val displayName: String,+    val description: String? = null,+    val versionName: String? = null,+    val versionCode: Long? = null,+    val registeredAt: Long = System.currentTimeMillis(),+    val lastSeenAt: Long = System.currentTimeMillis(),+    val lastPlayedAt: Long? = null,+    val totalPlaytimeMs: Long = 0L,+    val totalSessions: Int = 0+)
games/hub/src/main/java/com/vayunmathur/games/hub/data/entities/PlaySessionEntity.kt
diff --git a/games/hub/src/main/java/com/vayunmathur/games/hub/data/entities/PlaySessionEntity.kt b/games/hub/src/main/java/com/vayunmathur/games/hub/data/entities/PlaySessionEntity.ktnew file mode 100644index 0000000000..1c2483041c--- /dev/null+++ b/games/hub/src/main/java/com/vayunmathur/games/hub/data/entities/PlaySessionEntity.kt@@ -0,0 +1,15 @@+package com.vayunmathur.games.hub.data.entities++import androidx.room.Entity+import androidx.room.Index+import androidx.room.PrimaryKey++@Entity(tableName = "play_sessions", indices = [Index(value = ["sessionId"], unique = true)])+data class PlaySessionEntity(+    @PrimaryKey(autoGenerate = true) val id: Long = 0,+    val gameId: String,+    val sessionId: String,+    val startTime: Long,+    val endTime: Long? = null,+    val durationMs: Long? = null+)
games/hub/src/main/java/com/vayunmathur/games/hub/data/entities/PlayerProfileEntity.kt
diff --git a/games/hub/src/main/java/com/vayunmathur/games/hub/data/entities/PlayerProfileEntity.kt b/games/hub/src/main/java/com/vayunmathur/games/hub/data/entities/PlayerProfileEntity.ktnew file mode 100644index 0000000000..c82af71c9a--- /dev/null+++ b/games/hub/src/main/java/com/vayunmathur/games/hub/data/entities/PlayerProfileEntity.kt@@ -0,0 +1,14 @@+package com.vayunmathur.games.hub.data.entities++import androidx.room.Entity+import androidx.room.PrimaryKey++@Entity(tableName = "player_profile")+data class PlayerProfileEntity(+    @PrimaryKey val id: Int = 0,+    val displayName: String = "Player",+    val avatarSymbol: String? = null,+    val avatarUri: String? = null,+    val createdAt: Long = System.currentTimeMillis(),+    val title: String? = null+)
games/hub/src/main/java/com/vayunmathur/games/hub/provider/GamesHubProvider.kt
diff --git a/games/hub/src/main/java/com/vayunmathur/games/hub/provider/GamesHubProvider.kt b/games/hub/src/main/java/com/vayunmathur/games/hub/provider/GamesHubProvider.ktnew file mode 100644index 0000000000..bcdddc9044--- /dev/null+++ b/games/hub/src/main/java/com/vayunmathur/games/hub/provider/GamesHubProvider.kt@@ -0,0 +1,422 @@+package com.vayunmathur.games.hub.provider++import android.content.ContentProvider+import android.content.ContentValues+import android.content.UriMatcher+import android.database.Cursor+import android.database.MatrixCursor+import android.net.Uri+import com.vayunmathur.games.hub.data.DB_NAME+import com.vayunmathur.games.hub.data.GamesHubDatabase+import com.vayunmathur.games.hub.data.entities.AchievementDefEntity+import com.vayunmathur.games.hub.data.entities.AchievementProgressEntity+import com.vayunmathur.games.hub.data.entities.ActivityEventEntity+import com.vayunmathur.games.hub.data.entities.HubGameEntity+import com.vayunmathur.games.hub.data.entities.PlaySessionEntity+import com.vayunmathur.library.room.buildDatabase+import com.vayunmathur.sdk.games.GameHubContract+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.flow.first+import kotlinx.coroutines.runBlocking++open class GamesHubProvider : ContentProvider() {++    companion object {+        private const val CODE_GAMES = 1+        private const val CODE_GAME_ITEM = 2+        private const val CODE_ACH_DEFS = 10+        private const val CODE_ACH_PROGRESS = 11+        private const val CODE_ACH_PROGRESS_ITEM = 12+        private const val CODE_LEGACY_ACHIEVEMENTS = 20+        private const val CODE_LEGACY_ACHIEVEMENT_ITEM = 21+        private const val CODE_SESSIONS_BY_GAME = 50+        private const val CODE_SESSION_ITEM = 51++        private val uriMatcher = UriMatcher(UriMatcher.NO_MATCH).apply {+            addURI(GameHubContract.AUTHORITY, "games", CODE_GAMES)+            addURI(GameHubContract.AUTHORITY, "games/*", CODE_GAME_ITEM)+            addURI(GameHubContract.LEGACY_AUTHORITY, "games", CODE_GAMES)+            addURI(GameHubContract.LEGACY_AUTHORITY, "games/*", CODE_GAME_ITEM)++            addURI(GameHubContract.AUTHORITY, "achievements/*/defs", CODE_ACH_DEFS)+            addURI(GameHubContract.LEGACY_AUTHORITY, "achievements/*/defs", CODE_ACH_DEFS)+            addURI(GameHubContract.AUTHORITY, "achievements/*/progress", CODE_ACH_PROGRESS)+            addURI(GameHubContract.LEGACY_AUTHORITY, "achievements/*/progress", CODE_ACH_PROGRESS)+            addURI(GameHubContract.AUTHORITY, "achievements/*/progress/*", CODE_ACH_PROGRESS_ITEM)+            addURI(GameHubContract.LEGACY_AUTHORITY, "achievements/*/progress/*", CODE_ACH_PROGRESS_ITEM)++            addURI(GameHubContract.AUTHORITY, "achievements/*", CODE_LEGACY_ACHIEVEMENTS)+            addURI(GameHubContract.LEGACY_AUTHORITY, "achievements/*", CODE_LEGACY_ACHIEVEMENTS)+            addURI(GameHubContract.AUTHORITY, "achievements/*/*", CODE_LEGACY_ACHIEVEMENT_ITEM)+            addURI(GameHubContract.LEGACY_AUTHORITY, "achievements/*/*", CODE_LEGACY_ACHIEVEMENT_ITEM)++            addURI(GameHubContract.AUTHORITY, "sessions/*", CODE_SESSIONS_BY_GAME)+            addURI(GameHubContract.LEGACY_AUTHORITY, "sessions/*", CODE_SESSIONS_BY_GAME)+            addURI(GameHubContract.AUTHORITY, "sessions/*/*", CODE_SESSION_ITEM)+            addURI(GameHubContract.LEGACY_AUTHORITY, "sessions/*/*", CODE_SESSION_ITEM)+        }+    }++    @Volatile private var db: GamesHubDatabase? = null++    private fun getDb(): GamesHubDatabase {+        db?.let { return it }+        val ctx = context ?: error("GamesHubProvider context null")+        synchronized(this) {+            db?.let { return it }+            return ctx.buildDatabase<GamesHubDatabase>(dbName = DB_NAME).also { db = it }+        }+    }++    override fun onCreate(): Boolean = true++    override fun insert(uri: Uri, values: ContentValues?): Uri? {+        val v = values ?: return null+        return runBlocking(Dispatchers.IO) {+            val database = getDb()+            try {+                when (uriMatcher.match(uri)) {+                    CODE_GAME_ITEM, CODE_GAMES -> {+                        val entity = valuesToGame(v, uri)+                        database.gameDao().upsert(entity)+                        database.activityDao().upsert(+                            ActivityEventEntity(+                                type = ActivityEventEntity.TYPE_GAME_REGISTERED,+                                gameId = entity.gameId,+                                title = "${entity.displayName} registered",+                                description = entity.description+                            )+                        )+                        uri+                    }+                    CODE_ACH_DEFS, CODE_LEGACY_ACHIEVEMENTS -> {+                        val def = valuesToAchievementDef(v, uri)+                        database.achievementDao().upsertDef(def)+                        uri+                    }+                    CODE_ACH_PROGRESS -> {+                        val prog = valuesToProgress(v, uri)+                        val wasUnlocked = database.achievementDao().getProgress(prog.gameId, prog.achievementId)?.isUnlocked ?: false+                        val def = database.achievementDao().getDef(prog.gameId, prog.achievementId)+                        database.achievementDao().upsertProgress(prog)+                        if (prog.isUnlocked && !wasUnlocked && def != null) {+                            database.activityDao().upsert(+                                ActivityEventEntity(+                                    type = ActivityEventEntity.TYPE_ACHIEVEMENT_UNLOCKED,+                                    gameId = prog.gameId,+                                    title = def.name,+                                    description = def.description+                                )+                            )+                        }+                        uri+                    }+                    CODE_ACH_PROGRESS_ITEM, CODE_LEGACY_ACHIEVEMENT_ITEM -> {+                        val prog = valuesToProgress(v, uri)+                        val def = database.achievementDao().getDef(prog.gameId, prog.achievementId)+                        val existing = database.achievementDao().getProgress(prog.gameId, prog.achievementId)+                        val merged = if (existing != null) {+                            val newProgress = maxOf(existing.progress, prog.progress)+                            val newUnlocked = existing.isUnlocked || prog.isUnlocked+                            val newUnlockedAt = when {+                                newUnlocked && existing.unlockedAt != null -> existing.unlockedAt+                                newUnlocked -> prog.unlockedAt ?: System.currentTimeMillis()+                                else -> existing.unlockedAt+                            }+                            existing.copy(+                                progress = newProgress,+                                isUnlocked = newUnlocked,+                                unlockedAt = newUnlockedAt,+                                lastUpdated = System.currentTimeMillis()+                            )+                        } else prog+                        database.achievementDao().upsertProgress(merged)+                        val wasUnlockedBefore = existing?.isUnlocked ?: false+                        if (merged.isUnlocked && !wasUnlockedBefore && def != null) {+                            database.activityDao().upsert(+                                ActivityEventEntity(+                                    type = ActivityEventEntity.TYPE_ACHIEVEMENT_UNLOCKED,+                                    gameId = merged.gameId,+                                    title = def.name,+                                    description = def.description+                                )+                            )+                        }+                        if (uriMatcher.match(uri) == CODE_LEGACY_ACHIEVEMENT_ITEM) {+                            if (database.achievementDao().getDef(prog.gameId, prog.achievementId) == null) {+                                database.achievementDao().upsertDef(+                                    AchievementDefEntity(+                                        gameId = prog.gameId,+                                        achievementId = prog.achievementId,+                                        name = prog.achievementId,+                                        description = "",+                                        xpReward = 25+                                    )+                                )+                            }+                        }+                        uri+                    }+                    CODE_SESSIONS_BY_GAME -> {+                        val session = valuesToSession(v, uri)+                        database.gameDao().markPlayed(session.gameId, session.startTime)+                        database.sessionDao().upsert(session)+                        uri+                    }+                    CODE_SESSION_ITEM -> {+                        val session = valuesToSession(v, uri)+                        if (database.sessionDao().getBySessionId(session.sessionId) == null) {+                            database.gameDao().markPlayed(session.gameId, session.startTime)+                        }+                        database.sessionDao().upsert(session)+                        uri+                    }+                    else -> null+                }+            } catch (e: Exception) {+                android.util.Log.e("GamesHubProvider", "insert failed $uri", e)+                null+            }+        }+    }++    override fun update(uri: Uri, values: ContentValues?, selection: String?, selectionArgs: Array<out String>?): Int {+        val v = values ?: return 0+        return runBlocking(Dispatchers.IO) {+            val database = getDb()+            try {+                when (uriMatcher.match(uri)) {+                    CODE_ACH_PROGRESS_ITEM, CODE_LEGACY_ACHIEVEMENT_ITEM -> {+                        val gameId = uri.pathSegments.getOrNull(1) ?: v.getAsString(GameHubContract.AchievementProgressCols.GAME_ID) ?: v.getAsString("game_id") ?: return@runBlocking 0+                        val achId = uri.pathSegments.lastOrNull()?.takeIf { it != "progress" }+                            ?: v.getAsString(GameHubContract.AchievementProgressCols.ACHIEVEMENT_ID) ?: v.getAsString("achievement_id") ?: return@runBlocking 0+                        val legacyUnlocked = v.getAsInteger("unlocked")+                        val isUnlocked = when {+                            legacyUnlocked != null -> legacyUnlocked == 1+                            v.containsKey(GameHubContract.AchievementProgressCols.IS_UNLOCKED) ->+                                (v.getAsInteger(GameHubContract.AchievementProgressCols.IS_UNLOCKED) ?: 0) == 1+                            else -> false+                        }+                        val unlockedAt = v.getAsLong("unlocked_at") ?: v.getAsLong(GameHubContract.AchievementProgressCols.UNLOCKED_AT)+                        val progressVal = v.getAsInteger(GameHubContract.AchievementProgressCols.PROGRESS) ?: v.getAsInteger("progress") ?: 0++                        val existing = database.achievementDao().getProgress(gameId, achId)+                        val wasUnlockedBefore = existing?.isUnlocked ?: false+                        val merged = if (existing != null) {+                            existing.copy(+                                progress = maxOf(existing.progress, progressVal),+                                isUnlocked = existing.isUnlocked || isUnlocked,+                                unlockedAt = existing.unlockedAt ?: unlockedAt ?: if (isUnlocked) System.currentTimeMillis() else null,+                                lastUpdated = System.currentTimeMillis()+                            )+                        } else {+                            AchievementProgressEntity(+                                gameId = gameId,+                                achievementId = achId,+                                progress = progressVal,+                                isUnlocked = isUnlocked,+                                unlockedAt = unlockedAt ?: if (isUnlocked) System.currentTimeMillis() else null,+                                lastUpdated = System.currentTimeMillis()+                            )+                        }+                        database.achievementDao().upsertProgress(merged)+                        if (merged.isUnlocked && !wasUnlockedBefore) {+                            val def = database.achievementDao().getDef(gameId, achId)+                            database.activityDao().upsert(+                                ActivityEventEntity(+                                    type = ActivityEventEntity.TYPE_ACHIEVEMENT_UNLOCKED,+                                    gameId = gameId,+                                    title = def?.name ?: achId,+                                    description = def?.description+                                )+                            )+                        }+                        1+                    }+                    CODE_SESSION_ITEM -> {+                        val sessionId = uri.pathSegments.lastOrNull() ?: return@runBlocking 0+                        val existing = database.sessionDao().getBySessionId(sessionId) ?: return@runBlocking 0+                        val endTime = v.getAsLong(GameHubContract.Sessions.END_TIME) ?: v.getAsLong("end_time") ?: System.currentTimeMillis()+                        val duration = (endTime - existing.startTime).coerceAtLeast(0L)+                        database.sessionDao().endSession(sessionId, endTime, duration)+                        database.gameDao().addPlaytime(existing.gameId, duration)+                        database.activityDao().upsert(+                            ActivityEventEntity(+                                type = ActivityEventEntity.TYPE_SESSION_COMPLETED,+                                gameId = existing.gameId,+                                title = "Played ${existing.gameId}",+                                description = "Session ${duration / 1000}s"+                            )+                        )+                        1+                    }+                    else -> 0+                }+            } catch (e: Exception) {+                android.util.Log.e("GamesHubProvider", "update failed $uri", e)+                0+            }+        }+    }++    override fun query(uri: Uri, projection: Array<out String>?, selection: String?, selectionArgs: Array<out String>?, sortOrder: String?): Cursor? {+        return runBlocking(Dispatchers.IO) {+            val database = getDb()+            try {+                when (uriMatcher.match(uri)) {+                    CODE_GAMES -> cursorFromGames(database.gameDao().getAll())+                    CODE_GAME_ITEM -> {+                        val gameId = uri.pathSegments.getOrNull(1) ?: return@runBlocking null+                        val game = database.gameDao().getById(gameId)+                        cursorFromGames(listOfNotNull(game))+                    }+                    CODE_ACH_DEFS -> {+                        val gameId = uri.pathSegments.getOrNull(1) ?: return@runBlocking null+                        cursorFromAchievementDefs(database.achievementDao().flowDefsByGame(gameId).first())+                    }+                    CODE_LEGACY_ACHIEVEMENTS -> {+                        val gameId = uri.pathSegments.getOrNull(1) ?: return@runBlocking null+                        val allDefs = database.achievementDao().flowDefsByGame(gameId).first()+                        val progressMap = database.achievementDao().flowProgressByGame(gameId).first().associateBy { it.achievementId }+                        cursorFromLegacyAchievements(allDefs, progressMap)+                    }+                    CODE_ACH_PROGRESS -> {+                        val gameId = uri.pathSegments.getOrNull(1) ?: return@runBlocking null+                        cursorFromProgress(database.achievementDao().flowProgressByGame(gameId).first())+                    }+                    CODE_ACH_PROGRESS_ITEM -> {+                        val gameId = uri.pathSegments.getOrNull(1) ?: return@runBlocking null+                        val achId = uri.pathSegments.getOrNull(3) ?: return@runBlocking null+                        val prog = database.achievementDao().getProgress(gameId, achId)+                        cursorFromProgress(listOfNotNull(prog))+                    }+                    CODE_LEGACY_ACHIEVEMENT_ITEM -> {+                        val gameId = uri.pathSegments.getOrNull(1) ?: return@runBlocking null+                        val achId = uri.pathSegments.getOrNull(2) ?: return@runBlocking null+                        cursorFromLegacyAchievementItem(database.achievementDao().getDef(gameId, achId), database.achievementDao().getProgress(gameId, achId))+                    }+                    else -> null+                }+            } catch (e: Exception) {+                android.util.Log.e("GamesHubProvider", "query failed $uri", e)+                null+            }+        }+    }++    override fun delete(uri: Uri, selection: String?, selectionArgs: Array<out String>?): Int = 0+    override fun getType(uri: Uri): String? = null++    private fun valuesToGame(v: ContentValues, uri: Uri): HubGameEntity {+        val segGameId = uri.pathSegments.getOrNull(1)+        val gameId = v.getAsString(GameHubContract.Games.GAME_ID) ?: v.getAsString("game_id") ?: segGameId ?: error("gameId missing")+        return HubGameEntity(+            gameId = gameId,+            packageName = v.getAsString(GameHubContract.Games.PACKAGE_NAME) ?: v.getAsString("package_name") ?: "unknown",+            displayName = v.getAsString(GameHubContract.Games.DISPLAY_NAME) ?: v.getAsString("display_name") ?: gameId,+            description = v.getAsString(GameHubContract.Games.DESCRIPTION) ?: v.getAsString("description"),+            versionName = v.getAsString(GameHubContract.Games.VERSION_NAME) ?: v.getAsString("version_name"),+            versionCode = v.getAsLong(GameHubContract.Games.VERSION_CODE) ?: v.getAsLong("version_code"),+            registeredAt = v.getAsLong(GameHubContract.Games.REGISTERED_AT) ?: v.getAsLong("registered_at") ?: System.currentTimeMillis(),+            lastSeenAt = v.getAsLong(GameHubContract.Games.LAST_SEEN_AT) ?: v.getAsLong("last_seen_at") ?: System.currentTimeMillis()+        )+    }++    private fun valuesToAchievementDef(v: ContentValues, uri: Uri): AchievementDefEntity {+        val segGameId = uri.pathSegments.getOrNull(1)+        val gameId = v.getAsString(GameHubContract.AchievementDefs.GAME_ID) ?: v.getAsString("game_id") ?: segGameId ?: error("gameId missing in def")+        val achId = v.getAsString(GameHubContract.AchievementDefs.ACHIEVEMENT_ID) ?: v.getAsString("achievement_id") ?: error("achievement_id missing")+        return AchievementDefEntity(+            gameId = gameId,+            achievementId = achId,+            name = v.getAsString(GameHubContract.AchievementDefs.NAME) ?: v.getAsString("name") ?: achId,+            description = v.getAsString(GameHubContract.AchievementDefs.DESCRIPTION) ?: v.getAsString("description") ?: "",+            xpReward = v.getAsInteger(GameHubContract.AchievementDefs.XP_REWARD) ?: v.getAsInteger("xp_reward") ?: 25,+            targetProgress = v.getAsInteger(GameHubContract.AchievementDefs.TARGET_PROGRESS) ?: v.getAsInteger("target_progress") ?: 1,+            isSecret = (v.getAsInteger(GameHubContract.AchievementDefs.IS_SECRET) ?: v.getAsInteger("is_secret") ?: 0) == 1,+            tier = v.getAsString(GameHubContract.AchievementDefs.TIER) ?: v.getAsString("tier") ?: "BRONZE",+            iconResName = v.getAsString(GameHubContract.AchievementDefs.ICON_RES_NAME) ?: v.getAsString("icon_res_name")+        )+    }++    private fun valuesToProgress(v: ContentValues, uri: Uri): AchievementProgressEntity {+        val segs = uri.pathSegments+        val segGameId = segs.getOrNull(1)+        val segAchId = when {+            segs.size >= 4 && segs[2] == "progress" -> segs[3]+            segs.size == 3 && segs[1] != "defs" && segs[1] != "progress" -> segs[2]+            else -> null+        }+        val gameId = v.getAsString(GameHubContract.AchievementProgressCols.GAME_ID) ?: v.getAsString("game_id") ?: segGameId ?: error("gameId missing in progress")+        val achId = v.getAsString(GameHubContract.AchievementProgressCols.ACHIEVEMENT_ID) ?: v.getAsString("achievement_id") ?: segAchId ?: error("achievementId missing in progress")+        val legacyUnlocked = v.getAsInteger("unlocked")+        val newUnlocked = v.getAsInteger(GameHubContract.AchievementProgressCols.IS_UNLOCKED)+        val isUnlocked = when {+            legacyUnlocked != null -> legacyUnlocked == 1+            newUnlocked != null -> newUnlocked == 1+            else -> false+        }+        return AchievementProgressEntity(+            gameId = gameId,+            achievementId = achId,+            progress = v.getAsInteger(GameHubContract.AchievementProgressCols.PROGRESS) ?: v.getAsInteger("progress") ?: if (isUnlocked) 1 else 0,+            isUnlocked = isUnlocked,+            unlockedAt = v.getAsLong(GameHubContract.AchievementProgressCols.UNLOCKED_AT) ?: v.getAsLong("unlocked_at") ?: if (isUnlocked) System.currentTimeMillis() else null,+            lastUpdated = v.getAsLong(GameHubContract.AchievementProgressCols.LAST_UPDATED) ?: System.currentTimeMillis()+        )+    }++    private fun valuesToSession(v: ContentValues, uri: Uri): PlaySessionEntity {+        val segGameId = uri.pathSegments.getOrNull(1)+        val segSessionId = uri.pathSegments.getOrNull(2)+        return PlaySessionEntity(+            gameId = v.getAsString(GameHubContract.Sessions.GAME_ID) ?: v.getAsString("game_id") ?: segGameId ?: error("gameId missing in session"),+            sessionId = v.getAsString(GameHubContract.Sessions.SESSION_ID) ?: v.getAsString("session_id") ?: segSessionId ?: error("sessionId missing"),+            startTime = v.getAsLong(GameHubContract.Sessions.START_TIME) ?: v.getAsLong("start_time") ?: System.currentTimeMillis(),+            endTime = v.getAsLong(GameHubContract.Sessions.END_TIME) ?: v.getAsLong("end_time"),+            durationMs = v.getAsLong(GameHubContract.Sessions.DURATION_MS) ?: v.getAsLong("duration_ms")+        )+    }++    private fun cursorFromGames(games: List<HubGameEntity>): MatrixCursor {+        val c = MatrixCursor(arrayOf("game_id", "package_name", "display_name", "description", "version_name", "version_code", "registered_at", "last_seen_at", "last_played_at", "total_playtime_ms", "total_sessions"))+        for (g in games) {+            c.addRow(arrayOf<Any?>(g.gameId, g.packageName, g.displayName, g.description, g.versionName, g.versionCode, g.registeredAt, g.lastSeenAt, g.lastPlayedAt, g.totalPlaytimeMs, g.totalSessions))+        }+        return c+    }++    private fun cursorFromAchievementDefs(defs: List<com.vayunmathur.games.hub.data.entities.AchievementDefEntity>): MatrixCursor {+        val c = MatrixCursor(arrayOf("game_id", "achievement_id", "name", "description", "xp_reward", "target_progress", "is_secret", "tier", "icon_res_name"))+        for (d in defs) {+            c.addRow(arrayOf<Any?>(d.gameId, d.achievementId, d.name, d.description, d.xpReward, d.targetProgress, if (d.isSecret) 1 else 0, d.tier, d.iconResName))+        }+        return c+    }++    private fun cursorFromProgress(progresses: List<AchievementProgressEntity>): MatrixCursor {+        val c = MatrixCursor(arrayOf("game_id", "achievement_id", "progress", "is_unlocked", "unlocked_at", "last_updated"))+        for (p in progresses) {+            c.addRow(arrayOf<Any?>(p.gameId, p.achievementId, p.progress, if (p.isUnlocked) 1 else 0, p.unlockedAt, p.lastUpdated))+        }+        return c+    }++    private fun cursorFromLegacyAchievements(defs: List<AchievementDefEntity>, progressMap: Map<String, AchievementProgressEntity>): MatrixCursor {+        val c = MatrixCursor(arrayOf("achievement_id", "game_id", "name", "description", "icon_res_name", "unlocked", "unlocked_at"))+        for (d in defs) {+            val prog = progressMap[d.achievementId]+            c.addRow(arrayOf<Any?>(d.achievementId, d.gameId, d.name, d.description, d.iconResName, if (prog?.isUnlocked == true) 1 else 0, prog?.unlockedAt))+        }+        return c+    }++    private fun cursorFromLegacyAchievementItem(def: AchievementDefEntity?, prog: AchievementProgressEntity?): MatrixCursor {+        val c = MatrixCursor(arrayOf("achievement_id", "game_id", "name", "description", "icon_res_name", "unlocked", "unlocked_at"))+        val unlocked = prog?.isUnlocked == true+        c.addRow(arrayOf<Any?>(def?.achievementId ?: prog?.achievementId ?: "", def?.gameId ?: prog?.gameId ?: "", def?.name ?: "", def?.description ?: "", def?.iconResName, if (unlocked) 1 else 0, prog?.unlockedAt))+        return c+    }+}++class GamesHubLegacyProvider : GamesHubProvider()
games/hub/src/main/java/com/vayunmathur/games/hub/ui/components/AchievementRow.kt
diff --git a/games/hub/src/main/java/com/vayunmathur/games/hub/ui/components/AchievementRow.kt b/games/hub/src/main/java/com/vayunmathur/games/hub/ui/components/AchievementRow.ktnew file mode 100644index 0000000000..0179b31b4b--- /dev/null+++ b/games/hub/src/main/java/com/vayunmathur/games/hub/ui/components/AchievementRow.kt@@ -0,0 +1,102 @@+package com.vayunmathur.games.hub.ui.components++import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.runtime.Composable+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.res.painterResource+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.unit.dp+import com.vayunmathur.games.hub.data.dao.AchievementWithProgress+import com.vayunmathur.games.hub.util.tierColor+import com.vayunmathur.library.ui.Card+import com.vayunmathur.library.ui.CardDefaults+import com.vayunmathur.library.ui.Icon+import com.vayunmathur.library.ui.LinearProgressIndicator+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.Text++@Composable+fun AchievementRow(+    item: AchievementWithProgress,+    modifier: Modifier = Modifier,+    showGameTag: Boolean = true+) {+    val isLocked = !item.isUnlocked+    val tierCol = tierColor(item.tier)++    Card(+        modifier = modifier+            .fillMaxWidth()+            .padding(horizontal = 16.dp, vertical = 4.dp),+        shape = RoundedCornerShape(12.dp),+        colors = CardDefaults.cardColors(+            containerColor = if (item.isUnlocked) MaterialTheme.colorScheme.secondaryContainer+            else MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.6f)+        )+    ) {+        Row(+            modifier = Modifier.padding(12.dp),+            verticalAlignment = Alignment.CenterVertically+        ) {+            Icon(+                painter = painterResource(id = android.R.drawable.btn_star_big_on),+                contentDescription = null,+                modifier = Modifier.size(40.dp),+                tint = if (item.isUnlocked) tierCol else Color.Gray+            )+            Column(+                modifier = Modifier+                    .padding(start = 12.dp)+                    .weight(1f),+                verticalArrangement = Arrangement.spacedBy(2.dp)+            ) {+                Row(horizontalArrangement = Arrangement.spacedBy(6.dp), verticalAlignment = Alignment.CenterVertically) {+                    Text(+                        text = if (item.isSecret && isLocked) "???" else item.name,+                        style = MaterialTheme.typography.titleSmall,+                        fontWeight = FontWeight.Bold,+                        modifier = Modifier.weight(1f, fill = false)+                    )+                    Text(+                        text = "+${item.xpReward} XP",+                        style = MaterialTheme.typography.labelSmall,+                        color = tierCol+                    )+                }+                Text(+                    text = if (item.isSecret && isLocked) "Keep playing to reveal" else item.description,+                    style = MaterialTheme.typography.bodySmall,+                    maxLines = 2+                )+                if (showGameTag) {+                    Text(+                        text = item.gameId,+                        style = MaterialTheme.typography.labelSmall,+                        color = MaterialTheme.colorScheme.primary+                    )+                }+                if (item.targetProgress > 1) {+                    val displayProgress = if (item.isUnlocked) item.targetProgress else item.progress+                    val ratio = (displayProgress.toFloat() / item.targetProgress.toFloat()).coerceIn(0f, 1f)+                    LinearProgressIndicator(+                        progress = { ratio },+                        modifier = Modifier.fillMaxWidth().padding(top = 4.dp)+                    )+                    Text(+                        text = if (item.isUnlocked) "Completed!" else "$displayProgress / ${item.targetProgress}",+                        style = MaterialTheme.typography.labelSmall,+                        modifier = Modifier.align(Alignment.End)+                    )+                }+            }+        }+    }+}
games/hub/src/main/java/com/vayunmathur/games/hub/ui/components/ActivityItem.kt
diff --git a/games/hub/src/main/java/com/vayunmathur/games/hub/ui/components/ActivityItem.kt b/games/hub/src/main/java/com/vayunmathur/games/hub/ui/components/ActivityItem.ktnew file mode 100644index 0000000000..d34c954edc--- /dev/null+++ b/games/hub/src/main/java/com/vayunmathur/games/hub/ui/components/ActivityItem.kt@@ -0,0 +1,61 @@+package com.vayunmathur.games.hub.ui.components++import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.runtime.Composable+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.res.painterResource+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.unit.dp+import com.vayunmathur.games.hub.data.entities.ActivityEventEntity+import com.vayunmathur.games.hub.util.formatRelativeTime+import com.vayunmathur.library.ui.Card+import com.vayunmathur.library.ui.Icon+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.Text++@Composable+fun ActivityItemCard(+    event: ActivityEventEntity,+    onGameClick: ((String) -> Unit)? = null,+    modifier: Modifier = Modifier+) {+    Card(+        onClick = { event.gameId?.let { onGameClick?.invoke(it) } },+        modifier = modifier.fillMaxWidth()+    ) {+        Row(+            modifier = Modifier.padding(12.dp),+            verticalAlignment = Alignment.Top,+            horizontalArrangement = Arrangement.spacedBy(12.dp)+        ) {+            Icon(+                painter = painterResource(id = iconForType(event.type)),+                contentDescription = event.type,+                modifier = Modifier.padding(top = 2.dp)+            )+            Column(modifier = Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(2.dp)) {+                Text(text = event.title, style = MaterialTheme.typography.titleSmall, fontWeight = FontWeight.Bold)+                event.description?.let { Text(text = it, style = MaterialTheme.typography.bodySmall) }+                Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {+                    event.gameId?.let {+                        Text(text = it, style = MaterialTheme.typography.labelSmall, color = MaterialTheme.colorScheme.primary)+                    }+                    Text(text = formatRelativeTime(event.timestamp), style = MaterialTheme.typography.labelSmall, color = MaterialTheme.colorScheme.onSurfaceVariant)+                }+            }+        }+    }+}++private fun iconForType(type: String): Int = when (type) {+    ActivityEventEntity.TYPE_ACHIEVEMENT_UNLOCKED -> android.R.drawable.btn_star_big_on+    ActivityEventEntity.TYPE_LEVEL_UP -> android.R.drawable.ic_menu_slideshow+    ActivityEventEntity.TYPE_GAME_REGISTERED -> android.R.drawable.ic_menu_add+    ActivityEventEntity.TYPE_SESSION_COMPLETED -> android.R.drawable.ic_media_play+    else -> android.R.drawable.ic_menu_info_details+}
games/hub/src/main/java/com/vayunmathur/games/hub/ui/components/GameCard.kt
diff --git a/games/hub/src/main/java/com/vayunmathur/games/hub/ui/components/GameCard.kt b/games/hub/src/main/java/com/vayunmathur/games/hub/ui/components/GameCard.ktnew file mode 100644index 0000000000..9edf3db078--- /dev/null+++ b/games/hub/src/main/java/com/vayunmathur/games/hub/ui/components/GameCard.kt@@ -0,0 +1,105 @@+package com.vayunmathur.games.hub.ui.components++import android.graphics.drawable.Drawable+import androidx.compose.foundation.Image+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.runtime.Composable+import androidx.compose.runtime.remember+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.draw.clip+import androidx.compose.ui.graphics.asImageBitmap+import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.unit.dp+import androidx.core.graphics.drawable.toBitmap+import com.vayunmathur.games.hub.data.entities.HubGameEntity+import com.vayunmathur.games.hub.util.GameIconResolver+import com.vayunmathur.games.hub.util.formatPlaytime+import com.vayunmathur.library.ui.Card+import com.vayunmathur.library.ui.CardDefaults+import com.vayunmathur.library.ui.CircularProgressIndicator+import com.vayunmathur.library.ui.IconButton+import com.vayunmathur.library.ui.IconPlay+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.Text++@Composable+fun GameCard(+    game: HubGameEntity,+    isInstalled: Boolean,+    achievementProgress: Pair<Int, Int>? = null,+    iconDrawable: Drawable? = null,+    onClick: () -> Unit,+    onPlay: () -> Unit,+    modifier: Modifier = Modifier+) {+    val context = LocalContext.current+    val resolvedIcon = iconDrawable ?: remember(game.packageName) {+        GameIconResolver.resolveAppIcon(context, game.packageName)+    }++    Card(+        onClick = onClick,+        modifier = modifier.fillMaxWidth(),+        colors = CardDefaults.cardColors(+            containerColor = if (isInstalled) MaterialTheme.colorScheme.surfaceVariant+            else MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.6f)+        )+    ) {+        Row(+            modifier = Modifier.padding(12.dp),+            verticalAlignment = Alignment.CenterVertically,+            horizontalArrangement = Arrangement.spacedBy(12.dp)+        ) {+            Box(+                modifier = Modifier.size(48.dp).clip(RoundedCornerShape(12.dp)),+                contentAlignment = Alignment.Center+            ) {+                if (resolvedIcon != null) {+                    val bmp = remember(resolvedIcon) {+                        try { resolvedIcon.toBitmap(96, 96) } catch (_: Exception) { null }+                    }+                    if (bmp != null) {+                        Image(bitmap = bmp.asImageBitmap(), contentDescription = game.displayName, modifier = Modifier.size(48.dp).clip(RoundedCornerShape(12.dp)))+                    } else {+                        Text(text = game.displayName.firstOrNull()?.uppercase() ?: "?", style = MaterialTheme.typography.titleLarge, fontWeight = FontWeight.Bold)+                    }+                } else {+                    Text(text = game.displayName.firstOrNull()?.uppercase() ?: "?", style = MaterialTheme.typography.titleLarge, fontWeight = FontWeight.Bold)+                }+            }++            Column(modifier = Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(2.dp)) {+                Text(text = game.displayName, style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold)+                Text(text = if (isInstalled) "Installed" else "Not installed", style = MaterialTheme.typography.labelSmall, color = MaterialTheme.colorScheme.onSurfaceVariant)+                if (game.totalPlaytimeMs > 0) {+                    Text(text = "Playtime: ${formatPlaytime(game.totalPlaytimeMs)} • ${game.totalSessions} sessions", style = MaterialTheme.typography.labelSmall)+                }+                achievementProgress?.let { (unlocked, total) ->+                    if (total > 0) {+                        Text(text = "Achievements: $unlocked/$total", style = MaterialTheme.typography.labelSmall)+                    }+                }+            }++            if (achievementProgress != null && achievementProgress.second > 0) {+                val (unlocked, total) = achievementProgress+                val denom = total.toFloat().coerceAtLeast(1f)+                val frac = (unlocked.toFloat() / denom).coerceIn(0f, 1f)+                CircularProgressIndicator(progress = { frac }, modifier = Modifier.size(32.dp))+            }++            IconButton(onClick = onPlay) {+                IconPlay()+            }+        }+    }+}
games/hub/src/main/java/com/vayunmathur/games/hub/ui/components/LevelBadge.kt
diff --git a/games/hub/src/main/java/com/vayunmathur/games/hub/ui/components/LevelBadge.kt b/games/hub/src/main/java/com/vayunmathur/games/hub/ui/components/LevelBadge.ktnew file mode 100644index 0000000000..1284e3077f--- /dev/null+++ b/games/hub/src/main/java/com/vayunmathur/games/hub/ui/components/LevelBadge.kt@@ -0,0 +1,35 @@+package com.vayunmathur.games.hub.ui.components++import androidx.compose.foundation.background+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.shape.CircleShape+import androidx.compose.runtime.Composable+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.draw.clip+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.unit.dp+import androidx.compose.ui.unit.sp+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.Text++@Composable+fun LevelBadge(level: Int, modifier: Modifier = Modifier, large: Boolean = false) {+    val size = if (large) 56.dp else 36.dp+    val fontSize = if (large) 20.sp else 14.sp+    Box(+        modifier = modifier+            .size(size)+            .clip(CircleShape)+            .background(MaterialTheme.colorScheme.primary),+        contentAlignment = Alignment.Center+    ) {+        Text(+            text = "$level",+            fontSize = fontSize,+            fontWeight = FontWeight.Bold,+            color = MaterialTheme.colorScheme.onPrimary+        )+    }+}
games/hub/src/main/java/com/vayunmathur/games/hub/ui/components/StatCard.kt
diff --git a/games/hub/src/main/java/com/vayunmathur/games/hub/ui/components/StatCard.kt b/games/hub/src/main/java/com/vayunmathur/games/hub/ui/components/StatCard.ktnew file mode 100644index 0000000000..2bfcd21a49--- /dev/null+++ b/games/hub/src/main/java/com/vayunmathur/games/hub/ui/components/StatCard.kt@@ -0,0 +1,51 @@+package com.vayunmathur.games.hub.ui.components++import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.padding+import androidx.compose.runtime.Composable+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.unit.dp+import com.vayunmathur.library.ui.Card+import com.vayunmathur.library.ui.CardDefaults+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.Text++@Composable+fun StatCard(+    label: String,+    value: String,+    modifier: Modifier = Modifier,+    subLabel: String? = null+) {+    Card(+        modifier = modifier,+        colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surfaceVariant)+    ) {+        Column(+            modifier = Modifier.padding(12.dp),+            verticalArrangement = Arrangement.spacedBy(2.dp),+            horizontalAlignment = Alignment.CenterHorizontally+        ) {+            Text(+                text = value,+                style = MaterialTheme.typography.titleLarge,+                fontWeight = FontWeight.Bold+            )+            Text(+                text = label,+                style = MaterialTheme.typography.labelSmall,+                color = MaterialTheme.colorScheme.onSurfaceVariant+            )+            subLabel?.let {+                Text(+                    text = it,+                    style = MaterialTheme.typography.labelSmall,+                    color = MaterialTheme.colorScheme.onSurfaceVariant+                )+            }+        }+    }+}
games/hub/src/main/java/com/vayunmathur/games/hub/ui/components/StreakIndicator.kt
diff --git a/games/hub/src/main/java/com/vayunmathur/games/hub/ui/components/StreakIndicator.kt b/games/hub/src/main/java/com/vayunmathur/games/hub/ui/components/StreakIndicator.ktnew file mode 100644index 0000000000..ba84e48051--- /dev/null+++ b/games/hub/src/main/java/com/vayunmathur/games/hub/ui/components/StreakIndicator.kt@@ -0,0 +1,41 @@+package com.vayunmathur.games.hub.ui.components++import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.padding+import androidx.compose.material3.Card+import androidx.compose.material3.CardDefaults+import androidx.compose.runtime.Composable+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.res.painterResource+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.unit.dp+import com.vayunmathur.library.ui.Icon+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.Text++@Composable+fun StreakCard(+    currentStreak: Int,+    longestStreak: Int,+    modifier: Modifier = Modifier+) {+    Card(+        modifier = modifier,+        colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.tertiaryContainer)+    ) {+        Row(+            modifier = Modifier.padding(16.dp),+            verticalAlignment = Alignment.CenterVertically,+            horizontalArrangement = Arrangement.spacedBy(12.dp)+        ) {+            Icon(painter = painterResource(id = android.R.drawable.ic_menu_day), contentDescription = "Streak")+            Column(verticalArrangement = Arrangement.spacedBy(2.dp)) {+                Text(text = "$currentStreak day streak 🔥", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold)+                Text(text = "Longest: $longestStreak days", style = MaterialTheme.typography.bodySmall)+            }+        }+    }+}
games/hub/src/main/java/com/vayunmathur/games/hub/ui/components/XpProgressBar.kt
diff --git a/games/hub/src/main/java/com/vayunmathur/games/hub/ui/components/XpProgressBar.kt b/games/hub/src/main/java/com/vayunmathur/games/hub/ui/components/XpProgressBar.ktnew file mode 100644index 0000000000..e519005973--- /dev/null+++ b/games/hub/src/main/java/com/vayunmathur/games/hub/ui/components/XpProgressBar.kt@@ -0,0 +1,61 @@+package com.vayunmathur.games.hub.ui.components++import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.runtime.Composable+import androidx.compose.ui.Modifier+import androidx.compose.ui.unit.dp+import com.vayunmathur.games.hub.util.XpLevelCalculator+import com.vayunmathur.library.ui.LinearProgressIndicator+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.Text++@Composable+fun XpProgressBar(+    totalXp: Int,+    modifier: Modifier = Modifier+) {+    val level = XpLevelCalculator.level(totalXp)+    val progress = XpLevelCalculator.progressToNextLevel(totalXp)+    val nextLevelXp = XpLevelCalculator.xpForLevel(level + 1)+    val toNext = XpLevelCalculator.xpToNextLevel(totalXp)++    Column(modifier = modifier, verticalArrangement = Arrangement.spacedBy(4.dp)) {+        Row(+            modifier = Modifier.fillMaxWidth(),+            horizontalArrangement = Arrangement.SpaceBetween+        ) {+            Text(+                text = "Level $level • ${XpLevelCalculator.title(level)}",+                style = MaterialTheme.typography.labelMedium,+                color = MaterialTheme.colorScheme.primary+            )+            Text(+                text = "$toNext XP to L${level + 1}",+                style = MaterialTheme.typography.labelSmall,+                color = MaterialTheme.colorScheme.onSurfaceVariant+            )+        }+        LinearProgressIndicator(+            progress = { progress },+            modifier = Modifier.fillMaxWidth()+        )+        Row(+            modifier = Modifier.fillMaxWidth(),+            horizontalArrangement = Arrangement.SpaceBetween+        ) {+            Text(+                text = "$totalXp XP total",+                style = MaterialTheme.typography.labelSmall,+                color = MaterialTheme.colorScheme.onSurfaceVariant+            )+            Text(+                text = "Next: $nextLevelXp XP",+                style = MaterialTheme.typography.labelSmall,+                color = MaterialTheme.colorScheme.onSurfaceVariant+            )+        }+    }+}
games/hub/src/main/java/com/vayunmathur/games/hub/ui/screens/AchievementsScreen.kt
diff --git a/games/hub/src/main/java/com/vayunmathur/games/hub/ui/screens/AchievementsScreen.kt b/games/hub/src/main/java/com/vayunmathur/games/hub/ui/screens/AchievementsScreen.ktnew file mode 100644index 0000000000..d6a52ee0cd--- /dev/null+++ b/games/hub/src/main/java/com/vayunmathur/games/hub/ui/screens/AchievementsScreen.kt@@ -0,0 +1,87 @@+package com.vayunmathur.games.hub.ui.screens++import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.PaddingValues+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.lazy.LazyColumn+import androidx.compose.foundation.lazy.LazyRow+import androidx.compose.foundation.lazy.items+import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.Modifier+import androidx.compose.ui.unit.dp+import androidx.lifecycle.compose.collectAsStateWithLifecycle+import com.vayunmathur.games.hub.data.dao.AchievementWithProgress+import com.vayunmathur.games.hub.ui.components.AchievementRow+import com.vayunmathur.games.hub.viewmodel.GameHubViewModel+import com.vayunmathur.library.ui.CommonSearchBar+import com.vayunmathur.library.ui.FilterChip+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.Scaffold+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.TopAppBar++enum class AchievementFilter { ALL, LOCKED, UNLOCKED }++@Composable+fun AchievementsScreen(+    viewModel: GameHubViewModel,+    modifier: Modifier = Modifier,+    initialGameFilter: String? = null+) {+    val allAchievements by viewModel.allAchievementsFlow.collectAsStateWithLifecycle()+    val games by viewModel.gamesFlow.collectAsStateWithLifecycle()++    var search by remember { mutableStateOf("") }+    var statusFilter by remember { mutableStateOf(AchievementFilter.ALL) }+    var gameFilter by remember { mutableStateOf<String?>(initialGameFilter) }++    val gameIds = remember(games, allAchievements) {+        (games.map { it.gameId } + allAchievements.map { it.gameId }).distinct().sorted()+    }++    val filtered = remember(allAchievements, search, statusFilter, gameFilter) {+        var list = allAchievements+        if (search.isNotBlank()) {+            list = list.filter { it.name.contains(search, true) || it.description.contains(search, true) || it.gameId.contains(search, true) }+        }+        list = when (statusFilter) {+            AchievementFilter.LOCKED -> list.filter { !it.isUnlocked }+            AchievementFilter.UNLOCKED -> list.filter { it.isUnlocked }+            AchievementFilter.ALL -> list+        }+        if (gameFilter != null) list = list.filter { it.gameId == gameFilter }+        list.sortedWith(compareBy<AchievementWithProgress> { !it.isUnlocked }.thenBy { it.gameId }.thenBy { it.name })+    }++    Scaffold(topBar = { TopAppBar(title = { Text("Achievements (${filtered.size})") }) }) { padding ->+        LazyColumn(modifier = modifier.fillMaxSize().padding(padding), contentPadding = PaddingValues(bottom = 16.dp), verticalArrangement = Arrangement.spacedBy(4.dp)) {+            item { CommonSearchBar(value = search, onValueChange = { search = it }, padding = PaddingValues(horizontal = 16.dp, vertical = 8.dp)) }+            item {+                LazyRow(contentPadding = PaddingValues(horizontal = 16.dp), horizontalArrangement = Arrangement.spacedBy(8.dp)) {+                    item { FilterChip(selected = statusFilter == AchievementFilter.ALL, onClick = { statusFilter = AchievementFilter.ALL }, label = { Text("All") }) }+                    item { FilterChip(selected = statusFilter == AchievementFilter.UNLOCKED, onClick = { statusFilter = AchievementFilter.UNLOCKED }, label = { Text("Unlocked") }) }+                    item { FilterChip(selected = statusFilter == AchievementFilter.LOCKED, onClick = { statusFilter = AchievementFilter.LOCKED }, label = { Text("Locked") }) }+                }+            }+            if (gameIds.isNotEmpty()) {+                item {+                    LazyRow(contentPadding = PaddingValues(horizontal = 16.dp, vertical = 4.dp), horizontalArrangement = Arrangement.spacedBy(8.dp)) {+                        item { FilterChip(selected = gameFilter == null, onClick = { gameFilter = null }, label = { Text("All games") }) }+                        items(gameIds, key = { it }) { gid ->+                            FilterChip(selected = gameFilter == gid, onClick = { gameFilter = if (gameFilter == gid) null else gid }, label = { Text(gid) })+                        }+                    }+                }+            }+            if (filtered.isEmpty()) {+                item { Text(text = "No matching achievements", style = MaterialTheme.typography.bodyMedium, modifier = Modifier.padding(16.dp)) }+            }+            items(filtered, key = { "${it.gameId}:${it.achievementId}" }) { ach -> AchievementRow(item = ach, showGameTag = true) }+        }+    }+}
games/hub/src/main/java/com/vayunmathur/games/hub/ui/screens/ActivityFeedScreen.kt
diff --git a/games/hub/src/main/java/com/vayunmathur/games/hub/ui/screens/ActivityFeedScreen.kt b/games/hub/src/main/java/com/vayunmathur/games/hub/ui/screens/ActivityFeedScreen.ktnew file mode 100644index 0000000000..b8d710eefb--- /dev/null+++ b/games/hub/src/main/java/com/vayunmathur/games/hub/ui/screens/ActivityFeedScreen.kt@@ -0,0 +1,51 @@+package com.vayunmathur.games.hub.ui.screens++import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.PaddingValues+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.lazy.LazyColumn+import androidx.compose.foundation.lazy.items+import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.unit.dp+import androidx.lifecycle.compose.collectAsStateWithLifecycle+import com.vayunmathur.games.hub.MainRoute+import com.vayunmathur.games.hub.ui.components.ActivityItemCard+import com.vayunmathur.games.hub.viewmodel.GameHubViewModel+import com.vayunmathur.library.ui.IconNavigation+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.Scaffold+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.TopAppBar+import com.vayunmathur.library.util.NavBackStack++@Composable+fun ActivityFeedScreen(+    viewModel: GameHubViewModel,+    backStack: NavBackStack<MainRoute>? = null,+    onGameClick: ((String) -> Unit)? = null,+    modifier: Modifier = Modifier+) {+    val activity by viewModel.allActivityFlow.collectAsStateWithLifecycle()++    Scaffold(topBar = {+        TopAppBar(+            title = { Text("Activity") },+            navigationIcon = { backStack?.let { IconNavigation(it) } }+        )+    }) { padding ->+        if (activity.isEmpty()) {+            Box(modifier = Modifier.fillMaxSize().padding(padding).padding(16.dp), contentAlignment = Alignment.TopStart) {+                Text("No activity yet — start playing games to see your feed!", style = MaterialTheme.typography.bodyMedium)+            }+        } else {+            LazyColumn(modifier = modifier.fillMaxSize().padding(padding), contentPadding = PaddingValues(16.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {+                items(activity, key = { it.id }) { event -> ActivityItemCard(event = event, onGameClick = onGameClick) }+            }+        }+    }+}
games/hub/src/main/java/com/vayunmathur/games/hub/ui/screens/DashboardScreen.kt
diff --git a/games/hub/src/main/java/com/vayunmathur/games/hub/ui/screens/DashboardScreen.kt b/games/hub/src/main/java/com/vayunmathur/games/hub/ui/screens/DashboardScreen.ktnew file mode 100644index 0000000000..2265e6d4cd--- /dev/null+++ b/games/hub/src/main/java/com/vayunmathur/games/hub/ui/screens/DashboardScreen.kt@@ -0,0 +1,170 @@+package com.vayunmathur.games.hub.ui.screens++import android.content.Context+import android.graphics.drawable.Drawable+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.PaddingValues+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.lazy.LazyColumn+import androidx.compose.foundation.lazy.LazyRow+import androidx.compose.foundation.lazy.items+import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.remember+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.unit.dp+import androidx.lifecycle.compose.collectAsStateWithLifecycle+import com.vayunmathur.games.hub.data.entities.HubGameEntity+import com.vayunmathur.games.hub.ui.components.ActivityItemCard+import com.vayunmathur.games.hub.ui.components.GameCard+import com.vayunmathur.games.hub.ui.components.LevelBadge+import com.vayunmathur.games.hub.ui.components.StatCard+import com.vayunmathur.games.hub.ui.components.StreakCard+import com.vayunmathur.games.hub.ui.components.XpProgressBar+import com.vayunmathur.games.hub.util.GameIconResolver+import com.vayunmathur.games.hub.util.formatPlaytime+import com.vayunmathur.games.hub.viewmodel.GameHubViewModel+import com.vayunmathur.library.ui.BackupButtons+import com.vayunmathur.library.ui.Card+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.Scaffold+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.TextButton+import com.vayunmathur.library.ui.TopAppBar++@Composable+fun DashboardScreen(+    viewModel: GameHubViewModel,+    onGameClick: (String) -> Unit,+    onProfileClick: () -> Unit,+    onActivityClick: () -> Unit,+    onGamesClick: () -> Unit,+    dbConfigs: List<Pair<String, String>>,+    datastoreNames: List<String>,+    modifier: Modifier = Modifier+) {+    val games by viewModel.gamesFlow.collectAsStateWithLifecycle()+    val crossStats by viewModel.statsFlow.collectAsStateWithLifecycle()+    val xp by viewModel.totalXpFlow.collectAsStateWithLifecycle()+    val level by viewModel.levelFlow.collectAsStateWithLifecycle()+    val title by viewModel.titleFlow.collectAsStateWithLifecycle()+    val profile by viewModel.profileFlow.collectAsStateWithLifecycle()+    val recentActivity by viewModel.recentActivityFlow.collectAsStateWithLifecycle()+    val allAchievements by viewModel.allAchievementsFlow.collectAsStateWithLifecycle()+    val sessions by viewModel.sessionsFlow.collectAsStateWithLifecycle()+    val context = LocalContext.current++    val iconCache = remember { mutableMapOf<String, Drawable?>() }+    fun getIcon(pkg: String): Drawable? = iconCache.getOrPut(pkg) { GameIconResolver.resolveAppIcon(context, pkg) }++    val installedMap = remember(games) {+        games.associate { g ->+            g.gameId to try { context.packageManager.getPackageInfo(g.packageName, 0); true } catch (_: Exception) { false }+        }+    }++    val recentlyPlayedGames = remember(sessions, games) {+        val cutoff = System.currentTimeMillis() - 7L * 24 * 60 * 60 * 1000+        sessions.filter { it.startTime >= cutoff }+            .distinctBy { it.gameId }+            .mapNotNull { session -> games.find { g -> g.gameId == session.gameId } }+            .take(10)+    }++    val achievementProgressByGame = remember(allAchievements) {+        allAchievements.groupBy { it.gameId }.mapValues { (_, list) -> list.count { it.isUnlocked } to list.size }+    }++    Scaffold(+        topBar = {+            TopAppBar(+                title = { Text("GameHub", fontWeight = FontWeight.Bold) },+                actions = { BackupButtons(dbConfigs = dbConfigs, datastoreNames = datastoreNames) }+            )+        }+    ) { padding ->+        LazyColumn(+            modifier = modifier.fillMaxSize().padding(padding),+            verticalArrangement = Arrangement.spacedBy(12.dp),+            contentPadding = PaddingValues(16.dp)+        ) {+            item {+                Card(onClick = onProfileClick, modifier = Modifier.fillMaxWidth()) {+                    Row(modifier = Modifier.padding(16.dp), horizontalArrangement = Arrangement.spacedBy(12.dp)) {+                        LevelBadge(level = level, large = true)+                        Column(modifier = Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(4.dp)) {+                            Text(text = profile?.displayName ?: "Player", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold)+                            Text(text = title, style = MaterialTheme.typography.labelMedium, color = MaterialTheme.colorScheme.primary)+                            XpProgressBar(totalXp = xp, modifier = Modifier.fillMaxWidth())+                        }+                    }+                }+            }++            if (crossStats.currentStreak > 0 || crossStats.longestStreak > 0) {+                item { StreakCard(currentStreak = crossStats.currentStreak, longestStreak = crossStats.longestStreak, modifier = Modifier.fillMaxWidth()) }+            }++            item {+                Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp)) {+                    StatCard(label = "Playtime", value = formatPlaytime(crossStats.totalPlaytimeMs), modifier = Modifier.weight(1f))+                    StatCard(label = "Games", value = "${crossStats.totalGames}", modifier = Modifier.weight(1f))+                    StatCard(label = "Achievements", value = "${crossStats.totalAchievementsUnlocked}/${crossStats.totalAchievements}", modifier = Modifier.weight(1f))+                }+            }++            if (recentlyPlayedGames.isNotEmpty()) {+                item {+                    Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically) {+                        Text(text = "Continue playing", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold)+                        TextButton(onClick = onGamesClick) { Text("See all") }+                    }+                }+                item {+                    LazyRow(horizontalArrangement = Arrangement.spacedBy(8.dp)) {+                        items(recentlyPlayedGames, key = { it.gameId }) { game ->+                            GameCard(+                                game = game, isInstalled = installedMap[game.gameId] ?: true,+                                achievementProgress = achievementProgressByGame[game.gameId],+                                iconDrawable = getIcon(game.packageName),+                                onClick = { onGameClick(game.gameId) },+                                onPlay = { launchGame(context, game) },+                                modifier = Modifier.fillParentMaxWidth(0.85f)+                            )+                        }+                    }+                }+            }++            if (recentActivity.isNotEmpty()) {+                item {+                    Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically) {+                        Text(text = "Recent activity", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold)+                        TextButton(onClick = onActivityClick) { Text("See all") }+                    }+                }+                items(recentActivity.take(5), key = { it.id }) { event -> ActivityItemCard(event = event, onGameClick = onGameClick) }+            } else {+                item {+                    Card(modifier = Modifier.fillMaxWidth()) {+                        Text(text = "No activity yet — play a game!", modifier = Modifier.padding(16.dp), style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant)+                    }+                }+            }+        }+    }+}++fun launchGame(context: Context, game: HubGameEntity) {+    try {+        val intent = context.packageManager.getLaunchIntentForPackage(game.packageName)+        if (intent != null) context.startActivity(intent)+    } catch (_: Exception) { }+}
games/hub/src/main/java/com/vayunmathur/games/hub/ui/screens/GameDetailScreen.kt
diff --git a/games/hub/src/main/java/com/vayunmathur/games/hub/ui/screens/GameDetailScreen.kt b/games/hub/src/main/java/com/vayunmathur/games/hub/ui/screens/GameDetailScreen.ktnew file mode 100644index 0000000000..ed6d99ef79--- /dev/null+++ b/games/hub/src/main/java/com/vayunmathur/games/hub/ui/screens/GameDetailScreen.kt@@ -0,0 +1,115 @@+package com.vayunmathur.games.hub.ui.screens++import android.graphics.drawable.Drawable+import androidx.compose.foundation.Image+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.PaddingValues+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.lazy.LazyColumn+import androidx.compose.foundation.lazy.items+import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.remember+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.draw.clip+import androidx.compose.ui.graphics.asImageBitmap+import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.unit.dp+import androidx.core.graphics.drawable.toBitmap+import androidx.lifecycle.compose.collectAsStateWithLifecycle+import com.vayunmathur.games.hub.MainRoute+import com.vayunmathur.games.hub.ui.components.AchievementRow+import com.vayunmathur.games.hub.ui.components.ActivityItemCard+import com.vayunmathur.games.hub.ui.components.StatCard+import com.vayunmathur.games.hub.util.GameIconResolver+import com.vayunmathur.games.hub.util.formatDurationMs+import com.vayunmathur.games.hub.util.formatPlaytime+import com.vayunmathur.games.hub.util.formatRelativeTime+import com.vayunmathur.games.hub.viewmodel.GameHubViewModel+import com.vayunmathur.library.ui.Button+import com.vayunmathur.library.ui.Card+import com.vayunmathur.library.ui.IconNavigation+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.Scaffold+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.TopAppBar+import com.vayunmathur.library.util.NavBackStack++@Composable+fun GameDetailScreen(+    gameId: String,+    viewModel: GameHubViewModel,+    backStack: NavBackStack<MainRoute>,+    modifier: Modifier = Modifier+) {+    val game by viewModel.getGameFlow(gameId).collectAsStateWithLifecycle(initialValue = null)+    val achievements by viewModel.getAchievementsForGameFlow(gameId).collectAsStateWithLifecycle(initialValue = emptyList())+    val sessions by viewModel.getSessionsForGameFlow(gameId).collectAsStateWithLifecycle(initialValue = emptyList())+    val activity by viewModel.getActivityForGameFlow(gameId).collectAsStateWithLifecycle(initialValue = emptyList())+    val context = LocalContext.current++    val iconDrawable: Drawable? = remember(game?.packageName) { game?.packageName?.let { GameIconResolver.resolveAppIcon(context, it) } }+    val isInstalled = remember(game?.packageName) {+        try { if (game?.packageName != null) { context.packageManager.getPackageInfo(game!!.packageName, 0); true } else false } catch (_: Exception) { false }+    }++    Scaffold(topBar = { TopAppBar(title = { Text(game?.displayName ?: gameId) }, navigationIcon = { IconNavigation(backStack) }) }) { padding ->+        val g = game+        if (g == null) {+            Box(modifier = Modifier.fillMaxSize().padding(padding), contentAlignment = Alignment.Center) { Text("Game not found", style = MaterialTheme.typography.bodyLarge) }+            return@Scaffold+        }+        val iconBmp = remember(iconDrawable) { try { iconDrawable?.toBitmap(128,128) } catch (_:Exception){ null } }++        LazyColumn(modifier = modifier.fillMaxSize().padding(padding), contentPadding = PaddingValues(16.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) {+            item {+                Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(16.dp), verticalAlignment = Alignment.CenterVertically) {+                    Box(modifier = Modifier.size(72.dp).clip(RoundedCornerShape(16.dp)), contentAlignment = Alignment.Center) {+                        if (iconBmp != null) Image(bitmap = iconBmp.asImageBitmap(), contentDescription = g.displayName, modifier = Modifier.size(72.dp).clip(RoundedCornerShape(16.dp)))+                        else Text(text = g.displayName.firstOrNull()?.uppercase() ?: "?", style = MaterialTheme.typography.headlineLarge, fontWeight = FontWeight.Bold)+                    }+                    Column(modifier = Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(4.dp)) {+                        Text(text = g.displayName, style = MaterialTheme.typography.headlineSmall, fontWeight = FontWeight.Bold)+                        g.description?.let { Text(text = it, style = MaterialTheme.typography.bodySmall) }+                        Text(text = g.packageName, style = MaterialTheme.typography.labelSmall, color = MaterialTheme.colorScheme.onSurfaceVariant)+                    }+                }+            }+            item { Button(onClick = { launchGame(context, g) }, enabled = isInstalled, modifier = Modifier.fillMaxWidth()) { Text(if (isInstalled) "Play ${g.displayName}" else "Not installed") } }+            item { Row(horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.fillMaxWidth()) {+                StatCard(label = "Playtime", value = formatPlaytime(g.totalPlaytimeMs), modifier = Modifier.weight(1f))+                StatCard(label = "Sessions", value = "${sessions.size}", modifier = Modifier.weight(1f))+                StatCard(label = "Last", value = g.lastPlayedAt?.let { formatRelativeTime(it) } ?: "Never", modifier = Modifier.weight(1f))+            } }+            if (achievements.isNotEmpty()) {+                val unlocked = achievements.count { it.isUnlocked }+                item { Text(text = "Achievements $unlocked/${achievements.size}", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold) }+                items(achievements, key = { it.achievementId }) { ach -> AchievementRow(item = ach, showGameTag = false) }+            }+            if (sessions.isNotEmpty()) {+                item { Text(text = "Recent Sessions", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold) }+                items(sessions.take(10), key = { it.id }) { session ->+                    Card(modifier = Modifier.fillMaxWidth()) {+                        Row(modifier = Modifier.fillMaxWidth().padding(12.dp), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically) {+                            Text(text = formatRelativeTime(session.startTime), style = MaterialTheme.typography.bodySmall)+                            Text(text = session.durationMs?.let { formatDurationMs(it) } ?: "In progress", style = MaterialTheme.typography.labelSmall)+                        }+                    }+                }+            }+            if (activity.isNotEmpty()) {+                item { Text(text = "Activity", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold) }+                items(activity, key = { it.id }) { event -> ActivityItemCard(event = event) }+            }+        }+    }+}
games/hub/src/main/java/com/vayunmathur/games/hub/ui/screens/GamesListScreen.kt
diff --git a/games/hub/src/main/java/com/vayunmathur/games/hub/ui/screens/GamesListScreen.kt b/games/hub/src/main/java/com/vayunmathur/games/hub/ui/screens/GamesListScreen.ktnew file mode 100644index 0000000000..49c0ec9cb7--- /dev/null+++ b/games/hub/src/main/java/com/vayunmathur/games/hub/ui/screens/GamesListScreen.kt@@ -0,0 +1,108 @@+package com.vayunmathur.games.hub.ui.screens++import android.graphics.drawable.Drawable+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.PaddingValues+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.lazy.LazyColumn+import androidx.compose.foundation.lazy.items+import androidx.compose.material.icons.Icons+import androidx.compose.material.icons.filled.MoreVert+import androidx.compose.material3.DropdownMenu+import androidx.compose.material3.DropdownMenuItem+import androidx.compose.material3.Icon+import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.Modifier+import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.unit.dp+import androidx.lifecycle.compose.collectAsStateWithLifecycle+import com.vayunmathur.games.hub.ui.components.GameCard+import com.vayunmathur.games.hub.util.GameIconResolver+import com.vayunmathur.games.hub.viewmodel.GameHubViewModel+import com.vayunmathur.library.ui.CommonSearchBar+import com.vayunmathur.library.ui.IconButton+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.Scaffold+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.TopAppBar++enum class GameSort { LAST_PLAYED, MOST_PLAYED, NAME, COMPLETION }++@Composable+fun GamesListScreen(+    viewModel: GameHubViewModel,+    onGameClick: (String) -> Unit,+    modifier: Modifier = Modifier+) {+    val games by viewModel.gamesFlow.collectAsStateWithLifecycle()+    val allAchievements by viewModel.allAchievementsFlow.collectAsStateWithLifecycle()+    val context = LocalContext.current++    var search by remember { mutableStateOf("") }+    var sort by remember { mutableStateOf(GameSort.LAST_PLAYED) }+    var showSortMenu by remember { mutableStateOf(false) }++    val iconCache = remember { mutableMapOf<String, Drawable?>() }+    fun getIcon(pkg: String): Drawable? = iconCache.getOrPut(pkg) { GameIconResolver.resolveAppIcon(context, pkg) }++    val installedMap = remember(games) {+        games.associate { g ->+            g.gameId to try { context.packageManager.getPackageInfo(g.packageName, 0); true } catch (_: Exception) { false }+        }+    }++    val achievementProgressByGame = remember(allAchievements) {+        allAchievements.groupBy { it.gameId }.mapValues { (_, list) -> list.count { it.isUnlocked } to list.size }+    }++    val filteredSorted = remember(games, search, sort, achievementProgressByGame) {+        var list = if (search.isBlank()) games else games.filter { it.displayName.contains(search, true) || it.gameId.contains(search, true) }+        when (sort) {+            GameSort.LAST_PLAYED -> list.sortedByDescending { it.lastPlayedAt ?: 0L }+            GameSort.MOST_PLAYED -> list.sortedByDescending { it.totalPlaytimeMs }+            GameSort.NAME -> list.sortedBy { it.displayName }+            GameSort.COMPLETION -> list.sortedByDescending { game ->+                val (unlocked, total) = achievementProgressByGame[game.gameId] ?: (0 to 1)+                if (total == 0) 0f else unlocked.toFloat() / total.toFloat().coerceAtLeast(1f)+            }+        }+    }++    Scaffold(+        topBar = {+            TopAppBar(+                title = { Text("Games") },+                actions = {+                    IconButton(onClick = { showSortMenu = true }) { Icon(Icons.Filled.MoreVert, contentDescription = "Sort") }+                    DropdownMenu(expanded = showSortMenu, onDismissRequest = { showSortMenu = false }) {+                        DropdownMenuItem(text = { Text("Last played") }, onClick = { sort = GameSort.LAST_PLAYED; showSortMenu = false })+                        DropdownMenuItem(text = { Text("Most played") }, onClick = { sort = GameSort.MOST_PLAYED; showSortMenu = false })+                        DropdownMenuItem(text = { Text("Name") }, onClick = { sort = GameSort.NAME; showSortMenu = false })+                        DropdownMenuItem(text = { Text("Completion") }, onClick = { sort = GameSort.COMPLETION; showSortMenu = false })+                    }+                }+            )+        }+    ) { padding ->+        LazyColumn(modifier = modifier.fillMaxSize().padding(padding), contentPadding = PaddingValues(16.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {+            item { CommonSearchBar(value = search, onValueChange = { search = it }, placeholder = "Search games", padding = PaddingValues(0.dp)) }+            if (filteredSorted.isEmpty()) {+                item { Text(text = if (search.isNotEmpty()) "No matching games" else "No games registered yet.\nPlay a game to see it here.", style = MaterialTheme.typography.bodyMedium, modifier = Modifier.padding(top = 32.dp)) }+            }+            items(filteredSorted, key = { it.gameId }) { game ->+                GameCard(+                    game = game, isInstalled = installedMap[game.gameId] ?: false,+                    achievementProgress = achievementProgressByGame[game.gameId],+                    iconDrawable = getIcon(game.packageName),+                    onClick = { onGameClick(game.gameId) },+                    onPlay = { launchGame(context, game) }+                )+            }+        }+    }+}
games/hub/src/main/java/com/vayunmathur/games/hub/ui/screens/ProfileScreen.kt
diff --git a/games/hub/src/main/java/com/vayunmathur/games/hub/ui/screens/ProfileScreen.kt b/games/hub/src/main/java/com/vayunmathur/games/hub/ui/screens/ProfileScreen.ktnew file mode 100644index 0000000000..f7ac729706--- /dev/null+++ b/games/hub/src/main/java/com/vayunmathur/games/hub/ui/screens/ProfileScreen.kt@@ -0,0 +1,152 @@+package com.vayunmathur.games.hub.ui.screens++import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.PaddingValues+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.lazy.LazyColumn+import androidx.compose.foundation.lazy.LazyRow+import androidx.compose.foundation.lazy.items+import androidx.compose.material.icons.Icons+import androidx.compose.material.icons.filled.Person+import androidx.compose.material3.FilterChip+import androidx.compose.material3.Icon as M3Icon+import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.unit.dp+import androidx.lifecycle.compose.collectAsStateWithLifecycle+import com.vayunmathur.games.hub.ui.components.LevelBadge+import com.vayunmathur.games.hub.ui.components.StatCard+import com.vayunmathur.games.hub.ui.components.XpProgressBar+import com.vayunmathur.games.hub.util.XpLevelCalculator+import com.vayunmathur.games.hub.util.formatPlaytime+import com.vayunmathur.games.hub.viewmodel.GameHubViewModel+import com.vayunmathur.library.ui.AlertDialog+import com.vayunmathur.library.ui.Button+import com.vayunmathur.library.ui.Card+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.OutlinedTextField+import com.vayunmathur.library.ui.Scaffold+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.TextButton+import com.vayunmathur.library.ui.TopAppBar++private val avatarOptions = listOf(+    "person", "stadia_controller", "sports_esports", "emoji_events", "military_tech",+    "star", "bolt", "local_fire_department", "rocket", "diamond",+    "psychology", "lightbulb", "school", "workspace_premium", "king_bed"+)++@Composable+fun ProfileScreen(viewModel: GameHubViewModel, modifier: Modifier = Modifier) {+    val profile by viewModel.profileFlow.collectAsStateWithLifecycle()+    val xp by viewModel.totalXpFlow.collectAsStateWithLifecycle()+    val level by viewModel.levelFlow.collectAsStateWithLifecycle()+    val title by viewModel.titleFlow.collectAsStateWithLifecycle()+    val crossStats by viewModel.statsFlow.collectAsStateWithLifecycle()++    var showEditDialog by remember { mutableStateOf(false) }+    var editName by remember { mutableStateOf("") }+    var selectedAvatar by remember { mutableStateOf<String?>(null) }++    if (showEditDialog && editName.isEmpty() && profile != null) {+        editName = profile?.displayName ?: ""+        selectedAvatar = profile?.avatarSymbol+    }++    Scaffold(topBar = {+        TopAppBar(+            title = { Text("Profile") },+            actions = {+                androidx.compose.material3.IconButton(onClick = {+                    editName = profile?.displayName ?: ""+                    selectedAvatar = profile?.avatarSymbol+                    showEditDialog = true+                }) { M3Icon(Icons.Filled.Person, contentDescription = "Edit") }+            }+        )+    }) { padding ->+        LazyColumn(modifier = modifier.fillMaxSize().padding(padding), contentPadding = PaddingValues(16.dp), verticalArrangement = Arrangement.spacedBy(16.dp)) {+            item {+                Card(modifier = Modifier.fillMaxWidth()) {+                    Column(modifier = Modifier.padding(24.dp).fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(12.dp), horizontalAlignment = Alignment.CenterHorizontally) {+                        LevelBadge(level = level, large = true)+                        Text(text = profile?.displayName ?: "Player", style = MaterialTheme.typography.headlineSmall, fontWeight = FontWeight.Bold)+                        Text(text = title, style = MaterialTheme.typography.titleMedium, color = MaterialTheme.colorScheme.primary)+                        Text(text = "Level $level", style = MaterialTheme.typography.labelLarge)+                        XpProgressBar(totalXp = xp, modifier = Modifier.fillMaxWidth())+                    }+                }+            }+            item { Text(text = "Stats", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold) }+            item {+                Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp)) {+                    StatCard(label = "Playtime", value = formatPlaytime(crossStats.totalPlaytimeMs), modifier = Modifier.weight(1f))+                    StatCard(label = "Sessions", value = "${crossStats.totalSessions}", modifier = Modifier.weight(1f))+                }+            }+            item {+                Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp)) {+                    StatCard(label = "Achievements", value = "${crossStats.totalAchievementsUnlocked}/${crossStats.totalAchievements}", modifier = Modifier.weight(1f))+                    StatCard(label = "Games", value = "${crossStats.totalGames}", modifier = Modifier.weight(1f))+                }+            }+            item {+                Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp)) {+                    StatCard(label = "XP", value = "$xp", modifier = Modifier.weight(1f))+                    StatCard(label = "Best streak", value = "${crossStats.longestStreak}d", modifier = Modifier.weight(1f))+                }+            }+            item { Text(text = "Level table", style = MaterialTheme.typography.titleSmall, fontWeight = FontWeight.Bold) }+            items((1..maxOf(level + 2, 10)).toList(), key = { it }) { lvl ->+                val lvlXp = XpLevelCalculator.xpForLevel(lvl)+                val isCurrent = lvl == level+                Card(+                    modifier = Modifier.fillMaxWidth(),+                    colors = if (isCurrent) androidx.compose.material3.CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.primaryContainer)+                    else androidx.compose.material3.CardDefaults.cardColors()+                ) {+                    Row(modifier = Modifier.fillMaxWidth().padding(12.dp), horizontalArrangement = Arrangement.SpaceBetween) {+                        Text(text = "Level $lvl — ${XpLevelCalculator.title(lvl)}${if (isCurrent) " (you)" else ""}", fontWeight = if (isCurrent) FontWeight.Bold else FontWeight.Normal)+                        Text(text = "$lvlXp XP", style = MaterialTheme.typography.labelSmall)+                    }+                }+            }+        }++        if (showEditDialog) {+            AlertDialog(+                onDismissRequest = { showEditDialog = false; editName = "" },+                title = { Text("Edit profile") },+                text = {+                    Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {+                        OutlinedTextField(value = editName, onValueChange = { editName = it }, label = { Text("Display name") }, singleLine = true)+                        Text(text = "Avatar", style = MaterialTheme.typography.labelMedium)+                        LazyRow(horizontalArrangement = Arrangement.spacedBy(8.dp)) {+                            items(avatarOptions) { sym ->+                                FilterChip(selected = selectedAvatar == sym, onClick = { selectedAvatar = if (selectedAvatar == sym) null else sym }, label = { Text(sym) })+                            }+                        }+                    }+                },+                confirmButton = {+                    Button(onClick = {+                        if (editName.isNotBlank()) viewModel.updateDisplayName(editName.trim())+                        viewModel.updateAvatarSymbol(selectedAvatar)+                        showEditDialog = false; editName = ""+                    }) { Text("Save") }+                },+                dismissButton = { TextButton(onClick = { showEditDialog = false; editName = "" }) { Text("Cancel") } }+            )+        }+    }+}
games/hub/src/main/java/com/vayunmathur/games/hub/ui/screens/SettingsScreen.kt
diff --git a/games/hub/src/main/java/com/vayunmathur/games/hub/ui/screens/SettingsScreen.kt b/games/hub/src/main/java/com/vayunmathur/games/hub/ui/screens/SettingsScreen.ktnew file mode 100644index 0000000000..eb0d7c9812--- /dev/null+++ b/games/hub/src/main/java/com/vayunmathur/games/hub/ui/screens/SettingsScreen.kt@@ -0,0 +1,78 @@+package com.vayunmathur.games.hub.ui.screens++import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.PaddingValues+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.lazy.LazyColumn+import androidx.compose.material3.HorizontalDivider+import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.Modifier+import androidx.compose.ui.unit.dp+import com.vayunmathur.games.hub.MainRoute+import com.vayunmathur.games.hub.viewmodel.GameHubViewModel+import com.vayunmathur.library.ui.AlertDialog+import com.vayunmathur.library.ui.BackupButtons+import com.vayunmathur.library.ui.Button+import com.vayunmathur.library.ui.IconNavigation+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.OutlinedButton+import com.vayunmathur.library.ui.Scaffold+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.TopAppBar+import com.vayunmathur.library.util.NavBackStack++@Composable+fun SettingsScreen(+    viewModel: GameHubViewModel,+    backStack: NavBackStack<MainRoute>,+    dbConfigs: List<Pair<String, String>>,+    datastoreNames: List<String>,+    modifier: Modifier = Modifier+) {+    var showClearConfirm by remember { mutableStateOf(false) }++    Scaffold(topBar = { TopAppBar(title = { Text("Settings") }, navigationIcon = { IconNavigation(backStack) }) }) { padding ->+        LazyColumn(modifier = modifier.fillMaxSize().padding(padding), contentPadding = PaddingValues(16.dp), verticalArrangement = Arrangement.spacedBy(16.dp)) {+            item {+                Text(text = "Backup & Restore", style = MaterialTheme.typography.titleMedium)+                Row(horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.padding(top = 8.dp)) {+                    BackupButtons(dbConfigs = dbConfigs, datastoreNames = datastoreNames)+                }+            }+            item { HorizontalDivider() }+            item {+                Text(text = "Data", style = MaterialTheme.typography.titleMedium)+                Column(verticalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.padding(top = 8.dp)) {+                    Text(text = "Clear hub cache — removes all cached game data. Games will re-sync on next launch.", style = MaterialTheme.typography.bodySmall)+                    OutlinedButton(onClick = { showClearConfirm = true }, modifier = Modifier.fillMaxWidth()) { Text("Clear cache") }+                }+            }+            item { HorizontalDivider() }+            item {+                Text(text = "About GameHub", style = MaterialTheme.typography.titleMedium)+                Column(verticalArrangement = Arrangement.spacedBy(4.dp), modifier = Modifier.padding(top = 8.dp)) {+                    Text(text = "GameHub aggregates achievements, playtime, and activity across all registered games. Games remain source of truth — hub keeps a mirrored cache pushed via SDK. No leaderboards for now.", style = MaterialTheme.typography.bodySmall)+                    Text(text = "Package: com.vayunmathur.games.hub", style = MaterialTheme.typography.labelSmall, color = MaterialTheme.colorScheme.onSurfaceVariant)+                }+            }+        }++        if (showClearConfirm) {+            AlertDialog(+                onDismissRequest = { showClearConfirm = false },+                title = { Text("Clear cache?") },+                text = { Text("This will delete all cached games, achievements, sessions, and activity. Games will re-register on next launch.") },+                confirmButton = { Button(onClick = { viewModel.clearAllData(); showClearConfirm = false }) { Text("Clear") } },+                dismissButton = { com.vayunmathur.library.ui.TextButton(onClick = { showClearConfirm = false }) { Text("Cancel") } }+            )+        }+    }+}
games/hub/src/main/java/com/vayunmathur/games/hub/util/AppBackupAgent.kt
diff --git a/games/hub/src/main/java/com/vayunmathur/games/hub/util/AppBackupAgent.kt b/games/hub/src/main/java/com/vayunmathur/games/hub/util/AppBackupAgent.ktnew file mode 100644index 0000000000..7f4ad299bf--- /dev/null+++ b/games/hub/src/main/java/com/vayunmathur/games/hub/util/AppBackupAgent.kt@@ -0,0 +1,27 @@+package com.vayunmathur.games.hub.util++import com.vayunmathur.games.hub.data.DB_NAME+import com.vayunmathur.library.room.SqlCipherDbCodec+import com.vayunmathur.library.util.BaseBackupAgent+import com.vayunmathur.library.util.DatabaseHelper+import java.io.File++class AppBackupAgent : BaseBackupAgent() {+    override val dbCodec = SqlCipherDbCodec++    override val dbConfigs: List<Pair<String, String>>+        get() {+            return try {+                val pass = DatabaseHelper(this).getPassphrase()+                listOf(DB_NAME to pass)+            } catch (_: Exception) {+                emptyList()+            }+        }++    override val datastoreNames: List<String>+        get() = listOf("datastore_default")++    override val extraFiles: List<File>+        get() = emptyList()+}
games/hub/src/main/java/com/vayunmathur/games/hub/util/FormatUtils.kt
diff --git a/games/hub/src/main/java/com/vayunmathur/games/hub/util/FormatUtils.kt b/games/hub/src/main/java/com/vayunmathur/games/hub/util/FormatUtils.ktnew file mode 100644index 0000000000..d04ad650e4--- /dev/null+++ b/games/hub/src/main/java/com/vayunmathur/games/hub/util/FormatUtils.kt@@ -0,0 +1,49 @@+package com.vayunmathur.games.hub.util++import androidx.compose.ui.graphics.Color+import java.util.concurrent.TimeUnit++fun formatPlaytime(ms: Long): String {+    if (ms <= 0) return "0m"+    val hours = TimeUnit.MILLISECONDS.toHours(ms)+    val minutes = TimeUnit.MILLISECONDS.toMinutes(ms) % 60+    return when {+        hours > 0 -> "${hours}h ${minutes}m"+        minutes > 0 -> "${minutes}m"+        else -> "<1m"+    }+}++fun formatDurationMs(ms: Long): String {+    if (ms <= 0) return "0s"+    val seconds = TimeUnit.MILLISECONDS.toSeconds(ms)+    val minutes = seconds / 60+    val hours = minutes / 60+    return when {+        hours > 0 -> "${hours}h ${minutes % 60}m"+        minutes > 0 -> "${minutes}m ${seconds % 60}s"+        else -> "${seconds}s"+    }+}++fun formatRelativeTime(timestamp: Long, now: Long = System.currentTimeMillis()): String {+    val diff = now - timestamp+    if (diff < 0) return "now"+    val minutes = TimeUnit.MILLISECONDS.toMinutes(diff)+    val hours = TimeUnit.MILLISECONDS.toHours(diff)+    val days = TimeUnit.MILLISECONDS.toDays(diff)+    return when {+        minutes < 1 -> "just now"+        minutes < 60 -> "${minutes}m ago"+        hours < 24 -> "${hours}h ago"+        days < 7 -> "${days}d ago"+        else -> java.text.SimpleDateFormat("MMM d", java.util.Locale.getDefault()).format(java.util.Date(timestamp))+    }+}++fun tierColor(tier: String): Color = when (tier.uppercase()) {+    "PLATINUM" -> Color(0xFF9C27B0)+    "GOLD" -> Color(0xFFFFD700)+    "SILVER" -> Color(0xFF9E9E9E)+    else -> Color(0xFFCD7F32)+}
games/hub/src/main/java/com/vayunmathur/games/hub/util/GameIconResolver.kt
diff --git a/games/hub/src/main/java/com/vayunmathur/games/hub/util/GameIconResolver.kt b/games/hub/src/main/java/com/vayunmathur/games/hub/util/GameIconResolver.ktnew file mode 100644index 0000000000..a96e1bc05b--- /dev/null+++ b/games/hub/src/main/java/com/vayunmathur/games/hub/util/GameIconResolver.kt@@ -0,0 +1,18 @@+package com.vayunmathur.games.hub.util++import android.content.Context+import android.content.pm.PackageManager+import android.graphics.drawable.Drawable++object GameIconResolver {++    fun resolveAppIcon(context: Context, packageName: String): Drawable? {+        return try {+            context.packageManager.getApplicationIcon(packageName)+        } catch (_: PackageManager.NameNotFoundException) {+            null+        } catch (_: Exception) {+            null+        }+    }+}
games/hub/src/main/java/com/vayunmathur/games/hub/util/StreakCalculator.kt
diff --git a/games/hub/src/main/java/com/vayunmathur/games/hub/util/StreakCalculator.kt b/games/hub/src/main/java/com/vayunmathur/games/hub/util/StreakCalculator.ktnew file mode 100644index 0000000000..567fc46207--- /dev/null+++ b/games/hub/src/main/java/com/vayunmathur/games/hub/util/StreakCalculator.kt@@ -0,0 +1,81 @@+package com.vayunmathur.games.hub.util++import com.vayunmathur.games.hub.data.entities.PlaySessionEntity+import java.util.Calendar+import java.util.concurrent.TimeUnit++object StreakCalculator {++    data class StreakResult(+        val currentStreak: Int,+        val longestStreak: Int+    )++    fun calculate(+        sessions: List<PlaySessionEntity>,+        minSessionMs: Long = 60_000L,+        now: Long = System.currentTimeMillis()+    ): StreakResult {+        if (sessions.isEmpty()) return StreakResult(0, 0)++        val qualifyingDays = mutableSetOf<Long>()+        for (s in sessions) {+            val qualifies = when {+                s.durationMs != null -> s.durationMs >= minSessionMs+                s.endTime != null -> true+                else -> false+            }+            if (!qualifies) continue+            qualifyingDays.add(dayStart(s.startTime))+        }++        if (qualifyingDays.isEmpty()) return StreakResult(0, 0)++        val sortedDays = qualifyingDays.sorted()++        var maxStreak = 1+        var curRun = 1+        for (i in 1 until sortedDays.size) {+            if (sortedDays[i] - sortedDays[i - 1] == TimeUnit.DAYS.toMillis(1)) {+                curRun+++                if (curRun > maxStreak) maxStreak = curRun+            } else {+                curRun = 1+            }+        }++        val todayStart = dayStart(now)+        val yesterdayStart = todayStart - TimeUnit.DAYS.toMillis(1)++        var currentStreak = 0+        val lastDay = sortedDays.last()+        if (lastDay == todayStart || lastDay == yesterdayStart) {+            currentStreak = 1+            var idx = sortedDays.lastIndex - 1+            var expectedDay = lastDay - TimeUnit.DAYS.toMillis(1)+            while (idx >= 0) {+                if (sortedDays[idx] == expectedDay) {+                    currentStreak+++                    expectedDay -= TimeUnit.DAYS.toMillis(1)+                    idx--+                } else if (sortedDays[idx] < expectedDay) {+                    break+                } else {+                    idx--+                }+            }+        }++        return StreakResult(currentStreak, maxStreak)+    }++    private fun dayStart(millis: Long): Long {+        val cal = Calendar.getInstance()+        cal.timeInMillis = millis+        cal.set(Calendar.HOUR_OF_DAY, 0)+        cal.set(Calendar.MINUTE, 0)+        cal.set(Calendar.SECOND, 0)+        cal.set(Calendar.MILLISECOND, 0)+        return cal.timeInMillis+    }+}
games/hub/src/main/java/com/vayunmathur/games/hub/util/XpLevelCalculator.kt
diff --git a/games/hub/src/main/java/com/vayunmathur/games/hub/util/XpLevelCalculator.kt b/games/hub/src/main/java/com/vayunmathur/games/hub/util/XpLevelCalculator.ktnew file mode 100644index 0000000000..b3cc073f96--- /dev/null+++ b/games/hub/src/main/java/com/vayunmathur/games/hub/util/XpLevelCalculator.kt@@ -0,0 +1,49 @@+package com.vayunmathur.games.hub.util++import kotlin.math.floor+import kotlin.math.sqrt++/**+ * XP/Level system mirroring Play Games.+ * Formula: level = floor(sqrt(totalXp / 100)) + 1+ * L1=0xp, L2=100, L3=400, L4=900, L5=1600...+ * 7 games * ~7 achievements avg 25xp ~=1225 XP => L4.+ */+object XpLevelCalculator {++    fun level(totalXp: Int): Int {+        if (totalXp <= 0) return 1+        return floor(sqrt(totalXp.toDouble() / 100.0)).toInt() + 1+    }++    fun xpForLevel(level: Int): Int {+        if (level <= 1) return 0+        val l = level - 1+        return l * l * 100+    }++    fun xpToNextLevel(totalXp: Int): Int {+        val currentLevel = level(totalXp)+        val nextLevelXp = xpForLevel(currentLevel + 1)+        return nextLevelXp - totalXp+    }++    fun progressToNextLevel(totalXp: Int): Float {+        val currentLevel = level(totalXp)+        val currentLevelXp = xpForLevel(currentLevel)+        val nextLevelXp = xpForLevel(currentLevel + 1)+        val range = (nextLevelXp - currentLevelXp).toFloat()+        if (range <= 0f) return 1f+        return ((totalXp - currentLevelXp).toFloat() / range).coerceIn(0f, 1f)+    }++    fun title(level: Int): String = when {+        level >= 25 -> "Legend"+        level >= 18 -> "Grandmaster"+        level >= 12 -> "Master"+        level >= 8 -> "Enthusiast"+        level >= 4 -> "Casual Gamer"+        level >= 2 -> "Novice"+        else -> "Beginner"+    }+}
games/hub/src/main/java/com/vayunmathur/games/hub/viewmodel/GameHubViewModel.kt
diff --git a/games/hub/src/main/java/com/vayunmathur/games/hub/viewmodel/GameHubViewModel.kt b/games/hub/src/main/java/com/vayunmathur/games/hub/viewmodel/GameHubViewModel.ktnew file mode 100644index 0000000000..a5a278982e--- /dev/null+++ b/games/hub/src/main/java/com/vayunmathur/games/hub/viewmodel/GameHubViewModel.kt@@ -0,0 +1,203 @@+package com.vayunmathur.games.hub.viewmodel++import android.app.Application+import androidx.lifecycle.AndroidViewModel+import androidx.lifecycle.ViewModel+import androidx.lifecycle.ViewModelProvider+import androidx.lifecycle.viewModelScope+import com.vayunmathur.games.hub.data.GamesHubDatabase+import com.vayunmathur.games.hub.data.dao.AchievementWithProgress+import com.vayunmathur.games.hub.data.entities.ActivityEventEntity+import com.vayunmathur.games.hub.data.entities.HubGameEntity+import com.vayunmathur.games.hub.data.entities.PlayerProfileEntity+import com.vayunmathur.games.hub.data.entities.PlaySessionEntity+import com.vayunmathur.games.hub.util.StreakCalculator+import com.vayunmathur.games.hub.util.XpLevelCalculator+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.flow.Flow+import kotlinx.coroutines.flow.SharingStarted+import kotlinx.coroutines.flow.StateFlow+import kotlinx.coroutines.flow.combine+import kotlinx.coroutines.flow.map+import kotlinx.coroutines.flow.stateIn+import kotlinx.coroutines.launch++data class CrossGameStats(+    val totalPlaytimeMs: Long = 0L,+    val totalSessions: Int = 0,+    val totalGames: Int = 0,+    val totalAchievementsUnlocked: Int = 0,+    val totalAchievements: Int = 0,+    val totalXp: Int = 0,+    val level: Int = 1,+    val currentStreak: Int = 0,+    val longestStreak: Int = 0+)++class GameHubViewModel(+    application: Application,+    private val db: GamesHubDatabase+) : AndroidViewModel(application) {++    val gamesFlow: StateFlow<List<HubGameEntity>> =+        db.gameDao().flowAll()+            .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptyList())++    val totalPlaytimeFromGamesFlow: StateFl

Diff truncated.