<?php

declare(strict_types=1);

namespace Drupal\sobki_theme_bootstrap\HookHandler;

use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Drupal\Core\Language\LanguageManagerInterface;
use Drupal\Core\Template\Attribute;
use Drupal\ui_patterns_settings\Plugin\UiPatterns\SettingType\LinksSettingType;
use Symfony\Component\DependencyInjection\ContainerInterface;

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

  /**
   * The language manager service.
   *
   * @var \Drupal\Core\Language\LanguageManagerInterface
   */
  protected LanguageManagerInterface $languageManager;

  /**
   * Constructor.
   *
   * @param \Drupal\Core\Language\LanguageManagerInterface $languageManager
   *   The language manager service.
   */
  public function __construct(
    LanguageManagerInterface $languageManager,
  ) {
    $this->languageManager = $languageManager;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container): static {
    // @phpstan-ignore-next-line
    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 = LinksSettingType::normalize(\array_filter(
      $variables['links'],
    ));
    $currentLanguageLink = $this->getCurrentLanguageLink($links);

    $variables['dropdown'] = [
      '#type' => 'pattern',
      '#id' => 'dropdown',
      '#title' => $currentLanguageLink['title'],
      '#button_url' => $currentLanguageLink['url'] ?? '',
      '#button_attributes' => $currentLanguageLink['attributes'],
      '#button_variant' => 'link',
      '#content' => empty($links) ? [] : $links,
      '#attributes' => $variables['attributes'],
      '#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']) || !($link['attributes'] instanceof Attribute)) {
        continue;
      }

      if (!$link['attributes']->hasAttribute('hreflang')) {
        continue;
      }

      /** @var \Drupal\Core\Template\AttributeString $hreflang */
      $hreflang = $link['attributes']->offsetGet('hreflang');
      if ($hreflang->value() == $active_langcode) {
        unset($links[$key]);
        return $link;
      }
    }

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

}
