import XCTest

final class RepositoryMutatingUITests: ForgejoUITestBase {

    // MARK: - Code Browser & File Viewer (mutates repo via file edit + commit)

    @MainActor
    func testCodeBrowserAndFileViewer() throws {
        loginAndWaitForHome()
        navigateToRepoDetail()

        // Code tab shows files
        XCTAssertTrue(app.staticTexts["README.md"].waitForExistence(timeout: 10))
        XCTAssertTrue(app.staticTexts["hello.py"].waitForExistence(timeout: 5))

        // Navigate into src directory
        let srcFolder = app.staticTexts["src"].firstMatch
        XCTAssertTrue(srcFolder.waitForExistence(timeout: 10))
        srcFolder.tap()

        XCTAssertTrue(app.staticTexts["main.py"].waitForExistence(timeout: 10))
        XCTAssertTrue(app.buttons["test-repo"].waitForExistence(timeout: 5))

        // Breadcrumb back to root
        let rootBreadcrumb = app.buttons["test-repo"]
        rootBreadcrumb.tap()
        XCTAssertTrue(app.staticTexts["hello.py"].waitForExistence(timeout: 10))
        XCTAssertTrue(app.staticTexts["README.md"].waitForExistence(timeout: 5))

        // Scroll toggle button
        let toggleButton = app.buttons["code-scroll-toggle"]
        XCTAssertTrue(toggleButton.waitForExistence(timeout: 5))
        toggleButton.tap()
        toggleButton.tap()

        // File viewer, tap hello.py
        let fileCell = app.staticTexts["hello.py"].firstMatch
        XCTAssertTrue(fileCell.waitForExistence(timeout: 10))
        fileCell.tap()

        let editButton = app.buttons["file-edit-button"]
        XCTAssertTrue(editButton.waitForExistence(timeout: 10))

        // Enter edit mode
        editButton.tap()

        let cancelButton = app.buttons["file-edit-cancel"]
        XCTAssertTrue(cancelButton.waitForExistence(timeout: 5))
        cancelButton.tap()
        XCTAssertTrue(editButton.waitForExistence(timeout: 5))

        // Edit and commit flow
        editButton.tap()

        let textEditor = app.textViews.firstMatch
        XCTAssertTrue(textEditor.waitForExistence(timeout: 5))
        textEditor.tap()
        textEditor.typeText("\n# UI test edit")

        let commitButton = app.buttons["file-edit-commit"]
        XCTAssertTrue(commitButton.waitForExistence(timeout: 5))
        commitButton.tap()

        let commitMessageField = app.textFields["commit-message-field"]
        XCTAssertTrue(commitMessageField.waitForExistence(timeout: 5))

        let commitSubmit = app.buttons["commit-submit"]
        XCTAssertTrue(commitSubmit.waitForExistence(timeout: 5))
        commitSubmit.tap()

        XCTAssertTrue(editButton.waitForExistence(timeout: 10))
    }
}
