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
        
        ZStack(alignment: .bottom) {
            TabView(selection: $appState.selectedTab) {
                Tab(String.localized("My Cards"), systemImage: "rectangle.stack", value: AppTab.cards) {
                    CardsHomeView()
                }

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

                Tab(String.localized("Widgets"), systemImage: "square.grid.2x2", value: AppTab.widgets) {
                    WidgetsView()
                }
            }
            
            // Floating share button - only shown on cards tab when cards exist
            if appState.selectedTab == .cards && !appState.cardStore.cards.isEmpty {
                FloatingShareButton {
                    showingShareSheet = true
                }
            }
        }
        .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")
                .font(.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"))
        .padding(.bottom, Design.CardSize.floatingButtonBottomOffset)
    }
}

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