//
//  NavigationAssertions.swift
//  suixinkanUITests
//
//  Created by Codex on 2026/6/26.
//

import XCTest

/// 页面导航与可见性断言工具。
enum NavigationAssertions {
    /// 等待导航栏标题出现。
    @discardableResult
    static func waitForNavigationTitle(
        _ title: String,
        in app: SuixinkanApp,
        timeout: TimeInterval = 12,
        file: StaticString = #filePath,
        line: UInt = #line
    ) -> Bool {
        let deadline = Date().addingTimeInterval(timeout)
        while Date() < deadline {
            if app.application.navigationBars[title].exists {
                return true
            }

            let topBar = app.application.navigationBars.element(boundBy: 0)
            if topBar.staticTexts[title].exists {
                return true
            }

            if app.application.staticTexts[title].exists {
                return true
            }

            RunLoop.current.run(until: Date().addingTimeInterval(0.2))
        }

        XCTAssertTrue(false, "未找到导航标题：\(title)", file: file, line: line)
        return false
    }

    /// 等待任意一个导航标题出现。
    @discardableResult
    static func waitForAnyNavigationTitle(
        _ titles: [String],
        in app: SuixinkanApp,
        timeout: TimeInterval = 12,
        file: StaticString = #filePath,
        line: UInt = #line
    ) -> String? {
        let deadline = Date().addingTimeInterval(timeout)
        while Date() < deadline {
            for title in titles {
                if app.application.navigationBars[title].exists {
                    return title
                }

                let topBar = app.application.navigationBars.element(boundBy: 0)
                if topBar.staticTexts[title].exists {
                    return title
                }

                if app.application.staticTexts[title].exists {
                    return title
                }
            }
            RunLoop.current.run(until: Date().addingTimeInterval(0.2))
        }

        XCTFail("未找到任一导航标题：\(titles.joined(separator: " / "))", file: file, line: line)
        return nil
    }

    /// 等待静态文案出现。
    @discardableResult
    static func waitForStaticText(
        _ text: String,
        in app: SuixinkanApp,
        timeout: TimeInterval = 8,
        file: StaticString = #filePath,
        line: UInt = #line
    ) -> Bool {
        let label = app.application.staticTexts[text]
        let exists = label.waitForExistence(timeout: timeout)
        XCTAssertTrue(exists, "未找到文案：\(text)", file: file, line: line)
        return exists
    }

    /// 断言页面未停留在全局 Loading。
    static func assertNotStuckOnLoading(
        app: SuixinkanApp,
        file: StaticString = #filePath,
        line: UInt = #line
    ) {
        let loading = app.application.staticTexts["加载中"]
        XCTAssertFalse(loading.exists, "页面不应长期停留在全局 Loading。", file: file, line: line)
    }
}
