import Foundation
import Observation
import WidgetKit

/// Состояние окна настроек: загрузка списка пар, выбор и сохранение.
@MainActor
@Observable
final class SettingsModel {
    enum Phase: Equatable {
        case loading
        case loaded
        case failed
    }

    private(set) var phase: Phase = .loading
    private(set) var symbols: [SymbolThumb] = []
    /// Выбор с сохранением порядка: первая пара — «герой» виджета.
    private(set) var selection: [String]
    var searchText = ""
    private(set) var isSaved = false

    private let api = RapiraAPI.shared
    private let store = PairSelectionStore.shared

    init() {
        selection = PairSelectionStore.shared.load()
    }

    // MARK: - Данные

    var maxSelection: Int { PairSelectionStore.maxSelection }

    var filtered: [SymbolThumb] {
        guard !searchText.isEmpty else { return symbols }
        let query = searchText.lowercased()
        return symbols.filter {
            $0.symbol.lowercased().contains(query) ||
            $0.quoteCurrencyName.lowercased().contains(query)
        }
    }

    func load() async {
        phase = .loading
        do {
            symbols = try await api.symbolThumbs().sorted { $0.turnover > $1.turnover }
            phase = .loaded
        } catch {
            phase = .failed
        }
    }

    // MARK: - Выбор

    func isSelected(_ symbol: String) -> Bool {
        selection.contains(symbol)
    }

    /// Снять выбор можно всегда, добавить — пока есть свободные слоты.
    func canToggle(_ symbol: String) -> Bool {
        isSelected(symbol) || selection.count < maxSelection
    }

    func toggle(_ symbol: String) {
        if let index = selection.firstIndex(of: symbol) {
            selection.remove(at: index)
        } else if selection.count < maxSelection {
            selection.append(symbol)
        } else {
            return
        }
        isSaved = false
    }

    func save() {
        store.save(selection)
        WidgetCenter.shared.reloadAllTimelines()
        isSaved = true
    }
}
