<?php

namespace Drupal\artisan;

use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\Core\Theme\ComponentPluginManager;

/**
 * Artisan customizations.
 */
class ArtisanCustomizations implements ArtisanCustomizationsInterface {

  use StringTranslationTrait;

  /**
   * Used to get all components.
   *
   * @var \Drupal\Core\Theme\ComponentPluginManager
   */
  protected ComponentPluginManager $componentPluginManager;

  public function __construct() {
    $this->componentPluginManager = \Drupal::service('plugin.manager.sdc');
  }

  /**
   * {@inheritdoc}
   */
  public function themeSettingsAlter(&$form, FormStateInterface $form_state, string $theme): void {
    $components = $this->componentPluginManager->getAllComponents();
    // Skip for main theme, these options should only appear for subthemes.
    if ($theme == 'artisan') {
      $form['info'] = [
        '#markup' => $this->t('IMPORTANT: Go to your subtheme settings to customize your theme. Or use "artisan_starterkit" as a preview.'),
      ];
      return;
    }
    // Vite dev URL configuration.
    $request = \Drupal::request();
    $form['vite_dev_host'] = [
      '#title' => $this->t('Vite: Dev host'),
      '#type' => 'url',
      '#default_value' => theme_get_setting('vite_dev_host', $theme),
      '#description' => $this->t('It will allow hot module replacement at vite dev mode. Default: @default', [
        '@default' => sprintf('%s://%s', $request->getScheme(), $request->getHost()),
      ]),
    ];

    $form['vite_dev_port'] = [
      '#title' => $this->t('Vite: Dev port'),
      '#type' => 'url',
      '#default_value' => theme_get_setting('vite_dev_port', $theme),
      '#description' => $this->t('It will allow hot module replacement at vite dev mode. Default: 3000'),
    ];

    $footer_components = array_filter($components, function ($component) {
      return $component->metadata->group === 'Artisan Footer';
    });
    $footer_options = [];
    foreach ($footer_components as $component) {
      if (isset($component->metadata->id)) {
        $footer_options[$component->metadata->id] = $component->metadata->name;
      }
    }
    $form['footer_type'] = [
      '#type' => 'select',
      '#title' => $this->t('Footer'),
      '#options' => $footer_options,
      '#default_value' => theme_get_setting('footer_type', $theme) ?? '',
      '#description' => $this->t('Select the footer type to use on your site.'),
    ];
  }

}
