//
//  TabBarScreen.swift
//  Tests iOS
//
//  Screen object for the main tab bar navigation.
//

import XCTest

struct TabBarScreen {
    let app: XCUIApplication

    // MARK: - Tab Buttons

    var dayTab: XCUIElement { tab(identifier: UITestID.Tab.day, labels: ["Day", "Main"]) }
    var monthTab: XCUIElement { tab(identifier: UITestID.Tab.month, labels: ["Month"]) }
    var yearTab: XCUIElement { tab(identifier: UITestID.Tab.year, labels: ["Year", "Filter"]) }
    var insightsTab: XCUIElement { tab(identifier: UITestID.Tab.insights, labels: ["Insights"]) }
    var settingsTab: XCUIElement { tab(identifier: UITestID.Tab.settings, labels: ["Settings"]) }

    // MARK: - Actions

    @discardableResult
    func tapDay() -> DayScreen {
        app.tapTab(identifier: UITestID.Tab.day, labels: ["Day", "Main"])
        return DayScreen(app: app)
    }

    @discardableResult
    func tapMonth() -> TabBarScreen {
        app.tapTab(identifier: UITestID.Tab.month, labels: ["Month"])
        return self
    }

    @discardableResult
    func tapYear() -> TabBarScreen {
        app.tapTab(identifier: UITestID.Tab.year, labels: ["Year", "Filter"])
        return self
    }

    @discardableResult
    func tapInsights() -> TabBarScreen {
        app.tapTab(identifier: UITestID.Tab.insights, labels: ["Insights"])
        return self
    }

    @discardableResult
    func tapSettings() -> SettingsScreen {
        app.tapTab(identifier: UITestID.Tab.settings, labels: ["Settings"])
        return SettingsScreen(app: app)
    }

    // MARK: - Assertions

    func assertDayTabSelected() {
        XCTAssertTrue(dayTab.isSelected, "Day tab should be selected")
    }

    func assertTabBarVisible() {
        let visible = dayTab.waitForExistence(timeout: 5) ||
            monthTab.waitForExistence(timeout: 1) ||
            settingsTab.waitForExistence(timeout: 1)
        XCTAssertTrue(visible, "Tab bar should be visible")
    }

    // MARK: - Element Resolution

    private func tab(identifier: String, labels: [String]) -> XCUIElement {
        let idMatch = app.tabBars.buttons[identifier]
        if idMatch.exists {
            return idMatch
        }

        for label in labels {
            let match = app.tabBars.buttons[label]
            if match.exists {
                return match
            }
        }

        return app.tabBars.buttons[labels.first ?? identifier]
    }
}
