import React, { useEffect, useState } from 'react';
import JSZip from 'jszip';

const TestAnimation = () => {
  const [images, setImages] = useState([]);
  const [currentFrame, setCurrentFrame] = useState(0);
  const [loading, setLoading] = useState(true);
  const frameRate = 60; 

  useEffect(() => {
    const loadImages = async () => {
      const zip = new JSZip();
      try {
        const response = await fetch('src/assets/mainCharacters/M_Porsche_cross_arm.zip');
        if (!response.ok) {
          throw new Error('Network response was not ok');
        }
        const data = await response.arrayBuffer();
        const zipContent = await zip.loadAsync(data);

        const imgPromises = [];
        zipContent.forEach((relativePath, file) => {
          if (file.name.endsWith('.webp')) {
            imgPromises.push(
              file.async('base64').then(base64 => {
                return `data:image/webp;base64,${base64}`;
              })
            );
          }
        });

        const imgUrls = await Promise.all(imgPromises);

        // console.log('Loaded images:', imgUrls); 

        if (imgUrls.length === 0) {
          console.error('No images found in the ZIP file.');
        }

        setImages(imgUrls);
      } catch (error) {
        console.error('Error loading images:', error);
      } finally {
        setLoading(false); 
      }
    };

    loadImages();

  }, []);

  useEffect(() => {
    if (images.length > 0) {
      const interval = setInterval(() => {
        setCurrentFrame((prevFrame) => (prevFrame + 1) % images.length);
      }, frameRate);

      return () => clearInterval(interval);
    }
  }, [images]);

  if (loading) {
    return <div>Loading...</div>; 
  } else {
    return (
      <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center' }}>
        {images.length > 0 ? (
          <img
            src={images[currentFrame]}
            alt={`Animation frame ${currentFrame + 1}`}
            style={{ maxWidth: '500px', height: 'auto' }} 
          />
        ) : (
          <div>No images to display.</div> 
        )}
      </div>
    );
  }
};

export default TestAnimation;
