import APIClient
import ComponentLibrary
import ComposableArchitecture
import Errors
import GenAPI
import Localization
import SwiftUI
import Utilities

extension SongDetailsReducer {
    func isValidMention(_ mention: CaptionUserMention, in text: String) -> Bool {
        InteractiveTextFormatter.isValidMention(mention, in: text)
    }

    /// Finds the @mention currently being typed at the end of text
    func extractCurrentMention(from text: String) -> String? {
        InteractiveTextFormatter.extractCurrentMention(from: text)
    }

    /// Replaces @mention with user's display name and updates mentions list
    func replacePendingMention(
        from text: String,
        for user: SimpleProfile,
        mentions: inout [CaptionUserMention]
    ) -> String {
        InteractiveTextFormatter.replacePendingMention(
            from: text,
            for: user,
            mentions: &mentions
        ) { start, end, handle, displayName in
            CaptionUserMention(start: start, end: end, handle: handle, displayName: displayName)
        }
    }

    func restoreExistingMentionsFromCaption(text: String, state: inout State) {
        guard state.userMentions.isEmpty, !state.clip.captionMentions.isEmpty else { return }
        state.userMentions = state.clip.captionMentions.filter { isValidMention($0, in: text) }
    }
}
