import SwiftUI

struct ScrollableTabs: View {
    let tabs: [String]
    @Binding var selectedTab: String
    let onTabChanged: ((String) -> Void)?
    
    init(
        tabs: [String],
        selectedTab: Binding<String>,
        onTabChanged: ((String) -> Void)? = nil
    ) {
        self.tabs = tabs
        self._selectedTab = selectedTab
        self.onTabChanged = onTabChanged
    }
    
    var body: some View {
        ScrollView(.horizontal, showsIndicators: false) {
            HStack(spacing: 8) {
                ForEach(tabs, id: \.self) { tab in
                    TabButton(
                        title: tab,
                        isSelected: selectedTab == tab,
                        onTap: {
                            selectedTab = tab
                            onTabChanged?(tab)
                        }
                    )
                }
            }
            .padding(.horizontal, 16)
        }
        .background(
            Rectangle()
                .fill(Color.clear)
                .overlay(
                    Rectangle()
                        .frame(height: 1)
                        .foregroundColor(Color.white.opacity(0.1)),
                    alignment: .bottom
                )
        )
    }
}

private struct TabButton: View {
    let title: String
    let isSelected: Bool
    let onTap: () -> Void
    
    var body: some View {
        Button(action: onTap) {
            VStack(spacing: 0) {
                Text(title)
                    .font(Constants.Typography.small.weight(.medium))
                    .foregroundColor(isSelected ? Constants.Colors.Foreground.primary : Constants.Colors.Foreground.inactive)
                    .tracking(0.28)
                    .padding(.horizontal, 12)
                    .padding(.vertical, 12)
                    .frame(height: 40)
                
                // Bottom border for selected state
                Rectangle()
                    .frame(height: 1)
                    .foregroundColor(isSelected ? Constants.Colors.Foreground.primary : Color.clear)
            }
        }
        .buttonStyle(PlainButtonStyle())
        .background(
            // Background for selected state
            isSelected ? Constants.Colors.Background.primary : Color.clear
        )
    }
}

#Preview {
    let tabs = ["Songs", "Playlists", "Workspaces", "Personas", "Hooks", "History", "Archive"]
    
    VStack(spacing: 0) {
        ScrollableTabs(
            tabs: tabs,
            selectedTab: .constant("Workspaces")
        ) { selectedTab in
            print("Selected tab: \(selectedTab)")
        }
        
        Spacer()
    }
    .background(Constants.Colors.Background.primary)
    .preferredColorScheme(.dark)
}