<?php
/**
 * Injeta ANIM_SPINS e ANIM_SPEED no template HTML.
 * - $speed pode ser fator (0.3..3.0) ou percentual (30..300).
 */
function inject_anim_into_template(string $html, $spinsRaw, $speedRaw): string{
  $spins = (int)($spinsRaw ?? 2); if($spins<0)$spins=0; if($spins>30)$spins=30;
  $speed = (float)($speedRaw ?? 1.0);
  if($speed > 3.0) $speed /= 100.0; // se veio 250 -> 2.5
  if($speed < 0.3) $speed = 0.3;
  if($speed > 3.0) $speed = 3.0;

  // Substitui qualquer definição anterior das constantes
  $html = preg_replace('/const\s+ANIM_SPINS\s*=\s*[^;]*;/', 'const ANIM_SPINS = '.$spins.';', $html);
  $html = preg_replace('/const\s+ANIM_SPEED\s*=\s*[^;]*;/', 'const ANIM_SPEED = '.number_format($speed,3,'.','').';', $html);

  // Fallback: se o template usar let/var ao invés de const
  if (strpos($html, 'ANIM_SPINS') === false) {
    $html = preg_replace('/(<script[^>]*>)/i', "$1\nvar ANIM_SPINS=".$spins.";", $html, 1);
  }
  if (strpos($html, 'ANIM_SPEED') === false) {
    $html = preg_replace('/(<script[^>]*>)/i', "$1\nvar ANIM_SPEED=".number_format($speed,3,'.','').";", $html, 1);
  }
  return $html;
}
