"use client";

import { useEffect, useRef } from "react";

export function AutoSound() {
  const audioRef = useRef<HTMLAudioElement>(null);
  const hasTriedRef = useRef(false);

  useEffect(() => {
    if (hasTriedRef.current) return;
    hasTriedRef.current = true;

    const audio = audioRef.current;
    if (!audio) return;

    // Direkt çalmayı dene
    const tryPlay = () => {
      audio.volume = 0.7;
      audio.play().catch(() => {
        // Başarısız olursa etkileşim bekle
        const playOnInteraction = () => {
          audio.play().catch(() => {});
          cleanup();
        };

        const events = ["click", "touchstart", "scroll", "mousemove", "keydown"];
        
        const cleanup = () => {
          events.forEach(e => {
            document.removeEventListener(e, playOnInteraction);
          });
        };

        events.forEach(e => {
          document.addEventListener(e, playOnInteraction, { once: true, passive: true });
        });
      });
    };

    // Sayfa yüklenince hemen dene
    tryPlay();

    // Biraz bekleyip tekrar dene
    setTimeout(tryPlay, 100);
    setTimeout(tryPlay, 500);
    setTimeout(tryPlay, 1000);

  }, []);

  return (
    <audio 
      ref={audioRef} 
      preload="auto" 
      autoPlay
      playsInline
    >
      <source src="/wolf.mp3" type="audio/mpeg" />
    </audio>
  );
}

