//
//  OnboardingVotingTests.swift
//  Tests iOS
//
//  TC-122: Onboarding day voting — Today vs Yesterday selection.
//

import XCTest

final class OnboardingVotingTests: BaseUITestCase {
    override var seedFixture: String? { "empty" }
    override var skipOnboarding: Bool { false }

    /// TC-122: Tapping Today and Yesterday buttons toggles the selection.
    func testOnboarding_DayVoting_TodayAndYesterday() {
        let onboarding = OnboardingScreen(app: app)

        // Wait for welcome screen
        XCTAssertTrue(
            onboarding.welcomeScreen.waitForExistence(timeout: 10),
            "Onboarding welcome screen should appear"
        )

        // Swipe once: Welcome → Day (Day is now page 2, before Time)
        swipeToNext()

        // Look for the "Which day should" title text to confirm we're on the day page
        let dayTitle = app.staticTexts.matching(
            NSPredicate(format: "label CONTAINS[c] 'Which day'")
        ).firstMatch

        XCTAssertTrue(
            dayTitle.waitForExistence(timeout: 5),
            "Day screen title 'Which day should you rate?' should be visible"
        )

        captureScreenshot(name: "onboarding_day_screen")

        // Tap the Yesterday card by looking for its text
        let yesterdayText = app.staticTexts["Yesterday, Rate the previous day"]
        let todayText = app.staticTexts["Today, Rate the current day"]

        // Fallback: try the button by accessibility identifier
        let yesterdayButton = app.element(UITestID.Onboarding.dayYesterday)
        let todayButton = app.element(UITestID.Onboarding.dayToday)

        // Try tapping Yesterday via text label or accessibility ID
        if yesterdayButton.exists {
            yesterdayButton.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.5)).tap()
        } else if yesterdayText.exists {
            yesterdayText.tap()
        } else {
            // Fallback: tap coordinate at roughly the "Yesterday" card position
            app.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.72)).tap()
        }

        captureScreenshot(name: "onboarding_day_yesterday_tapped")

        // Tap Today
        if todayButton.exists {
            todayButton.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.5)).tap()
        } else if todayText.exists {
            todayText.tap()
        } else {
            app.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.60)).tap()
        }

        captureScreenshot(name: "onboarding_day_today_tapped")
    }

    // MARK: - Private

    private func swipeToNext() {
        let start = app.coordinate(withNormalizedOffset: CGVector(dx: 0.9, dy: 0.18))
        let end = app.coordinate(withNormalizedOffset: CGVector(dx: 0.1, dy: 0.18))
        start.press(forDuration: 0.05, thenDragTo: end)
        _ = app.waitForExistence(timeout: 1.0)
    }
}
