// ThemeStore.swift
// Observable store that tracks the active terminal theme and persists the
// selection across launches via UserDefaults.

import Foundation
import Combine

private let kThemeKey = "terminal.theme"

@MainActor
public final class ThemeStore: ObservableObject {

    // MARK: Singleton

    public static let shared = ThemeStore()

    // MARK: Published state

    @Published public private(set) var current: TerminalTheme

    // MARK: Available themes (ordered: default first)

    public let available: [TerminalTheme] = [.dark, .github]

    // MARK: Init

    private init() {
        // Restore previously selected theme id from UserDefaults.
        if let savedId = UserDefaults.standard.string(forKey: kThemeKey),
           let saved = [TerminalTheme.dark, .github].first(where: { $0.id == savedId }) {
            current = saved
        } else {
            current = .dark
        }
    }

    // MARK: Public API

    /// Makes `theme` the active theme and persists the choice.
    public func select(_ theme: TerminalTheme) {
        current = theme
        UserDefaults.standard.set(theme.id, forKey: kThemeKey)
    }
}
