'use client';
import { useEffect, useRef, useState } from 'react';
import type { AnimationItem } from 'lottie-web';

export default function ReactExample() {
  const host = useRef<HTMLDivElement>(null);
  const player = useRef<AnimationItem | null>(null);
  const [status, setStatus] = useState('Loading animation');
  const [ready, setReady] = useState(false);
  useEffect(() => {
    let disposed = false;
    const controller = new AbortController();
    const reduced = matchMedia('(prefers-reduced-motion: reduce)');
    const preference = () => {
      if (reduced.matches) player.current?.goToAndStop(0, true);
      else player.current?.play();
    };
    reduced.addEventListener('change', preference);
    void (async () => {
      try {
        const [{ default: lottie }, response] = await Promise.all([
          import('lottie-web/build/player/lottie_light'),
          fetch('/examples/animation.json', { signal: controller.signal }),
        ]);
        if (!response.ok)
          throw new Error('Animation file could not be fetched');
        const animationData = await response.json();
        if (disposed || !host.current) return;
        const animation = lottie.loadAnimation({
          container: host.current,
          renderer: 'svg',
          animationData,
          loop: true,
          autoplay: false,
        });
        player.current = animation;
        animation.addEventListener('DOMLoaded', () => {
          if (disposed) return;
          setReady(true);
          setStatus('Example animation ready');
          preference();
        });
        animation.addEventListener('data_failed', () => {
          if (!disposed) setStatus('Animation could not be rendered');
        });
      } catch {
        if (!disposed)
          setStatus(
            'Animation could not load. Check the file path and network.',
          );
      }
    })();
    return () => {
      disposed = true;
      controller.abort();
      reduced.removeEventListener('change', preference);
      player.current?.destroy();
      player.current = null;
    };
  }, []);
  return (
    <section aria-label="React Lottie example">
      <div
        ref={host}
        aria-hidden="true"
        style={{ width: 240, height: 240, maxWidth: '100%', margin: 'auto' }}
      />
      <output>{status}</output>
      <button disabled={!ready} onClick={() => player.current?.play()}>
        Play example
      </button>{' '}
      <button disabled={!ready} onClick={() => player.current?.pause()}>
        Pause example
      </button>
      <p>
        This decorative animation is separate from your application loading
        status.
      </p>
    </section>
  );
}
