import { useSyncExternalStore, useCallback } from "react";

// --- Original MP3s ---
import workWork from "./assets/sounds/work-work.mp3";
import zugZug from "./assets/sounds/zug-zug.mp3";
import beHappyTo from "./assets/sounds/be-happy-to.mp3";
import iCanDoThat from "./assets/sounds/i-can-do-that.mp3";
import hmm from "./assets/sounds/hmm.mp3";
import iLlTry from "./assets/sounds/i-ll-try.mp3";
import googleDokey from "./assets/sounds/google-dokey.mp3";
import double_ from "./assets/sounds/double.mp3";

// --- WAV Peon sounds ---
import peonAngry1 from "./assets/sounds/PeonAngry1.wav";
import peonAngry2 from "./assets/sounds/PeonAngry2.wav";
import peonAngry3 from "./assets/sounds/PeonAngry3.wav";
import peonAngry4 from "./assets/sounds/PeonAngry4.wav";
import peonDeath from "./assets/sounds/PeonDeath.wav";
import peonReady1 from "./assets/sounds/PeonReady1.wav";
import peonWarcry1 from "./assets/sounds/PeonWarcry1.wav";
import peonWhat1 from "./assets/sounds/PeonWhat1.wav";
import peonWhat2 from "./assets/sounds/PeonWhat2.wav";
import peonWhat3 from "./assets/sounds/PeonWhat3.wav";
import peonWhat4 from "./assets/sounds/PeonWhat4.wav";
import peonYes1 from "./assets/sounds/PeonYes1.wav";
import peonYes2 from "./assets/sounds/PeonYes2.wav";
import peonYes3 from "./assets/sounds/PeonYes3.wav";
import peonYes4 from "./assets/sounds/PeonYes4.wav";
import peonYesAttack1 from "./assets/sounds/PeonYesAttack1.wav";
import peonYesAttack2 from "./assets/sounds/PeonYesAttack2.wav";
import peonYesAttack3 from "./assets/sounds/PeonYesAttack3.wav";

// Sound groups — playSound picks a random variant from the group
const SOUND_GROUPS = {
  // Modal open: "what do you want?" / "ready"
  "what-do-you-want": [peonWhat1, peonWhat2, peonWhat3, peonWhat4, peonReady1],
  // Modal close: grumble on dismiss
  swobu: [peonAngry1, peonAngry2, peonAngry3, peonAngry4],
  // Create task: affirmation
  "work-work": [peonYes1, peonYes2, peonYes3, peonYes4, workWork],
  // Update task/feature: acknowledgment
  "zug-zug": [peonYesAttack1, peonYesAttack2, peonYesAttack3, zugZug],
  // Create feature
  "i-can-do-that": [iCanDoThat, peonReady1],
  // Create project
  "be-happy-to": [beHappyTo, peonReady1],
  // Create work log
  "google-dokey": [googleDokey, peonYes1, peonYes2],
  // Delete
  death: [peonDeath],
  // Error
  hmm: [hmm],
  // External change sounds (keep singular)
  "i-ll-try": [iLlTry],
  double: [double_],
  // Warcry (available for future use)
  warcry: [peonWarcry1],
} as const;

export type PeonSound = keyof typeof SOUND_GROUPS;

// Preload all sounds so the first playSound() call doesn't race against fetch
const allUrls = Object.values(SOUND_GROUPS).flat();
const preloaded = new Map<string, HTMLAudioElement>();
for (const url of allUrls) {
  if (!preloaded.has(url)) {
    const audio = new Audio(url);
    audio.preload = "auto";
    preloaded.set(url, audio);
  }
}

function pickRandom<T>(arr: readonly T[]): T {
  return arr[Math.floor(Math.random() * arr.length)];
}

const STORAGE_KEY = "peon-sound-enabled";

let enabled = localStorage.getItem(STORAGE_KEY) !== "false";
const listeners = new Set<() => void>();

function getSnapshot() {
  return enabled;
}

function subscribe(cb: () => void) {
  listeners.add(cb);
  return () => listeners.delete(cb);
}

function setEnabled(value: boolean) {
  enabled = value;
  localStorage.setItem(STORAGE_KEY, String(value));
  listeners.forEach((cb) => cb());
}

export function playSound(name: PeonSound, volume = 0.5) {
  if (!enabled) return;
  const url = pickRandom(SOUND_GROUPS[name]);
  const cached = preloaded.get(url);
  const clone = (cached ? cached.cloneNode() : new Audio(url)) as HTMLAudioElement;
  clone.volume = volume;
  clone.play().catch(() => {});
}

export function useSoundEnabled(): [boolean, () => void] {
  const value = useSyncExternalStore(subscribe, getSnapshot);
  const toggle = useCallback(() => setEnabled(!enabled), []);
  return [value, toggle];
}
