import XCTest

/// Shared navigation helpers for UI test base classes.
/// Each conforming class provides its own `app` and `navigateToRepoDetail`
/// implementation; the protocol extension supplies the rest.
protocol UITestNavigating {
    var app: XCUIApplication! { get }
    func navigateToRepoDetail(_ repoName: String)
}

extension UITestNavigating {

    func navigateToRepoDetail() {
        navigateToRepoDetail("test-repo")
    }

    func navigateToIssueTab() {
        navigateToRepoDetail()
        let picker = app.segmentedControls["repo-detail-tab-picker"]
        XCTAssertTrue(picker.waitForExistence(timeout: 10))
        picker.buttons["Issues"].tap()
    }

    func navigateToPRTab() {
        navigateToRepoDetail()
        let picker = app.segmentedControls["repo-detail-tab-picker"]
        XCTAssertTrue(picker.waitForExistence(timeout: 10))
        picker.buttons["PRs"].tap()
    }

    /// Resets the overview filter to Open + All involvement (the app defaults).
    func resetOverviewFilters() {
        let filterMenuButton = app.buttons["filter-menu-button"]
        guard filterMenuButton.waitForExistence(timeout: 5) else { return }
        filterMenuButton.tap()
        app.buttons["Open"].tap()
        sleep(1)
        setOverviewScopeAll()
    }

    /// Switches the overview scope to "All" to show items from all users.
    /// The Scope "All" is the second "All" button in the filter menu
    /// (the first is from the State section).
    func setOverviewScopeAll() {
        let filterMenuButton = app.buttons["filter-menu-button"]
        guard filterMenuButton.waitForExistence(timeout: 5) else { return }
        filterMenuButton.tap()
        let allButtons = app.buttons.matching(identifier: "All")
        if allButtons.count >= 2 {
            allButtons.element(boundBy: 1).tap()
        } else {
            allButtons.firstMatch.tap()
        }
        sleep(1)
    }

    func expandActionMenu() {
        let toggle = app.buttons["action-menu-toggle"]
        XCTAssertTrue(toggle.waitForExistence(timeout: 10), "Action menu toggle not found")
        if toggle.value as? String != "expanded" {
            toggle.tap()
        }
    }
}
