// Browser ringtone using Web Audio API — no external file needed
let audioContext: AudioContext | null = null;
let ringtoneInterval: number | null = null;

function playTone(ctx: AudioContext, frequency: number, duration: number, startTime: number) {
    const osc = ctx.createOscillator();
    const gain = ctx.createGain();
    osc.type = 'sine';
    osc.frequency.value = frequency;
    gain.gain.setValueAtTime(0.3, startTime);
    gain.gain.exponentialRampToValueAtTime(0.01, startTime + duration);
    osc.connect(gain);
    gain.connect(ctx.destination);
    osc.start(startTime);
    osc.stop(startTime + duration);
}

function playRingBurst() {
    if (!audioContext) audioContext = new AudioContext();
    const now = audioContext.currentTime;
    // Two-tone ring: 440Hz + 480Hz (standard phone ring)
    playTone(audioContext, 440, 0.4, now);
    playTone(audioContext, 480, 0.4, now);
    playTone(audioContext, 440, 0.4, now + 0.5);
    playTone(audioContext, 480, 0.4, now + 0.5);
}

export function startRingtone() {
    stopRingtone();
    playRingBurst();
    // Repeat every 3 seconds (ring-pause-ring pattern)
    ringtoneInterval = window.setInterval(playRingBurst, 3000);
}

export function stopRingtone() {
    if (ringtoneInterval !== null) {
        clearInterval(ringtoneInterval);
        ringtoneInterval = null;
    }
}
