<?php

declare(strict_types=1);

namespace Drupal\ffmpeg_media_player\Form;

use Drupal\Core\Form\ConfigFormBase;
use Drupal\Core\Form\FormStateInterface;

/**
 * Configuration form for FFmpeg Media Player settings.
 */
final class PlayerSettingsForm extends ConfigFormBase {

  /**
   * {@inheritdoc}
   */
  #[\Override]
  public function getFormId(): string {
    return 'ffmpeg_media_player_settings';
  }

  /**
   * {@inheritdoc}
   *
   * @phpstan-return array<int, string>
   */
  #[\Override]
  protected function getEditableConfigNames(): array {
    return ['ffmpeg_media_player.settings'];
  }

  /**
   * {@inheritdoc}
   *
   * @phpstan-return array<string, mixed>
   */
  #[\Override]
  public function buildForm(array $form, FormStateInterface $form_state): array {
    $config = $this->config('ffmpeg_media_player.settings');

    $form['player_source'] = [
      '#type' => 'radios',
      '#title' => $this->t('Player library source'),
      '#description' => $this->t('Select how the Vidstack player runtime should be loaded. Local mode ships the Vidstack runtime, captions parser, and HLS/DASH helpers from this module. Google Cast is disabled in local mode to avoid third-party runtime requests.'),
      '#options' => [
        'local' => $this->t('Vendored local runtime (recommended; no third-party runtime requests for module-provided playback)'),
        'cdn' => $this->t('<abbr title="Content Delivery Network">CDN</abbr> (Vidstack base library and runtime helpers load externally)'),
      ],
      '#default_value' => $config->get('player_source') ?? 'local',
    ];

    $form['default_theme'] = [
      '#type' => 'select',
      '#title' => $this->t('Default player theme'),
      '#options' => [
        'default' => $this->t('Default - Full controls with quality selector'),
        'minimal' => $this->t('Minimal - Basic playback controls only'),
      ],
      '#default_value' => $config->get('default_theme') ?? 'default',
    ];

    $form['default_aspect_ratio'] = [
      '#type' => 'select',
      '#title' => $this->t('Default aspect ratio'),
      '#options' => [
        'auto' => $this->t('Auto (use intrinsic video dimensions)'),
        '16:9' => $this->t('16:9 (Widescreen)'),
        '4:3' => $this->t('4:3 (Standard)'),
        '21:9' => $this->t('21:9 (Ultrawide)'),
        '1:1' => $this->t('1:1 (Square)'),
        '9:16' => $this->t('9:16 (Portrait)'),
      ],
      '#default_value' => $config->get('default_aspect_ratio') ?? '16:9',
    ];

    $form['optimization'] = [
      '#type' => 'details',
      '#title' => $this->t('Performance & Core Web Vitals'),
      '#open' => TRUE,
    ];

    $form['optimization']['lazy_load_enabled'] = [
      '#type' => 'checkbox',
      '#title' => $this->t('Enable lazy loading by default'),
      '#description' => $this->t('Initialize player only when visible in viewport. Improves page load time and <abbr title="Interaction to Next Paint">INP</abbr> scores.'),
      '#default_value' => $config->get('lazy_load_enabled') ?? TRUE,
    ];

    $form['optimization']['preload_strategy'] = [
      '#type' => 'select',
      '#title' => $this->t('Default preload strategy'),
      '#options' => [
        'none' => $this->t('None - No preloading'),
        'metadata' => $this->t('Metadata - Load video metadata only (recommended)'),
        'auto' => $this->t('Auto - Browser decides what to preload'),
      ],
      '#default_value' => $config->get('preload_strategy') ?? 'metadata',
    ];

    $form['optimization']['poster_loading_priority'] = [
      '#type' => 'select',
      '#title' => $this->t('Poster image loading priority'),
      '#description' => $this->t('High priority helps with <abbr title="Largest Contentful Paint">LCP</abbr> for above-the-fold videos.'),
      '#options' => [
        'high' => $this->t('High - Fetch immediately (for above-the-fold)'),
        'low' => $this->t('Low - Defer loading'),
        'auto' => $this->t('Auto - Browser decides'),
      ],
      '#default_value' => $config->get('poster_loading_priority') ?? 'high',
    ];

    $form['features'] = [
      '#type' => 'details',
      '#title' => $this->t('Default Features'),
      '#open' => TRUE,
    ];

    $form['features']['enable_keyboard_navigation'] = [
      '#type' => 'checkbox',
      '#title' => $this->t('Enable keyboard navigation'),
      '#description' => $this->t('Allow controlling the player with keyboard shortcuts (Space, arrows, etc.).'),
      '#default_value' => $config->get('enable_keyboard_navigation') ?? TRUE,
    ];

    $form['features']['crossorigin'] = [
      '#type' => 'select',
      '#title' => $this->t('<abbr title="Cross-Origin Resource Sharing">CORS</abbr> mode'),
      '#description' => $this->t('Required for <abbr title="HTTP Live Streaming">HLS</abbr>/<abbr title="Dynamic Adaptive Streaming over HTTP">DASH</abbr> from CDN or different origins. Use "anonymous" unless credentials are needed.'),
      '#options' => [
        'anonymous' => $this->t('Anonymous (recommended)'),
        'use-credentials' => $this->t('Use credentials'),
        'none' => $this->t('None (disable CORS)'),
      ],
      '#default_value' => $config->get('crossorigin') ?? 'anonymous',
    ];

    $form['features']['storage_key'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Storage key'),
      '#description' => $this->t('LocalStorage key for persisting volume, captions, and playback time. Leave empty to disable.'),
      '#default_value' => $config->get('storage_key') ?? 'ffmpeg-media',
      '#maxlength' => 64,
    ];

    $form['features']['enable_pip'] = [
      '#type' => 'checkbox',
      '#title' => $this->t('Enable <abbr title="Picture-in-Picture">PiP</abbr>'),
      '#description' => $this->t('Show the PiP button when the browser supports it.'),
      '#default_value' => $config->get('enable_pip') ?? TRUE,
    ];

    $form['features']['enable_playback_speed'] = [
      '#type' => 'checkbox',
      '#title' => $this->t('Enable playback speed controls'),
      '#description' => $this->t('Show playback speed menu in the player controls.'),
      '#default_value' => $config->get('enable_playback_speed') ?? TRUE,
    ];

    return parent::buildForm($form, $form_state);
  }

