'use client';

/**
 * Bangla speech-to-text via the browser SpeechRecognition API (Chrome/Edge).
 * Best-effort: returns a controller with start/stop, or null if unsupported.
 */

type Rec = any; // SpeechRecognition isn't in the standard TS lib DOM types

export interface SttController {
  start: () => void;
  stop: () => void;
}

export function isSttSupported(): boolean {
  if (typeof window === 'undefined') return false;
  return Boolean((window as any).SpeechRecognition || (window as any).webkitSpeechRecognition);
}

export function createStt(handlers: {
  onResult: (text: string) => void;
  onEnd?: () => void;
  onError?: (msg: string) => void;
}): SttController | null {
  if (typeof window === 'undefined') return null;
  const Ctor = (window as any).SpeechRecognition || (window as any).webkitSpeechRecognition;
  if (!Ctor) return null;

  const rec: Rec = new Ctor();
  rec.lang = 'bn-BD';
  rec.interimResults = false;
  rec.maxAlternatives = 1;
  rec.continuous = false;

  rec.onresult = (e: any) => {
    const text = e?.results?.[0]?.[0]?.transcript ?? '';
    if (text) handlers.onResult(text);
  };
  rec.onerror = (e: any) => handlers.onError?.(e?.error ?? 'error');
  rec.onend = () => handlers.onEnd?.();

  return {
    start: () => {
      try {
        rec.start();
      } catch {
        /* already started */
      }
    },
    stop: () => {
      try {
        rec.stop();
      } catch {
        /* not running */
      }
    },
  };
}
