//
//  AppLaunchTests.swift
//  Tests iOS
//
//  App launch and tab bar navigation tests.
//

import XCTest

final class AppLaunchTests: BaseUITestCase {
    override var seedFixture: String? { "empty" }

    /// Verify the app launches to the Day tab and all 5 tabs are visible.
    func testAppLaunches_TabBarVisible() {
        let tabBar = TabBarScreen(app: app)
        tabBar.assertTabBarVisible()

        // All 5 tabs should exist
        XCTAssertTrue(tabBar.dayTab.exists, "Day tab should exist")
        XCTAssertTrue(tabBar.monthTab.exists, "Month tab should exist")
        XCTAssertTrue(tabBar.yearTab.exists, "Year tab should exist")
        XCTAssertTrue(tabBar.insightsTab.exists, "Insights tab should exist")
        XCTAssertTrue(tabBar.settingsTab.exists, "Settings tab should exist")

        captureScreenshot(name: "app_launched")
    }

    /// Navigate through every tab and verify each loads.
    func testTabNavigation_AllTabsAccessible() {
        let tabBar = TabBarScreen(app: app)

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

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

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

        // Settings tab
        tabBar.tapSettings()
        assertTabSelected(tabBar.settingsTab, name: "Settings")

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

    /// 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) {
        // Re-query the element to get fresh state, since isSelected can be stale.
        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")
    }
}
