import Foundation

// MARK: - String Extensions

extension String {
    /// Checks if string is empty or contains only whitespace
    var isBlank: Bool {
        self.trimmingCharacters(in: .whitespaces).isEmpty
    }

    /// Returns nil if string is blank, otherwise returns trimmed string
    var nilIfBlank: String? {
        let trimmed = self.trimmingCharacters(in: .whitespaces)
        return trimmed.isEmpty ? nil : trimmed
    }

    /// Capitalizes first letter only
    var capitalizedFirst: String {
        guard let first = self.first else { return self }
        return first.uppercased() + self.dropFirst()
    }

    /// Truncates string to specified length with ellipsis
    func truncated(to length: Int, addEllipsis: Bool = true) -> String {
        guard self.count > length else { return self }
        let truncated = String(self.prefix(length))
        return addEllipsis ? truncated + "..." : truncated
    }

    /// Validates email format
    var isValidEmail: Bool {
        let emailRegex = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}"
        let emailPredicate = NSPredicate(format: "SELF MATCHES %@", emailRegex)
        return emailPredicate.evaluate(with: self)
    }

    /// Validates phone number (basic check)
    var isValidPhone: Bool {
        let phoneRegex = "^(?=.*[0-9])[0-9+\\-\\(\\)\\s]{10,}$"
        let phonePredicate = NSPredicate(format: "SELF MATCHES %@", phoneRegex)
        return phonePredicate.evaluate(with: self)
    }
}

// MARK: - Optional String Extensions

extension Optional where Wrapped == String {
    /// Checks if optional string is nil or blank
    var isNilOrBlank: Bool {
        guard let string = self else { return true }
        return string.isBlank
    }

    /// Returns the string if it has content, otherwise returns nil
    var nilIfBlank: String? {
        guard let string = self else { return nil }
        return string.nilIfBlank
    }
}