  /**
   * {@inheritdoc}
   */
  #[\Override]
  public function validateForm(array &$form, FormStateInterface $form_state): void {
    parent::validateForm($form, $form_state);

    $storageKey = (string) $form_state->getValue('storage_key');
    if ($storageKey !== '' && !preg_match('/^[a-zA-Z][a-zA-Z0-9_-]*$/', $storageKey)) {
      $form_state->setErrorByName('storage_key', $this->t('The storage key must start with a letter and contain only letters, numbers, hyphens, and underscores.'));
    }
  }

  /**
   * {@inheritdoc}
   */
  #[\Override]
  public function submitForm(array &$form, FormStateInterface $form_state): void {
    $this->config('ffmpeg_media_player.settings')
      ->set('player_source', $form_state->getValue('player_source'))
      ->set('default_theme', $form_state->getValue('default_theme'))
      ->set('default_aspect_ratio', $form_state->getValue('default_aspect_ratio'))
      ->set('lazy_load_enabled', (bool) $form_state->getValue('lazy_load_enabled'))
      ->set('preload_strategy', $form_state->getValue('preload_strategy'))
      ->set('poster_loading_priority', $form_state->getValue('poster_loading_priority'))
      ->set('enable_keyboard_navigation', (bool) $form_state->getValue('enable_keyboard_navigation'))
      ->set('crossorigin', $form_state->getValue('crossorigin'))
      ->set('storage_key', $form_state->getValue('storage_key'))
      ->set('enable_pip', (bool) $form_state->getValue('enable_pip'))
      ->set('enable_playback_speed', (bool) $form_state->getValue('enable_playback_speed'))
      ->save();

    parent::submitForm($form, $form_state);
  }

}
