import CoreBluetooth
import Foundation
import SwiftUI

struct PeripheralInfo: Identifiable {
    let id: UUID
    let peripheral: CBPeripheral
    var name: String
    var rssi: Int
    var isConnected: Bool

    var rssiText: String { "\(rssi) dBm" }

    var signalStrength: SignalStrength {
        switch rssi {
        case -50 ..< 0:        return .excellent
        case -70 ..< -50:   return .good
        case -85 ..< -70:   return .fair
        default:            return .weak
        }
    }

    enum SignalStrength {
        case excellent, good, fair, weak
        var icon: String {
            switch self {
            case .excellent, .good: return "wifi"
            case .fair:             return "wifi.exclamationmark"
            case .weak:             return "wifi.slash"
            }
        }
        var color: Color {
            switch self {
            case .excellent: return .green
            case .good:      return .yellow
            case .fair:      return .orange
            case .weak:      return .red
            }
        }
    }
}

struct TerminalEntry: Identifiable {
    let id = UUID()
    let timestamp: Date
    let direction: Direction
    let data: Data
    let label: String

    var asciiText: String {
        String(data: data, encoding: .utf8) ?? hexText
    }
    var hexText: String {
        data.map { String(format: "%02X", $0) }.joined(separator: " ")
    }
    var timestampText: String {
        let f = DateFormatter()
        f.dateFormat = "HH:mm:ss.SSS"
        return f.string(from: timestamp)
    }

    enum Direction { case sent, received, info }

    func displayText(mode: DisplayMode) -> String {
        switch mode {
        case .auto:  return data.isValidUTF8 ? asciiText : hexText
        case .ascii: return asciiText
        case .hex:   return hexText
        case .both:  return "\(hexText)  |  \(asciiText)"
        }
    }
}

enum InputMode: String, CaseIterable   { case text = "Text";  case hex = "Hex" }
enum DisplayMode: String, CaseIterable { case auto = "Auto";  case ascii = "ASCII"; case hex = "Hex"; case both = "Both" }

extension Data {
    var isValidUTF8: Bool { String(data: self, encoding: .utf8) != nil }
}
