import Foundation

/// Desktop parity: in-memory draft store per dialog.
/// Desktop uses `useMemory` hook to persist draft text per conversation;
/// drafts survive switching between chats but are lost on app restart.
@MainActor
final class DraftManager {
    static let shared = DraftManager()

    /// Dialog public key → draft text.
    private var drafts: [String: String] = [:]

    private init() {}

    /// Returns the stored draft for a dialog, or empty string if none.
    func getDraft(for dialogKey: String) -> String {
        drafts[dialogKey] ?? ""
    }

    /// Saves a draft for a dialog. Empty/whitespace-only text deletes the draft.
    func saveDraft(for dialogKey: String, text: String) {
        let trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines)
        if trimmed.isEmpty {
            drafts.removeValue(forKey: dialogKey)
        } else {
            drafts[dialogKey] = text
        }
    }

    /// Deletes the draft for a dialog (called after sending a message).
    func deleteDraft(for dialogKey: String) {
        drafts.removeValue(forKey: dialogKey)
    }

    /// Whether a draft exists for a given dialog.
    func hasDraft(for dialogKey: String) -> Bool {
        guard let text = drafts[dialogKey] else { return false }
        return !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
    }

    /// Clears all drafts (called on logout).
    func reset() {
        drafts.removeAll()
    }
}
