package dev.privacyllc.period.feature.common

import androidx.activity.ComponentActivity
import androidx.compose.material3.Text
import androidx.compose.ui.test.assertIsDisplayed
import androidx.compose.ui.test.junit4.createAndroidComposeRule
import androidx.compose.ui.test.onNodeWithContentDescription
import androidx.compose.ui.test.onNodeWithText
import androidx.compose.ui.test.performClick
import dev.privacyllc.period.R
import dev.privacyllc.period.designsystem.PeriodTheme
import org.junit.Assert.assertEquals
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config

/**
 * The one piece of chrome every screen below a tab shares.
 *
 * Before it, a grep for `TopAppBar`, `navigationIcon` and `popBackStack` across
 * the whole app returned nothing: no screen had a way back that a user could
 * see, and App lock had a headline that looked like a bar without being one.
 * This asserts the arrow exists, says "Back" to a screen reader, and does
 * something when tapped — the three things a label cannot do.
 */
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [34])
class SettingsSubpageTest {

    @get:Rule val rule = createAndroidComposeRule<ComponentActivity>()

    private val back get() = rule.activity.getString(R.string.action_back)

    @Test fun `it offers a back arrow that a screen reader can name`() {
        rule.setContent { PeriodTheme { SettingsSubpage("App lock", onBack = {}) { Text("body") } } }

        rule.onNodeWithContentDescription(back).assertIsDisplayed()
    }

    @Test fun `tapping the arrow goes back exactly once`() {
        var backs = 0
        rule.setContent { PeriodTheme { SettingsSubpage("App lock", onBack = { backs++ }) { Text("body") } } }

        rule.onNodeWithContentDescription(back).performClick()

        assertEquals(1, backs)
    }

    @Test fun `it names where you are, and still shows what you came for`() {
        rule.setContent { PeriodTheme { SettingsSubpage("Reminders and privacy", onBack = {}) { Text("body") } } }

        rule.onNodeWithText("Reminders and privacy").assertIsDisplayed()
        rule.onNodeWithText("body").assertIsDisplayed()
    }
}
