let audioContext = null;
let ringTimer = null;

function getAudioContext() {
  if (!audioContext) {
    audioContext = new AudioContext();
  }
  return audioContext;
}

function playTone(frequency, startTime, duration) {
  const context = getAudioContext();
  const oscillator = context.createOscillator();
  const gain = context.createGain();

  oscillator.type = 'sine';
  oscillator.frequency.setValueAtTime(frequency, startTime);
  gain.gain.setValueAtTime(0.0001, startTime);
  gain.gain.exponentialRampToValueAtTime(0.22, startTime + 0.03);
  gain.gain.exponentialRampToValueAtTime(0.0001, startTime + duration);

  oscillator.connect(gain);
  gain.connect(context.destination);
  oscillator.start(startTime);
  oscillator.stop(startTime + duration + 0.02);
}

async function playRingtone() {
  const context = getAudioContext();
  if (context.state === 'suspended') {
    await context.resume();
  }

  const now = context.currentTime;
  playTone(880, now, 0.22);
  playTone(1174.66, now + 0.27, 0.22);
  playTone(1567.98, now + 0.54, 0.32);
}

function startRingtoneLoop() {
  if (ringTimer) return;
  playRingtone();
  ringTimer = setInterval(playRingtone, 1400);
}

function stopRingtoneLoop() {
  if (ringTimer) {
    clearInterval(ringTimer);
    ringTimer = null;
  }
  if (audioContext) {
    audioContext.suspend();
  }
}

chrome.runtime.onMessage.addListener((message) => {
  if (message.target !== 'offscreen') return;

  if (message.action === 'playRingtone') {
    startRingtoneLoop();
  } else if (message.action === 'stopRingtone') {
    stopRingtoneLoop();
  }
});
