//
//  DateLocaleTests.swift
//  Tests iOS
//
//  TC-139: Date formatting matches locale (German locale uses DD.MM.YYYY format).
//

import XCTest

final class DateLocaleTests: BaseUITestCase {
    override var seedFixture: String? { "week_of_moods" }
    override var bypassSubscription: Bool { true }

    override func setUp() {
        // Do NOT call super — we need custom locale launch args
        continueAfterFailure = false

        let application = XCUIApplication()
        let args: [String] = [
            "--ui-testing", "--disable-animations",
            "--reset-state",
            "--bypass-subscription",
            "--skip-onboarding",
            "-AppleLanguages", "(de)",
            "-AppleLocale", "de_DE"
        ]
        application.launchArguments = args
        application.launchEnvironment = ["UI_TEST_FIXTURE": "week_of_moods"]
        application.launch()
        app = application
    }

    /// TC-139: German locale displays German month/weekday names.
    func testGermanLocale_DateFormattingMatchesLocale() {
        // Tab bar should load
        let tabBar = app.tabBars.firstMatch
        XCTAssertTrue(tabBar.waitForExistence(timeout: 5), "Tab bar should exist")

        captureScreenshot(name: "german_locale_day_tab")

        // Navigate to Year View via tab bar
        // In German, Year tab may be labeled "Jahr" or use accessibility ID
        let yearTabButton = app.tabBars.buttons["Jahr"]
        if yearTabButton.waitForExistence(timeout: 3) {
            yearTabButton.tap()
        } else {
            // Fallback: tap by index (year is the 3rd tab)
            let allButtons = app.tabBars.buttons.allElementsBoundByIndex
            if allButtons.count >= 3 {
                allButtons[2].tap()
            }
        }

        // Year view should show German month abbreviations
        // German months: Jan, Feb, Mär, Apr, Mai, Jun, Jul, Aug, Sep, Okt, Nov, Dez
        let germanMonth = app.staticTexts.matching(
            NSPredicate(format: "label CONTAINS[c] 'Feb' OR label CONTAINS[c] 'Mär' OR label CONTAINS[c] 'Okt' OR label CONTAINS[c] 'Dez'")
        ).firstMatch

        let hasGermanDate = germanMonth.waitForExistence(timeout: 5)

        captureScreenshot(name: "german_locale_year_tab")

        // Navigate to Settings to verify German "Einstellungen" text
        let settingsButton = app.tabBars.buttons["Einstellungen"]
        if settingsButton.waitForExistence(timeout: 3) {
            settingsButton.tap()
        } else {
            let allButtons = app.tabBars.buttons.allElementsBoundByIndex
            if allButtons.count >= 5 {
                allButtons[4].tap()
            }
        }

        let settingsHeader = app.element(UITestID.Settings.header)
        XCTAssertTrue(
            settingsHeader.waitForExistence(timeout: 5),
            "Settings header should be visible in German locale"
        )

        captureScreenshot(name: "german_locale_settings")
    }
}
