/* kit/animacao.jsx — a animação pronta (Lottie) da biblioteca, quadro a quadro.
 *
 * {"tipo":"kit","peca":"animacao","src":"midia/animacoes/1f525.json","x":…,"y":…,"largura":…,"altura":…,
 *  "loop":true,"velocidade":1}
 *
 * O Lottie é vetor: sai nítido em qualquer tamanho. Ele NÃO toca sozinho
 * (o relógio do navegador faria cada render sair diferente): a cada quadro o
 * tempo do elemento vira o quadro da animação (goToAndStop). Os arquivos vêm
 * de colecao.js (o Noto Emoji animado do Google, CC BY 4.0). */
import React, { useEffect, useRef, useState } from 'react';
import { staticFile, delayRender, continueRender } from 'remotion';
import lottie from 'lottie-web';

export function Animacao({ el, t }) {
  const caixa = useRef(null);
  const [anim, setAnim] = useState(null);
  const [espera] = useState(() => delayRender('animação ' + el.src));
  useEffect(() => {
    let vivo = true;
    let a = null;
    fetch(/^https?:/.test(el.src) ? el.src : staticFile(el.src))
      .then((r) => r.json())
      .then((dados) => {
        if (!vivo || !caixa.current) return;
        a = lottie.loadAnimation({ container: caixa.current, renderer: 'svg', loop: false, autoplay: false, animationData: dados,
          rendererSettings: { preserveAspectRatio: 'xMidYMid meet' } });
        a.addEventListener('DOMLoaded', () => { setAnim(a); continueRender(espera); });
      })
      .catch(() => continueRender(espera));
    return () => { vivo = false; if (a) a.destroy(); };
  }, [el.src]);
  if (anim) {
    const total = Math.max(1, anim.totalFrames - 1);
    const q = Math.max(0, t) * (anim.frameRate || 30) * (el.velocidade || 1);
    anim.goToAndStop(el.loop === false ? Math.min(q, total) : q % total, true);
  }
  const w = el.largura || 300, h = el.altura || w;
  return <div ref={caixa} style={{ position: 'absolute', left: el.x || 0, top: el.y || 0, width: w, height: h }} />;
}

export const ANIMACAO = { animacao: Animacao };
