<?php

declare(strict_types=1);

namespace Drupal\sobki_admin\Plugin\TopBarItem;

use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\navigation\Attribute\TopBarItem;
use Drupal\navigation\TopBarItemBase;
use Drupal\navigation\TopBarRegion;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Make Layout Builder actions sticky.
 */
#[TopBarItem(
  id: 'sobki_admin_layout_builder_actions',
  region: TopBarRegion::Actions,
  label: new TranslatableMarkup('Layout Builder actions (Sobki Admin)'),
)]
class LayoutBuilderActions extends TopBarItemBase implements ContainerFactoryPluginInterface {

  use StringTranslationTrait;

  public function __construct(
    array $configuration,
    $plugin_id,
    $plugin_definition,
    protected RouteMatchInterface $routeMatch,
  ) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition): static {
    return new static(
      $configuration,
      $plugin_id,
      $plugin_definition,
      $container->get(RouteMatchInterface::class),
    );
  }

  /**
   * {@inheritdoc}
   */
  public function build(): array {
    $build = [
      '#cache' => [
        'contexts' => ['route'],
      ],
    ];

    $routeName = $this->routeMatch->getRouteName();
    if (!\is_string($routeName)) {
      return $build;
    }

    if (!\str_starts_with($routeName, 'layout_builder.overrides.')) {
      return $build;
    }

    $build += [
      'save' => [
        '#type' => 'component',
        '#component' => 'navigation:toolbar-button',
        '#props' => [
          'text' => $this->t('Save layout'),
          'modifiers' => [
            'primary',
          ],
          'attributes' => [
            'class' => [
              'js-layout-builder-top-bar-save',
            ],
          ],
          'icon' => [
            'pack_id' => 'sobki_admin',
            'icon_id' => 'check-lg',
          ],
        ],
      ],
      'discard' => [
        '#type' => 'component',
        '#component' => 'navigation:toolbar-button',
        '#props' => [
          'text' => $this->t('Discard changes'),
          'modifiers' => [
            'dark',
          ],
          'attributes' => [
            'class' => [
              'js-layout-builder-top-bar-discard',
            ],
          ],
          'icon' => [
            'pack_id' => 'sobki_admin',
            'icon_id' => 'trash',
          ],
        ],
      ],
      '#attached' => [
        'library' => [
          'sobki_admin/navigation.layout_builder',
        ],
      ],
    ];

    return $build;
  }

}
