import SwiftUI
import Bedrock
import SwiftData

struct RootTabView: View {
    @Environment(AppState.self) private var appState
    @State private var showingShareSheet = false

    var body: some View {
        @Bindable var appState = appState
        
        TabView(selection: $appState.selectedTab) {
            Tab(String.localized("My Cards"), systemImage: "rectangle.stack", value: AppTab.cards) {
                CardsHomeView()
                    .safeAreaInset(edge: .bottom, spacing: 0) {
                        // Floating share button positioned above tab bar
                        if !appState.cardStore.cards.isEmpty {
                            FloatingShareButton {
                                showingShareSheet = true
                            }
                            .frame(maxWidth: .infinity)
                            .padding(.bottom, Design.Spacing.small)
                        }
                    }
            }

            Tab(String.localized("Contacts"), systemImage: "person.2", value: AppTab.contacts) {
                ContactsView()
            }

            Tab(String.localized("Widgets"), systemImage: "square.grid.2x2", value: AppTab.widgets) {
                WidgetsView()
            }

            Tab(String.localized("Settings"), systemImage: "gearshape", value: AppTab.settings) {
                SettingsView()
            }
        }
        .sheet(isPresented: $showingShareSheet) {
            ShareCardView()
        }
    }
}

// MARK: - Floating Share Button

private struct FloatingShareButton: View {
    let action: () -> Void
    
    var body: some View {
        Button(action: action) {
            Image(systemName: "qrcode")
                .typography(.title2)
                .fontWeight(.semibold)
                .foregroundStyle(.white)
                .frame(width: Design.CardSize.floatingButtonSize, height: Design.CardSize.floatingButtonSize)
                .background(
                    Circle()
                        .fill(Color.Accent.red)
                        .shadow(
                            color: Color.Accent.red.opacity(Design.Opacity.medium),
                            radius: Design.Shadow.radiusMedium,
                            x: Design.Shadow.offsetNone,
                            y: Design.Shadow.offsetSmall
                        )
                )
        }
        .accessibilityLabel(String.localized("Share"))
        .accessibilityHint(String.localized("Opens the share sheet to send your card"))
    }
}

#Preview {
    RootTabView()
        .environment(AppState(modelContext: try! ModelContainer(for: BusinessCard.self, Contact.self).mainContext))
}
