//
//  StabilityTests.swift
//  Tests iOS
//
//  Full navigation stability tests — visit every screen without crash.
//

import XCTest

final class StabilityTests: BaseUITestCase {
    override var seedFixture: String? { "week_of_moods" }

    /// TC-152: Navigate to every screen and feature without crashing.
    func testFullNavigation_NoCrash() {
        let tabBar = TabBarScreen(app: app)

        // 1. Day tab (default) - verify loaded
        assertTabSelected(tabBar.dayTab, name: "Day (initial)")
        captureScreenshot(name: "stability_day")

        // 2. Open entry detail
        let firstEntry = app.firstEntryRow
        if firstEntry.waitForExistence(timeout: 5) {
            firstEntry.tapWhenReady()
            let detailScreen = EntryDetailScreen(app: app)
            if detailScreen.sheet.waitForExistence(timeout: 3) {
                captureScreenshot(name: "stability_entry_detail")
                detailScreen.dismiss()
                detailScreen.assertDismissed()
            }
        }

        // 3. Month tab
        tabBar.tapMonth()
        assertTabSelected(tabBar.monthTab, name: "Month")
        captureScreenshot(name: "stability_month")

        // 4. Year tab
        tabBar.tapYear()
        assertTabSelected(tabBar.yearTab, name: "Year")
        captureScreenshot(name: "stability_year")

        // 5. Insights tab
        tabBar.tapInsights()
        assertTabSelected(tabBar.insightsTab, name: "Insights")
        captureScreenshot(name: "stability_insights")

        // 6. Settings tab - Customize sub-tab
        tabBar.tapSettings()
        assertTabSelected(tabBar.settingsTab, name: "Settings")
        captureScreenshot(name: "stability_settings_customize")

        // 7. Settings tab - Settings sub-tab
        let settingsScreen = SettingsScreen(app: app)
        settingsScreen.tapSettingsTab()
        captureScreenshot(name: "stability_settings_settings")

        // 8. Back to Customize sub-tab
        settingsScreen.tapCustomizeTab()
        captureScreenshot(name: "stability_settings_customize_return")

        // 9. Back to Day
        tabBar.tapDay()
        assertTabSelected(tabBar.dayTab, name: "Day")

        captureScreenshot(name: "stability_full_navigation_complete")
    }

    /// Wait for a tab to become selected (iOS 26 Liquid Glass may delay state updates).
    private func assertTabSelected(_ tab: XCUIElement, name: String, timeout: TimeInterval = 8) {
        let predicate = NSPredicate(format: "isSelected == true")
        let expectation = XCTNSPredicateExpectation(predicate: predicate, object: tab)
        let result = XCTWaiter.wait(for: [expectation], timeout: timeout)
        XCTAssertEqual(result, .completed, "\(name) tab should be selected")
    }
}
