<?php

declare(strict_types=1);

namespace Drupal\ffmpeg_media\Hook;

use Drupal\Core\Hook\Attribute\Hook;

/**
 * Theme-related hook implementations.
 */
final class ThemeHooks {

  /**
   * Implements hook_theme().
   *
   * @phpstan-return array<string, mixed>
   */
  #[Hook('theme')]
  public function theme(): array {
    return [
      'ffmpeg_media_progress' => [
        'variables' => [
          'media_id' => NULL,
          'progress' => NULL,
        ],
        'template' => 'ffmpeg-media-progress',
      ],
      'ffmpeg_media_profiles' => [
        'variables' => [
          'profiles' => [],
          'profile_groups' => [],
        ],
        'template' => 'ffmpeg-media-profiles',
      ],
      'ffmpeg_media_video' => [
        'variables' => [
          'media' => NULL,
          'sources' => [],
          'poster' => NULL,
          'attributes' => [],
        ],
        'template' => 'ffmpeg-media-video',
      ],
    ];
  }

  /**
   * Prepares variables for the progress template.
   *
   * Formats raw estimated_remaining seconds into a human-readable string.
   *
   * @param array<string, mixed> &$variables
   *   Template variables.
   */
  #[Hook('preprocess_ffmpeg_media_progress')]
  public function preprocessProgress(array &$variables): void {
    $progress = $variables['progress'] ?? NULL;
    if (!is_array($progress)) {
      return;
    }

    $seconds = $progress['estimated_remaining'] ?? NULL;
    if ($seconds !== NULL && is_numeric($seconds) && (int) $seconds > 0) {
      $variables['progress']['estimated_remaining_formatted'] = self::formatDuration((int) $seconds);
    }
    else {
      $variables['progress']['estimated_remaining_formatted'] = NULL;
    }
  }

  /**
   * Formats a duration in seconds to a compact human-readable string.
   *
   * @param int $seconds
   *   Duration in seconds.
   *
   * @return string
   *   Formatted duration (e.g., "45s", "2m 15s", "1h 30m").
   */
  private static function formatDuration(int $seconds): string {
    if ($seconds < 60) {
      return $seconds . 's';
    }
    if ($seconds < 3600) {
      return intdiv($seconds, 60) . 'm ' . ($seconds % 60) . 's';
    }
    return intdiv($seconds, 3600) . 'h ' . intdiv($seconds % 3600, 60) . 'm';
  }

}
