import { useState, useEffect, useRef, useCallback } from 'react';
import styles from '../styles/Background.module.css';

const MusicPlayer = ({ onReady }: { onReady: (unmute: () => void) => void }) => {
  const [isMuted, setIsMuted] = useState(false);
  const audioRef = useRef<HTMLAudioElement | null>(null);

  const play = useCallback(() => {
    if (audioRef.current) {
      audioRef.current.play().catch(error => console.log("Audio play failed:", error));
    }
  }, []);

  const unmute = useCallback(() => {
    if (audioRef.current) {
      audioRef.current.muted = false;
      setIsMuted(false);
      play();
    }
  }, [play]);

  useEffect(() => {
    if (audioRef.current) {
      audioRef.current.volume = 0.5;
      audioRef.current.loop = true;
      audioRef.current.muted = true;
      play();
      onReady(unmute);
    }
  }, [play, onReady, unmute]);

  const toggleMute = () => {
    if (audioRef.current) {
      audioRef.current.muted = !isMuted;
      setIsMuted(!isMuted);
      if (!isMuted) {
        play();
      }
    }
  };

  return (
    <>
      <audio ref={audioRef} src="https://olive-fashionable-swallow-983.mypinata.cloud/ipfs/QmT74A6AVYTXywz7SGGuvqSqgoidV2SDCn9jGW5KEiRYtR" />
      <button onClick={toggleMute} className={styles.musicButton}>
        {isMuted ? '🔇' : '🔊'}
      </button>
    </>
  );
};

export default MusicPlayer;
