import SwiftUI

/// Keeps the static system launch screen visually continuous, then presents
/// the selected 星痕 brand artwork before revealing the app.
struct LaunchRootView: View {
    @State private var isShowingSplash = true

    var body: some View {
        ZStack {
            ContentView()

            if isShowingSplash {
                SplashView {
                    withAnimation(.easeInOut(duration: 0.45)) {
                        isShowingSplash = false
                    }
                }
                .transition(.opacity)
                .zIndex(1)
            }
        }
    }
}

struct SplashView: View {
    @Environment(\.accessibilityReduceMotion) private var reduceMotion

    @State private var artworkOpacity = 0.0
    @State private var artworkScale = 1.008
    @State private var hasStarted = false

    let onFinished: () -> Void

    var body: some View {
        ZStack {
            Color("LaunchBackground")
                .ignoresSafeArea()

            Image("SplashArtwork")
                .resizable()
                .scaledToFill()
                .frame(maxWidth: .infinity, maxHeight: .infinity)
                .clipped()
                .opacity(artworkOpacity)
                .scaleEffect(artworkScale)
                .ignoresSafeArea()
        }
        .statusBarHidden(true)
        .task {
            guard !hasStarted else { return }
            hasStarted = true
            await playEntrance()
        }
        .accessibilityElement(children: .ignore)
        .accessibilityLabel("星痕。倾听，然后深刻。纯粹星辰出品。")
    }

    @MainActor
    private func playEntrance() async {
        if reduceMotion {
            artworkOpacity = 1
            artworkScale = 1
            try? await Task.sleep(for: .seconds(1.2))
            onFinished()
            return
        }

        withAnimation(.easeOut(duration: 0.65)) {
            artworkOpacity = 1
            artworkScale = 1
        }

        let holdDuration: Duration = ProcessInfo.processInfo.environment["XINGHEN_SPLASH_QA"] == "1"
            ? .seconds(30)
            : .seconds(2.05)
        try? await Task.sleep(for: holdDuration)
        onFinished()
    }
}

#Preview("星痕开屏") {
    SplashView(onFinished: {})
}
