import type { GlitchHostBridge } from './types';

export const HOST_SOUND_EVENT = 'glitch:play-sound';
export const HOST_STOP_SOUND_EVENT = 'glitch:stop-sound';
export const HOST_EMIT_PREFIX = 'glitch:host:';

export const SOUND_IDS = {
  click: 'ui.button_click',
  hover: 'ui.button_hover',
  computeStart: 'machine.compute_start',
  computeStep: 'machine.compute_step',
  computeDone: 'machine.compute_done',
  verdictStable: 'machine.verdict_stable',
  verdictAlert: 'machine.verdict_alert'
} as const;

export type SoundId = (typeof SOUND_IDS)[keyof typeof SOUND_IDS];

function dispatchWindowEvent<T>(type: string, detail: T) {
  if (typeof window === 'undefined') return;
  window.dispatchEvent(new CustomEvent(type, { detail }));
}

export function safePlaySound(
  host: GlitchHostBridge | undefined,
  id: string,
  payload?: Record<string, unknown>
) {
  try {
    if (host?.playSound) {
      host.playSound(id, payload);
      return;
    }
  } catch {
    // Host bridge errors should not break the component.
  }

  dispatchWindowEvent(HOST_SOUND_EVENT, { id, payload });
}

export function safeStopSound(
  host: GlitchHostBridge | undefined,
  id: string,
  payload?: Record<string, unknown>
) {
  try {
    if (host?.stopSound) {
      host.stopSound(id, payload);
      return;
    }
  } catch {
    // Host bridge errors should not break the component.
  }

  dispatchWindowEvent(HOST_STOP_SOUND_EVENT, { id, payload });
}

export function safeEmit(host: GlitchHostBridge | undefined, type: string, payload?: unknown) {
  try {
    if (host?.emit) {
      host.emit(type, payload);
      return;
    }
  } catch {
    // Host bridge errors should not break the component.
  }

  dispatchWindowEvent(`${HOST_EMIT_PREFIX}${type}`, payload);
}
