import * as store from './store.js';
import { getAsset } from './theme.js';

let ctx = null;
const buffers = {};
const audioElements = {};
const volumes = { ui: 0.5, game: 0.7, reward: 0.8 };

const sounds = {
  click: { src: null, freq: 800, dur: 0.05 },
  move: { src: null, freq: 300, dur: 0.1 },
  capture: { src: null, freq: 200, dur: 0.15 },
  check: { src: null, freq: 600, dur: 0.2 },
  castle: { src: null, freq: 400, dur: 0.12 },
  gameOver: { src: null, freq: 150, dur: 0.4 },
  win: { src: null, freq: 523, dur: 0.5 },
  lose: { src: null, freq: 180, dur: 0.6 },
  coin: { src: null, freq: 1200, dur: 0.08 },
  levelUp: { src: null, freq: 880, dur: 0.6 },
  notification: { src: null, freq: 700, dur: 0.15 },
  dice: { src: null, freq: 250, dur: 0.3 },
  place: { src: null, freq: 350, dur: 0.1 },
  reward: { src: null, freq: 660, dur: 0.4 },
  match_found: { src: null, freq: 740, dur: 0.3 },
  sfx_dice_shake: { src: null, freq: 180, dur: 0.4 },
  sfx_boost: { src: null, freq: 880, dur: 0.25 },
  sfx_piece_home: { src: null, freq: 660, dur: 0.35 },
  sfx_turn_start: { src: null, freq: 520, dur: 0.15 },
  sfx_emote: { src: null, freq: 440, dur: 0.08 },
  sfx_bg_dice_roll: { src: null, freq: 180, dur: 0.4 },
  sfx_bg_piece_move: { src: null, freq: 400, dur: 0.06 },
  sfx_bg_piece_hit: { src: null, freq: 150, dur: 0.2 },
  sfx_bg_bear_off: { src: null, freq: 600, dur: 0.25 },
  sfx_bg_double: { src: null, freq: 120, dur: 0.3 },
  sfx_bg_win_game: { src: null, freq: 523, dur: 0.5 },
  sfx_bg_win_match: { src: null, freq: 660, dur: 0.7 }
};

function getCtx() {
  if (!ctx) {
    ctx = new (window.AudioContext || window.webkitAudioContext)();
  }
  return ctx;
}

export function init() {
  document.addEventListener('touchstart', resume, { once: true });
  document.addEventListener('click', resume, { once: true });
  preloadCustomAudio();
}

function resume() {
  const c = getCtx();
  if (c.state === 'suspended') c.resume();
}

function preloadCustomAudio() {
  for (const name of Object.keys(sounds)) {
    // Keys starting with sfx_ are already the full slot name
    const slot = name.startsWith('sfx_') ? name : 'sfx_' + name;
    const url = getAsset(slot);
    if (url) {
      const audio = new Audio();
      audio.preload = 'auto';
      audio.src = url;
      audioElements[name] = audio;
    }
  }
}

export function play(name, category = 'ui') {
  if (!store.get('audioEnabled')) return;

  // Use custom audio file if uploaded via branding
  if (audioElements[name]) {
    const el = audioElements[name];
    el.volume = volumes[category] || 0.5;
    el.currentTime = 0;
    el.play().catch(() => {});
    return;
  }

  // Fallback: synthesized sound
  const sound = sounds[name];
  if (!sound) return;

  const c = getCtx();
  if (c.state === 'suspended') return;

  const osc = c.createOscillator();
  const gain = c.createGain();
  osc.connect(gain);
  gain.connect(c.destination);

  osc.frequency.value = sound.freq;
  osc.type = name === 'click' ? 'sine' : 'triangle';
  gain.gain.setValueAtTime(volumes[category] || 0.5, c.currentTime);
  gain.gain.exponentialRampToValueAtTime(0.001, c.currentTime + sound.dur);

  osc.start(c.currentTime);
  osc.stop(c.currentTime + sound.dur);
}

export function playSequence(notes, interval = 100) {
  notes.forEach((note, i) => {
    setTimeout(() => play(note), i * interval);
  });
}

export function setVolume(category, vol) {
  volumes[category] = Math.max(0, Math.min(1, vol));
}
