import SwiftUI
import Combine

/// Compatibility adapter for the legacy single-workspace architecture.
/// New code should use `WorkspaceRegistry` + `WorkspaceController`.
@MainActor
class TerminalManager: ObservableObject {

    static let shared = TerminalManager()

    private var workspaceCancellable: AnyCancellable?

    private init() {
        workspaceCancellable = WorkspaceRegistry.shared.defaultWorkspaceController.objectWillChange
            .sink { [weak self] _ in
                self?.objectWillChange.send()
            }
    }

    private var workspace: WorkspaceController {
        WorkspaceRegistry.shared.defaultWorkspaceController
    }

    var tabs: [TerminalSession] {
        workspace.tabs
    }

    var activeTabIndex: Int {
        workspace.activeTabIndex
    }

    var activeTab: TerminalSession? {
        workspace.activeTab
    }

    var activeTitle: String {
        workspace.activeTitle
    }

    func newTab() {
        workspace.newTab()
    }

    func closeActiveTab() {
        workspace.closeActiveTab()
    }

    func closeTab(at index: Int) {
        workspace.closeTab(at: index)
    }

    func switchToTab(at index: Int) {
        workspace.switchToTab(at: index)
    }

    func nextTab() {
        workspace.nextTab()
    }

    func previousTab() {
        workspace.previousTab()
    }

    func detachActiveTab() -> TerminalSession? {
        workspace.detachActiveTab()
    }

    func updateAllFontSizes(_ size: CGFloat) {
        workspace.updateAllFontSizes(size)
    }

    func updateAllThemes(_ theme: TerminalTheme) {
        workspace.updateAllThemes(theme)
    }
}
