import { useEffect } from 'react';
import { useSetAtom } from 'jotai';
import { manualDndAtom } from '../state/manualDnd';
import { tauriInvoke, useTauriEvent } from './useTauri';

/** Detail shape of the `lotus-dnd-changed` event emitted by the native side. */
type DndChangedDetail = {
  active: boolean;
};

/**
 * P6-1 — Tray "Do Not Disturb" → notification suppression (desktop). Subscribes
 * to the native `lotus-dnd-changed` event (emitted when the user toggles the
 * tray "Do Not Disturb" item, `{ active }`) and mirrors it into `manualDndAtom`,
 * which the notification gate reads to suppress notifications while DND is on.
 * Inert in the browser, since `useTauriEvent` only listens under Tauri.
 */
export function useTauriDnd(): void {
  const setDnd = useSetAtom(manualDndAtom);

  useTauriEvent<DndChangedDetail>('lotus-dnd-changed', ({ active }) => setDnd(active));

  // Re-hydrate on mount. The tray CheckMenuItem persists its checkstate, but
  // `manualDndAtom` is in-memory and resets to false on every reload (the
  // custom-chrome toggle, logout). Without this the tray could show DND ON while
  // notifications resume firing. Query the native tray state (`get_tray_dnd`) so
  // they stay in sync. No-op in the browser.
  useEffect(() => {
    tauriInvoke()?.('get_tray_dnd')
      .then((active) => {
        if (typeof active === 'boolean') setDnd(active);
      })
      .catch(() => undefined);
  }, [setDnd]);
}
