'use client';
// lib/notificationSound.ts

let audioCtx: AudioContext | null = null;

function getCtx(): AudioContext {
  if (!audioCtx) {
    audioCtx = new (window.AudioContext || (window as any).webkitAudioContext)();
  }
  return audioCtx;
}

export function playNotificationSound(type: 'default' | 'success' | 'error' = 'default'): void {
  try {
    if (typeof window === 'undefined') return;

    const ctx = getCtx();
    if (ctx.state === 'suspended') ctx.resume();

    const notes: Record<string, number[]> = {
      default: [880, 1100],
      success: [880, 1320],
      error:   [660, 440],
    };

    const freqs = notes[type] ?? notes.default;
    const now   = ctx.currentTime;

    freqs.forEach((freq, i) => {
      const osc  = ctx.createOscillator();
      const gain = ctx.createGain();

      osc.type = 'sine';
      osc.frequency.setValueAtTime(freq, now + i * 0.12);

      gain.gain.setValueAtTime(0, now + i * 0.12);
      gain.gain.linearRampToValueAtTime(0.18, now + i * 0.12 + 0.02);
      gain.gain.exponentialRampToValueAtTime(0.001, now + i * 0.12 + 0.35);

      osc.connect(gain);
      gain.connect(ctx.destination);

      osc.start(now + i * 0.12);
      osc.stop(now + i * 0.12 + 0.38);
    });
  } catch {
    // ignore — audio is not critical
  }
}