/*
 * Book's Story — free and open-source Material You eBook reader.
 * Copyright (C) 2024-2026 Acclorite
 * SPDX-License-Identifier: GPL-3.0-only
 */

package org.dueattendant149.bookshelf.ui.about

import android.content.Intent
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.core.net.toUri
import kotlinx.coroutines.flow.SharedFlow
import org.dueattendant149.bookshelf.R
import org.dueattendant149.bookshelf.presentation.about.AboutEffect
import org.dueattendant149.bookshelf.presentation.credits.CreditsScreen
import org.dueattendant149.bookshelf.presentation.licenses.LicensesScreen
import org.dueattendant149.bookshelf.ui.common.helpers.LocalActivity
import org.dueattendant149.bookshelf.ui.common.helpers.launchActivity
import org.dueattendant149.bookshelf.ui.common.helpers.showToast
import org.dueattendant149.bookshelf.ui.navigator.LocalNavigator

@Composable
fun AboutEffects(effects: SharedFlow<AboutEffect>) {
    val navigator = LocalNavigator.current
    val activity = LocalActivity.current

    LaunchedEffect(effects, activity, navigator) {
        effects.collect { effect ->
            when (effect) {
                is AboutEffect.OnNavigateToBrowserPage -> {
                    val intent = Intent(
                        Intent.ACTION_VIEW,
                        effect.page.toUri()
                    )

                    intent.launchActivity(activity) {
                        activity.getString(R.string.error_no_browser)
                            .showToast(context = activity, longToast = false)
                    }
                }

                is AboutEffect.OnNavigateToLicenses -> {
                    navigator.push(LicensesScreen)
                }

                is AboutEffect.OnNavigateToCredits -> {
                    navigator.push(CreditsScreen)
                }

                is AboutEffect.OnNavigateBack -> {
                    navigator.pop()
                }
            }
        }
    }
}