//
//  ShareNoDataTests.swift
//  Tests iOS
//
//  TC-119: Share with no mood data — verifies graceful behavior.
//

import XCTest

final class ShareNoDataTests: BaseUITestCase {
    override var seedFixture: String? { "empty" }
    override var bypassSubscription: Bool { true }

    /// TC-119: With no mood data, Year view share button is absent or sharing handles empty state.
    func testShare_NoData_GracefulBehavior() {
        let tabBar = TabBarScreen(app: app)
        tabBar.tapYear()

        // Wait for year view to load
        _ = app.waitForExistence(timeout: 3)

        captureScreenshot(name: "share_no_data_year")

        // With no mood data, there should be no year card share button
        let shareButton = app.element(UITestID.Year.shareButton)
        let shareExists = shareButton.waitForExistence(timeout: 3)

        if shareExists {
            // If the share button exists despite no data, tap it and verify
            // the sharing picker handles empty state gracefully
            shareButton.tapWhenReady()

            _ = app.waitForExistence(timeout: 2)

            captureScreenshot(name: "share_no_data_picker")

            // Look for "No designs available" text or a valid picker
            let noDesigns = app.staticTexts["No designs available"].firstMatch
            let exitButton = app.buttons["Exit"].firstMatch
            let pickerPresent = noDesigns.waitForExistence(timeout: 3) ||
                exitButton.waitForExistence(timeout: 3)

            // Either the picker shows empty state or renders normally
            // Both are acceptable — the key is no crash
            if exitButton.exists {
                exitButton.tap()
            }
        }

        // Navigate to Month view and check share button there too
        tabBar.tapMonth()
        _ = app.waitForExistence(timeout: 3)

        captureScreenshot(name: "share_no_data_month")

        let monthShareButton = app.element(UITestID.Month.shareButton)
        let monthShareExists = monthShareButton.waitForExistence(timeout: 3)

        // With empty data, month share button should be absent
        // or if present, should handle gracefully (no crash)
        if monthShareExists {
            monthShareButton.tapWhenReady()
            _ = app.waitForExistence(timeout: 2)
            captureScreenshot(name: "share_no_data_month_picker")

            let exitButton = app.buttons["Exit"].firstMatch
            if exitButton.waitForExistence(timeout: 3) {
                exitButton.tap()
            }
        }

        // Final verification: app is still responsive
        tabBar.tapDay()
        let emptyState = app.element(UITestID.Day.emptyStateNoData)
        let moodHeader = app.element(UITestID.Day.moodHeader)
        XCTAssertTrue(
            emptyState.waitForExistence(timeout: 5) || moodHeader.waitForExistence(timeout: 2),
            "App should remain functional after share-with-no-data flow"
        )
    }
}
