package com.joe.camera.webcam.ui

import android.widget.Toast
import androidx.compose.runtime.*
import androidx.compose.ui.platform.LocalContext
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.rememberNavController
import com.joe.camera.webcam.MainViewModel
import com.joe.camera.webcam.model.MediaKind

@Composable
fun WebCamApp(viewModel: MainViewModel) {
    WebCamTheme {
        val nav = rememberNavController()
        val state by viewModel.uiState.collectAsStateWithLifecycle()
        val context = LocalContext.current
        LaunchedEffect(state.message) { state.message?.let { Toast.makeText(context, it, Toast.LENGTH_SHORT).show(); viewModel.clearMessage() } }
        NavHost(navController = nav, startDestination = "home") {
            composable("home") { HomeScreen(viewModel, state, onMedia = { nav.navigate("media") }) }
            composable("media") { MediaGridScreen(viewModel, state.media, onBack = nav::popBackStack, onOpen = { item -> viewModel.selectMedia(item); nav.navigate(if (item.kind == MediaKind.IMAGE) "image" else "video") }) }
            composable("image") { ImageViewerScreen(viewModel, onBack = nav::popBackStack) }
            composable("video") { VideoViewerScreen(viewModel, onBack = nav::popBackStack) }
        }
    }
}
