import Foundation

struct TableMember: Identifiable {
    let userId: Int
    let firstName: String
    let lastName: String
    let photoUrl: String
    let isHost: Bool
    let joinedAt: Date

    var id: Int { userId }

    init(json: [String: Any]) {
        userId = WorkTask.parseInt(json["UserID"]) ?? 0
        firstName = (json["UserFirstName"] as? String) ?? (json["FirstName"] as? String) ?? ""
        lastName = (json["UserLastName"] as? String) ?? (json["LastName"] as? String) ?? ""
        photoUrl = (json["UserPhotoUrl"] as? String) ?? ""
        if let b = json["IsHost"] as? Bool { isHost = b }
        else if let i = json["IsHost"] as? Int { isHost = i == 1 }
        else { isHost = false }
        if let s = json["JoinedAt"] as? String { joinedAt = APIService.parseDate(s) ?? Date() }
        else { joinedAt = Date() }
    }

    var fullName: String {
        let parts = [firstName, lastName].filter { !$0.isEmpty }
        return parts.isEmpty ? "Guest" : parts.joined(separator: " ")
    }

    var initials: String {
        let f = firstName.isEmpty ? "" : String(firstName.prefix(1)).uppercased()
        let l = lastName.isEmpty ? "" : String(lastName.prefix(1)).uppercased()
        let result = "\(f)\(l)"
        return result.isEmpty ? "?" : result
    }
}
