import Foundation

enum PhoneNumberText {
    nonisolated static func normalizedForStorage(_ value: String) -> String {
        let trimmed = value.trimmingCharacters(in: .whitespacesAndNewlines)
        let hasLeadingPlus = trimmed.hasPrefix("+")
        let digits = trimmed.filter(\.isNumber)

        guard !digits.isEmpty else { return "" }
        if hasLeadingPlus {
            return "+\(digits)"
        }
        return digits
    }

    nonisolated static func isValid(_ value: String) -> Bool {
        let trimmed = value.trimmingCharacters(in: .whitespacesAndNewlines)
        guard !trimmed.isEmpty else { return false }

        let plusCount = trimmed.filter { $0 == "+" }.count
        if plusCount > 1 { return false }
        if plusCount == 1 && !trimmed.hasPrefix("+") { return false }

        let digits = trimmed.filter(\.isNumber)
        return (7...15).contains(digits.count)
    }

    nonisolated static func formatted(_ raw: String) -> String {
        let trimmed = raw.trimmingCharacters(in: .whitespacesAndNewlines)
        guard !trimmed.isEmpty else { return "" }

        let hasLeadingPlus = trimmed.hasPrefix("+")
        let digits = trimmed.filter(\.isNumber)
        guard !digits.isEmpty else { return hasLeadingPlus ? "+" : "" }

        if hasLeadingPlus {
            if digits.count == 11, digits.first == "1" {
                return "+1 \(formatUSDigits(String(digits.dropFirst())))"
            }
            return "+" + formatInternationalDigits(digits)
        }

        if digits.count == 11, digits.first == "1" {
            return "1 \(formatUSDigits(String(digits.dropFirst())))"
        }
        if digits.count <= 10 {
            return formatUSDigits(digits)
        }
        return formatInternationalDigits(digits)
    }

    nonisolated private static func formatUSDigits(_ digits: String) -> String {
        if digits.isEmpty { return "" }

        if digits.count <= 3 {
            return digits
        }

        let area = String(digits.prefix(3))
        let remaining = String(digits.dropFirst(3))

        if remaining.count <= 3 {
            return "(\(area)) \(remaining)"
        }

        let prefix = String(remaining.prefix(3))
        let line = String(remaining.dropFirst(3).prefix(4))
        return "(\(area)) \(prefix)-\(line)"
    }

    nonisolated private static func formatInternationalDigits(_ digits: String) -> String {
        guard !digits.isEmpty else { return "" }

        if digits.count <= 3 {
            return digits
        }

        var groups: [String] = []
        var index = digits.startIndex

        while index < digits.endIndex {
            let next = digits.index(index, offsetBy: 3, limitedBy: digits.endIndex) ?? digits.endIndex
            groups.append(String(digits[index..<next]))
            index = next
        }

        return groups.joined(separator: " ")
    }
}
