package io.unom.punktfunk

import androidx.activity.compose.BackHandler
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.unit.dp

/**
 * Open-source licenses: punktfunk's own license (MIT OR Apache-2.0) plus the third-party software
 * notices, read from the bundled `THIRD-PARTY-NOTICES.txt` asset (generated by
 * scripts/gen-third-party-notices.sh). Reached from [SettingsScreen]; Back returns there.
 */
@Composable
fun LicensesScreen(onBack: () -> Unit) {
    val context = LocalContext.current
    BackHandler(onBack = onBack)

    val notices = remember {
        runCatching {
            context.assets.open("THIRD-PARTY-NOTICES.txt").bufferedReader().use { it.readText() }
        }.getOrDefault("Third-party notices unavailable.")
    }
    val version = remember {
        runCatching {
            @Suppress("DEPRECATION")
            context.packageManager.getPackageInfo(context.packageName, 0).versionName
        }.getOrNull()
    }

    Column(
        modifier = Modifier
            .fillMaxSize()
            .verticalScroll(rememberScrollState())
            .padding(horizontal = 20.dp, vertical = 24.dp),
        verticalArrangement = Arrangement.spacedBy(16.dp),
    ) {
        Text("Open-source licenses", style = MaterialTheme.typography.headlineMedium)
        if (version != null) {
            Text(
                "punktfunk $version",
                style = MaterialTheme.typography.bodyMedium,
                color = MaterialTheme.colorScheme.onSurfaceVariant,
            )
        }
        Text(
            "punktfunk is licensed under MIT OR Apache-2.0, at your option. It uses the open-source " +
                "components below, each under its own license.",
            style = MaterialTheme.typography.bodyMedium,
        )
        Text(
            notices,
            style = MaterialTheme.typography.bodySmall.copy(fontFamily = FontFamily.Monospace),
        )
    }
}
