import ComposableArchitecture
import FeatureOnboardingModels
import FeatureOnboardingScreens
import Localization
import SwiftUI

struct MadlibsUsernameEntryScreen: View {
    @Bindable var store: StoreOf<UsernameEntry>

    init(store: StoreOf<UsernameEntry>) {
        self.store = store
    }

    var body: some View {
        VStack(spacing: 8) {
            MadlibsStyledTextField(
                title: L10n.FeatureOnboarding.madlibsUsernameQuestion,
                subtitle: L10n.FeatureOnboarding.usernameSubtitle,
                placeholder: L10n.FeatureOnboarding.usernameEntryPlaceholder,
                autofillContentType: .username,
                value: $store.value,
                focused: $store.isFocused.sending(\.setFocus),
                isLoading: store.isWorking,
                onClear: { store.send(.clearText) },
                errorMessage: nil // We'll show status below instead
            )

            // Show status view below the text field
            UsernameStatusView(
                isInputEmpty: store.value.isEmpty,
                isChecking: store.isCheckingOrPending,
                isAvailable: store.isUsernameAvailable,
                errorMessage: store.errorMessage,
                wasLastCheckSuccessful: store.wasLastCheckSuccessful
            )
            .padding(.horizontal, 16)
        }
        .onAppear {
            store.send(.onAppear)

            // Trigger validation if there's already a value
            if !store.value.isEmpty {
                store.send(.internal(.validateUsername(store.value)))
            }
        }
    }
}
