'use client';

import { useCallback, useState } from 'react';

import type { ChatAttachment } from '../types';

export type ChatLightboxScope = 'message' | 'conversation';

export interface ChatLightboxState {
  gallery: ChatAttachment[];
  index: number;
}

export interface UseChatLightboxReturn {
  state: ChatLightboxState | null;
  open: (att: ChatAttachment, gallery?: ChatAttachment[]) => void;
  close: () => void;
}

/** Tiny state container for an image lightbox. The host owns the modal +
 *  `<LazyImageViewer>` mount; we just track which gallery to show. */
export function useChatLightbox(): UseChatLightboxReturn {
  const [state, setState] = useState<ChatLightboxState | null>(null);

  const open = useCallback((att: ChatAttachment, gallery?: ChatAttachment[]) => {
    const list = gallery && gallery.length ? gallery : [att];
    const idx = list.findIndex((a) => a.id === att.id);
    setState({ gallery: list, index: idx === -1 ? 0 : idx });
  }, []);

  const close = useCallback(() => setState(null), []);

  return { state, open, close };
}
