package com.keylightpiano.pianotimeline

import android.content.Intent
import android.net.Uri
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.activity.viewModels
import com.keylightpiano.pianotimeline.ui.RecordingListScreen
import com.keylightpiano.pianotimeline.ui.RecordingListViewModel
import com.keylightpiano.pianotimeline.ui.theme.PianoTimelineTheme

class MainActivity : ComponentActivity() {

    // Hoist the ViewModel to the Activity so deep-link intents (which arrive here)
    // can be forwarded to it. The Compose screen uses this same instance.
    private val vm: RecordingListViewModel by viewModels()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()

        // Cold start: an intent may already carry a deep link.
        handleIntent(intent)

        setContent {
            // Force dark mode regardless of system setting
            PianoTimelineTheme(darkTheme = true) {
                RecordingListScreen(vm = vm)
            }
        }
    }

    // Warm start: app already running, a new link arrives.
    override fun onNewIntent(intent: Intent) {
        super.onNewIntent(intent)
        setIntent(intent)
        handleIntent(intent)
    }

    private fun handleIntent(intent: Intent?) {
        val data: Uri = intent?.data ?: return
        if (intent.action == Intent.ACTION_VIEW) {
            vm.handleDeepLink(data)
        }
    }
}
