class Employee {
  final String id;
  final String name;
  final String email;

  Employee({
    required this.id,
    required this.name,
    required this.email,
  });

  /// Computed getters for first and last names
  String get firstName {
    final parts = name.trim().split(RegExp(r'\s+'));
    return parts.isNotEmpty ? parts.first : '';
  }

  String get lastName {
    final parts = name.trim().split(RegExp(r'\s+'));
    if (parts.length > 1) {
      return parts.sublist(1).join(' ');
    }
    return '';
  }

  factory Employee.fromJson(Map<String, dynamic> json) {
    // Try many possible id fields
    final idVal = (json['id'] ??
            json['Id'] ??
            json['employeeId'] ??
            json['empId'] ??
            json['employee_id'])
        ?.toString();

    // Try many possible first/last name fields
    final first = (json['firstName'] ??
            json['first_name'] ??
            json['firstname'] ??
            json['fname'] ??
            '')
        .toString()
        .trim();
    final last = (json['lastName'] ??
            json['last_name'] ??
            json['lastname'] ??
            json['lname'] ??
            '')
        .toString()
        .trim();

    // Name may come as a single field in multiple variants
    String nameVal = (json['name'] ??
            json['Name'] ??
            json['fullName'] ??
            json['full_name'] ??
            json['employeeName'] ??
            json['employee_name'] ??
            json['empName'] ??
            json['employee'] ??
            '')
        .toString()
        .trim();

    // If separate first/last found and name empty, combine them
    if (nameVal.isEmpty && (first.isNotEmpty || last.isNotEmpty)) {
      nameVal = ('$first ${last}').trim();
    }

    // If name still empty, fallback to email or id to avoid blank name
    if (nameVal.isEmpty && (json['email'] != null)) {
      nameVal = json['email'].toString().split('@').first;
    }
    if (nameVal.isEmpty) {
      nameVal = idVal ?? '';
    }

    final emailVal = (json['email'] ??
            json['emailAddress'] ??
            json['email_address'] ??
            json['employeeEmail'] ??
            json['employee_email'] ??
            '')
        .toString();

    return Employee(
      id: idVal ?? '',
      name: nameVal,
      email: emailVal,
    );
  }

  static List<Employee> listFromJson(dynamic data) {
    if (data is List) {
      return data.map((e) {
        if (e is Map<String, dynamic>) return Employee.fromJson(e);
        return Employee.fromJson(Map<String, dynamic>.from(e));
      }).toList();
    }
    // In case API returns { data: [...] }, that should already be unwrapped by ApiService
    return [];
  }
}
