<?php

declare(strict_types=1);

namespace Drupal\native_observability\Service;

use Drupal\Core\Link;
use Drupal\Core\Routing\UrlGeneratorInterface;
use Drupal\Core\StringTranslation\TranslationInterface;
use Drupal\Core\Url;

/**
 * Builds safe, reusable UI render arrays for Native Observability.
 *
 * Why this service exists:
 * - Centralizes UI patterns (links/buttons) across controllers and forms.
 * - Prevents Twig Attribute rendering issues (e.g. Url objects in #attributes).
 * - Keeps controllers focused on orchestration, not UI minutiae.
 *
 * IMPORTANT RULE:
 * - Never place Url objects inside '#attributes'. Attributes must contain only
 *   scalars (strings/ints) or arrays of scalars.
 */
final readonly class NativeObservabilityUiBuilder {

  /**
   * Constructs the UI builder.
   *
   * @param \Drupal\Core\StringTranslation\TranslationInterface $translator
   *   The string translation service.
   * @param \Drupal\Core\Routing\UrlGeneratorInterface $url_generator
   *   The URL generator.
   */
  public function __construct(
    private TranslationInterface $translator,
    private UrlGeneratorInterface $url_generator,
  ) {
  }

  /**
   * Builds the "Delete ALL" traces action link.
   */
  public function deleteAllTracesButton(): array {
    $path = $this->url_generator->generateFromRoute('native_observability.traces_delete_all');

    return [
      '#type' => 'link',
      '#title' => $this->translator->translate('Delete ALL'),
      '#url' => Url::fromUri('internal:' . $path),
      '#attributes' => [
        'class' => ['button', 'button--danger'],
      ],
    ];
  }

  /**
   * Builds a "Reset" button link for the traces listing page.
   *
   * @return array
   *   Renderable link array.
   */
  public function resetFiltersButton(): array {
    $build = Link::fromTextAndUrl(
      $this->translator->translate('Reset'),
      Url::fromRoute('native_observability.traces')
    )->toRenderable();

    $build['#attributes']['class'] = ['button', 'button--secondary'];

    return $build;
  }

  /**
   * Builds a back link to the traces listing.
   *
   * @return array
   *   A renderable link array.
   */
  public function backToTracesButton(): array {
    return Link::fromTextAndUrl(
        $this->translator->translate('← Back to traces'),
        Url::fromRoute('native_observability.traces')
      )->toRenderable() + [
        '#attributes' => [
          'class' => ['button'],
        ],
      ];
  }

}
