class MetadataHelper {
  // Common prefixes or patterns
  static const Map<String, String> _prefixes = {
    '_yoast_': 'Yoast SEO',
    '_elementor_': 'Elementor',
    '_wpas_': 'Publicize',
    'facebook_': 'Facebook',
    '_wc_': 'WooCommerce',
    'slide_template': 'Slider',
  };

  static const Map<String, String> _fieldNames = {
    '_yoast_wpseo_title': 'SEO Title',
    '_yoast_wpseo_metadesc': 'Meta Description',
    '_yoast_wpseo_focuskw': 'Focus Keyword',
    '_yoast_wpseo_canonical': 'Canonical URL',
    '_elementor_edit_mode': 'Edit Mode',
    '_elementor_template_type': 'Template Type',
    '_elementor_version': 'Version',
    '_price': 'Price',
    '_regular_price': 'Regular Price',
    '_sale_price': 'Sale Price',
    '_sku': 'SKU',
    '_stock_status': 'Stock Status',
  };

  static String getPluginName(String key) {
    for (final entry in _prefixes.entries) {
      if (key.startsWith(entry.key)) {
        return entry.value;
      }
    }
    return 'Other';
  }

  static String getFieldTitle(String key) {
    if (_fieldNames.containsKey(key)) {
      return _fieldNames[key]!;
    }
    
    // Fallback: cleanup the key
    String title = key;
    
    // Remove underscores
    if (title.startsWith('_')) title = title.substring(1);
    
    // Replace separators
    title = title.replaceAll('_', ' ').replaceAll('-', ' ');
    
    // Remove plugin prefixes if recognizable to clean it up further
    for (final prefix in _prefixes.keys) {
        final cleanPrefix = prefix.replaceAll('_', ' ').trim();
         if (title.toLowerCase().startsWith(cleanPrefix)) {
             title = title.substring(cleanPrefix.length).trim();
         }
    }

    // Capitalize Words
    return title.split(' ').map((str) {
      if (str.isEmpty) return '';
      return str[0].toUpperCase() + str.substring(1).toLowerCase();
    }).join(' ');
  }

  static Map<String, List<dynamic>> groupMetadata(List<dynamic> metaData) {
    final Map<String, List<dynamic>> groups = {};

    for (var meta in metaData) {
      final key = meta['key']?.toString() ?? '';
      final groupName = getPluginName(key);
      
      if (!groups.containsKey(groupName)) {
        groups[groupName] = [];
      }
      groups[groupName]!.add(meta);
    }
    
    // Sort keys: Known plugins first, Other last
    // We can return a sorted map logic or just let the UI handle it. 
    // Just ensuring 'Other' is at the end might be nice, but simple map is fine for now.
    return groups;
  }
}
