import SwiftUI

/// Horizontal tab bar at the bottom of the open notch panel.
/// Solid black background to match the rest of the notch —
/// the single `.opacity()` on ContentView handles transparency.
struct TabBar: View {

    @ObservedObject var workspace: WorkspaceController

    var body: some View {
        HStack(spacing: 0) {
            Button {
                workspace.newTab()
            } label: {
                Image(systemName: "plus")
                    .font(.system(size: 11, weight: .medium))
                    .foregroundStyle(.white.opacity(0.6))
            }
            .accessibilityLabel("New Tab")
            .accessibilityIdentifier("notch.new-tab")
            .buttonStyle(.plain)
            .padding(.horizontal, 8)

            ScrollView(.horizontal, showsIndicators: false) {
                HStack(spacing: 2) {
                    ForEach(Array(workspace.tabs.enumerated()), id: \.element.id) { index, tab in
                        tabButton(for: tab, at: index)
                    }
                }
                .padding(.horizontal, 4)
            }
        }
        .frame(height: 28)
        .background(.black)
    }

    @ViewBuilder
    private func tabButton(for tab: TerminalSession, at index: Int) -> some View {
        let isActive = index == workspace.activeTabIndex

        HStack(spacing: 4) {
            Text(abbreviateTitle(tab.title))
                .font(.system(size: 11))
                .lineLimit(1)
                .foregroundStyle(isActive ? .white : .white.opacity(0.5))

            if isActive && workspace.tabs.count > 1 {
                Button {
                    workspace.closeTab(at: index)
                } label: {
                    Image(systemName: "xmark")
                        .font(.system(size: 8, weight: .bold))
                        .foregroundStyle(.white.opacity(0.4))
                }
                .buttonStyle(.plain)
            }
        }
        .padding(.horizontal, 10)
        .padding(.vertical, 4)
        .background(
            RoundedRectangle(cornerRadius: 6)
                .fill(isActive ? Color.white.opacity(0.12) : Color.clear)
        )
        .contentShape(Rectangle())
        .onTapGesture {
            workspace.switchToTab(at: index)
        }
    }

    private func abbreviateTitle(_ title: String) -> String {
        title.count <= 24 ? title : String(title.prefix(22)) + "…"
    }
}
