import { usePanelChannel } from 'hooks/usePanelChannel';

export const MUSIC_LYRICS_CHANNEL = 'music:lyrics';

const STORAGE_KEY = 'music.lyrics';
// Read once, at import: the play dock re-renders every animation frame, and this is its initial value.
const initialOpen = localStorage.getItem(STORAGE_KEY) === '1';

/**
 * Whether the lyrics panel is open. Shared by the two microphone buttons — the one in the play dock and
 * the one on the album header — which are the same switch shown twice, so it lives in a channel rather
 * than in either component. Seeded from localStorage so the choice survives a reload.
 */
export const useLyricsOpen = () => {
  const [open, setOpen] = usePanelChannel<boolean>(MUSIC_LYRICS_CHANNEL, initialOpen);

  // Deliberately not a functional update: useGlobal applies those to the render-time snapshot, and `open`
  // is that snapshot anyway.
  const toggleLyrics = () => {
    localStorage.setItem(STORAGE_KEY, open ? '0' : '1');
    setOpen(!open);
  };

  return [open, toggleLyrics] as const;
};
