import { atom } from 'jotai';
import { CallEmbed } from '../plugins/call';

const baseCallEmbedAtom = atom<CallEmbed | undefined>(undefined);

export const callEmbedAtom = atom<CallEmbed | undefined, [CallEmbed | undefined], void>(
  (get) => get(baseCallEmbedAtom),
  (get, set, callEmbed) => {
    const prevCallEmbed = get(baseCallEmbedAtom);
    if (callEmbed === prevCallEmbed) return;

    if (prevCallEmbed) {
      prevCallEmbed.dispose();
    }

    set(baseCallEmbedAtom, callEmbed);
  }
);

export const callChatAtom = atom<boolean>(false);

// In-call loudspeaker state (true = громкая связь / speaker, false = earpiece).
// Android-only — driven by `useCallSpeaker` via the native AudioRoute plugin;
// reset to earpiece on every call teardown. Default false because a 1:1 voice
// call should start on the earpiece, like a phone call.
export const callSpeakerAtom = atom<boolean>(false);
