<?php

declare(strict_types=1);

namespace Drupal\sobki_theme_bootstrap\HookHandler;

use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Drupal\Core\Language\LanguageManagerInterface;
use Drupal\ui_patterns\Plugin\UiPatterns\PropType\LinksPropType;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Ensure language links structure fits into dropdown structure.
 */
class PreprocessLinksLanguageBlock implements ContainerInjectionInterface {

  /**
   * Constructor.
   *
   * @param \Drupal\Core\Language\LanguageManagerInterface $languageManager
   *   The language manager service.
   */
  public function __construct(protected LanguageManagerInterface $languageManager) {}

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container): static {
    return new static(
      $container->get('language_manager')
    );
  }

  /**
   * Ensure language links structure fits into dropdown structure.
   *
   * @param array $variables
   *   The preprocessed variables.
   */
  public function preprocess(array &$variables): void {
    if (empty($variables['links'])) {
      return;
    }

    $links = LinksPropType::normalize(\array_filter(
      $variables['links'],
    ));
    $currentLanguageLink = $this->getCurrentLanguageLink($links);

    $variables['dropdown'] = [
      '#type' => 'component',
      '#component' => 'ui_suite_bootstrap:dropdown',
      '#slots' => [
        'title' => $currentLanguageLink['title'],
      ],
      '#props' => [
        'attributes' => $variables['attributes'],
        'content' => empty($links) ? [] : $links,
        'button_url' => $currentLanguageLink['url'] ?? '',
        'button_attributes' => $currentLanguageLink['attributes'],
        'button_variant' => 'link',
        'dropdown_menu_end' => 'end',
      ],
    ];
  }

  /**
   * Get the current language link.
   *
   * @param array $links
   *   The normalized links.
   *
   * @return array
   *   An array of a normalized link.
   */
  protected function getCurrentLanguageLink(array &$links): array {
    $active_langcode = $this->languageManager->getCurrentLanguage()->getId();

    foreach ($links as $key => $link) {
      if (!isset($link['attributes']['hreflang'])) {
        continue;
      }

      if ($link['attributes']['hreflang'] == $active_langcode) {
        unset($links[$key]);
        return $link;
      }
    }

    // If not possible to find the active link take the first one.
    return \array_shift($links);
  }

}
