<?php

declare(strict_types=1);

namespace Drupal\languagewire_translation_provider\Ui;

/**
 * Items interactor.
 */
final class ItemsInteractor {
  /**
   * General suffix.
   */
  public const GENERAL_SUFFIX = ' - General';

  /**
   * Sort items.
   *
   * @param array $items
   *   Items to sort.
   * @param string|null $suffix
   *   Suffix to add.
   *
   * @return array
   *   Sorted items.
   */
  public static function sortItems(array $items, ?string $suffix = NULL): array {
    uasort($items, function (string $a, string $b) use ($suffix) {
      if (isset($suffix)) {
            $aHasSuffix = str_contains($a, $suffix);
            $bHasSuffix = str_contains($b, $suffix);

        if ($aHasSuffix || $bHasSuffix) {
          // Extract item name without any suffixes.
          $aName = preg_replace('/\s*-.*/', '', $a);
          $bName = preg_replace('/\s*-.*/', '', $b);

          // Compare items names.
          $nameCmp = strnatcasecmp($aName, $bName);

          // If items are equal, suffix item should come first if it exits.
          if ($nameCmp === 0 && $aHasSuffix !== $bHasSuffix) {
                return $aHasSuffix ? -1 : 1;
          }
        }
      }

      if (strcmp(mb_strtolower($a), mb_strtolower($b)) === 0) {
        $aUppercase = ctype_upper($a[0]);
        $bUppercase = ctype_upper($b[0]);

        // If $a contains uppercase letter and $b doesn't,
        // $a comes first otherwise check same for $b.
        if ($aUppercase) {
            return -1;
        }
        elseif ($bUppercase) {
              return 1;
        }
      }

              return strnatcasecmp($a, $b);
    });

    return $items;
  }

}
