<?php
use Drupal\Core\Asset\AttachedAssetsInterface;
use Drupal\Core\Language\LanguageInterface;

/**
 * Implements hook_css_alter().
 */
function sector_theme_css_alter(&$css, AttachedAssetsInterface $assets, LanguageInterface $language) {
  // Get all of the core libraries.
  $libraries = \Drupal::service('library.discovery.collector')->get('core');

  // Filter out the component libraries.
  $componentLibraries = array_filter(
    $libraries,
    fn($key) => str_starts_with($key, 'components.'),
    ARRAY_FILTER_USE_KEY
  );

  foreach ($componentLibraries as $libraryName => $library) {
    if (!isset($library['css'])) {
      continue;
    }

    $componentPaths = [];

    // Iterate through the CSS files in the component library.
    foreach ($library['css'] as $cssKey => $cssDefinition) {
      $componentPaths[] = $cssDefinition['data'];
    }

    $matches = [];

    // Now iterate through the full CSS array keys and extract the matches.
    foreach ($css as $key => $stylesheet) {
      foreach ($componentPaths as $componentPath) {
        if (str_contains($key, $componentPath)) {
          $matches[$key] = $stylesheet;
        }
      }
    }

    // Now we have the matches, we can change the CSS group.
    foreach ($matches as $key => $stylesheet) {
      $css[$key]['group'] = CSS_AGGREGATE_THEME;
    }
  }
}
