import { useAtom } from 'jotai';
import { useCallback } from 'react';
import { callSpeakerAtom } from '../state/callEmbed';
import { callAudioRoute } from '../plugins/call/callAudioRoute';

// In-call loudspeaker ⇄ earpiece toggle, backed by the native AudioRoute
// plugin. The atom holds the UI truth; `toggle` optimistically flips it then
// reconciles to the route the native side actually reports (an OEM WebView may
// refuse the request). `available` is false on web / iOS, where the OS owns
// output routing and the UI hides the control.
export const useCallSpeaker = (): {
  speaker: boolean;
  toggle: () => void;
  available: boolean;
} => {
  const [speaker, setSpeaker] = useAtom(callSpeakerAtom);

  const toggle = useCallback(() => {
    const next = !speaker;
    setSpeaker(next);
    callAudioRoute.setSpeaker(next).then(
      (actual) => setSpeaker(actual),
      () => undefined
    );
  }, [speaker, setSpeaker]);

  return { speaker, toggle, available: callAudioRoute.available() };
};
