'use client';

/**
 * `@djangocfg/ui-tools/chat` subpath entrypoint.
 *
 * This file is the public surface consumers see when they
 * `import … from '@djangocfg/ui-tools/chat'`. It is designed so that the
 * heavy chat UI (~hundreds of KB across MessageList, Composer, ToolCalls,
 * Attachments, MarkdownMessage transitively) loads only when one of the
 * `Lazy*` wrappers actually mounts.
 *
 * Rules of thumb:
 * - **Heavy** (ChatRoot, ChatLauncher, ChatFAB, ChatDock, MessageList,
 *   MessageBubble, Composer, ToolCalls, Attachments*, ChatHeader*, …) —
 *   loaded only via `Lazy*` wrappers below. Do NOT add synchronous
 *   re-exports for these from this file.
 * - **Light** (types, config constants, pure core reducer/utils,
 *   transports, hooks without UI, audio prefs, draft sanitizer) —
 *   re-exported synchronously here. Types are erased at compile time;
 *   helpers and hooks pull in no UI components.
 *
 * Consumers that need synchronous access to the heavy components
 * (custom chat layouts, Storybook stories) can import from the root
 * barrel `@djangocfg/ui-tools` instead.
 */

import { createLazyComponent, LoadingFallback } from '../../components/lazy-wrapper';
import type { ChatRootProps } from './components/ChatRoot';
import type { ChatLauncherProps } from './launcher';

// ============================================================================
// Lazy UI components
// ============================================================================

export const LazyChat = createLazyComponent<ChatRootProps>(
  () => import('./components/ChatRoot').then((m) => ({ default: m.ChatRoot })),
  {
    displayName: 'LazyChat',
    fallback: <LoadingFallback minHeight={320} text="Loading chat…" />,
  },
);

export const LazyChatLauncher = createLazyComponent<ChatLauncherProps>(
  () => import('./launcher').then((m) => ({ default: m.ChatLauncher })),
  {
    displayName: 'LazyChatLauncher',
    // Launcher renders a floating FAB by default — no inline placeholder.
    fallback: null,
  },
);

// ============================================================================
// Light surface re-exports — types + pure helpers + hooks without UI
// ============================================================================

// Types (erased at compile time, free to re-export)
export type {
  ChatRole,
  ChatMessage,
  ChatPersona,
  ChatToolCall,
  ChatAttachment,
  ChatSource,
  ChatDisplayMode,
  ChatUserContext,
  ChatAssistantContext,
  ChatPrefs,
  ChatConfig,
  ChatLabels,
  ChatTransport,
  ChatStreamEvent,
  CreateSessionOptions,
  SessionInfo,
  HistoryPage,
  StreamOptions,
  SendOptions,
} from './types';
export { DEFAULT_LABELS } from './types';

// Config — plain constants, no UI imports
export {
  STORAGE_KEYS,
  CSS_VARS,
  DEFAULT_Z_INDEX,
  LIMITS,
  DEFAULT_SIDEBAR,
  HOTKEYS,
  CHAT_EVENT_NAME,
  type ChatEventDetail,
} from './config';

// Core — pure reducer / id / token buffer / persona / initials
export {
  reducer,
  initialState,
  createId,
  createTokenBuffer,
  resolvePersona,
  deriveInitials,
  type ChatState,
  type ChatAction,
  type TokenBuffer,
} from './core';

// Transports — pure functions, no UI
export {
  createHttpTransport,
  createMockTransport,
  parseSSE,
  TransportError,
  createPydanticAIChatTransport,
  createToolIdQueue,
  mapPydanticAIEvent,
  createPydanticAISSEMap,
  type HttpTransportConfig,
  type MockTransportOptions,
  type ParseSSEOptions,
  type PydanticAIChatTransportOpts,
  type PydanticAIEvent,
  type ToolIdQueue,
} from './core/transport';

// Hooks — no JSX, no UI
export {
  useChat,
  useChatComposer,
  useChatScroll,
  useChatHistory,
  useChatLayout,
  useChatAudio,
  useAutoFocusOnStreamEnd,
  useRegisterComposer,
  useChatReset,
  useVisitorFingerprint,
  useChatDockPrefs,
  DEFAULT_DOCK_PREFS,
  useFocusOnEmptyClick,
  useChatUnread,
  useChatLightbox,
  type UseChatUnreadOptions,
  type UseChatUnreadReturn,
  type UseChatConfig,
  type UseChatReturn,
  type UseChatComposerOptions,
  type UseChatComposerReturn,
  type UseChatScrollOptions,
  type UseChatScrollReturn,
  type UseChatHistoryOptions,
  type UseChatLayoutConfig,
  type UseChatLayoutReturn,
  type UseAutoFocusOnStreamEndOptions,
  type Focusable,
  type UseChatResetOptions,
  type UseChatResetReturn,
  type UseVisitorFingerprintOptions,
  type ChatDockPrefs,
  type UseChatDockPrefsOptions,
  type UseChatDockPrefsReturn,
  type UseFocusOnEmptyClickOptions,
  type UseChatLightboxReturn,
  type ChatLightboxState,
} from './hooks';

// Audio
export {
  useChatAudioPrefs,
  DEFAULT_CHAT_SOUNDS,
  type ChatAudioEvent,
  type ChatAudioSounds,
  type ChatAudioConfig,
  type UseChatAudioReturn,
} from './core/audio';

// Tool-call payload dispatcher — pure
export {
  dispatchToolPayload,
  isPlainObject,
  isLatLng,
  isGeoJSONFeatureCollection,
  isStringValue,
  type ToolPayloadMatcher,
  type ToolPayloadFallback,
} from './core/payload-dispatch';

// Logger — pure
export {
  getChatLogger,
  type ChatLogger,
  type ChatLogScope,
} from './core/logger';

// Utils — pure
export { sanitizeDraft, isSubmittableDraft } from './utils/sanitizeDraft';
export { collectImageAttachments } from './utils/collectImageAttachments';

// Style tokens — strings + hooks, no UI components
export {
  BUBBLE_SURFACE,
  ANCHOR,
  TOGGLE,
  DESTRUCTIVE_SURFACE,
  TOOL_CALL,
  useChatBubbleStyles,
  useChatRoleStyles,
  useChatDestructiveStyles,
  type ChatBubbleSurface,
  type ChatBubbleStyles,
  type ChatRoleStyles,
  type ChatDestructiveStyles,
} from './styles';

// Provider / context — needed by callers wiring custom chat shells
export {
  ChatProvider,
  useChatContext,
  useChatContextOptional,
  type ChatContextValue,
  type ChatProviderProps,
} from './context';

// ============================================================================
// Composable surface — synchronously re-exported components and their prop
// types. These are needed by consumers that build custom chat shells
// (e.g. `@djangocfg/crm`'s AdminChat / PublicChat) rather than rendering
// `LazyChat` directly.
//
// They DO transitively pull in MarkdownMessage / Sources / StreamingIndicator
// when actually rendered. Importing the types alone is free. Importing the
// component costs the dependency graph — that's the price of a custom shell.
//
// Apps that want maximum laziness should use `LazyChat` / `LazyChatLauncher`
// above and skip these.
// ============================================================================

export {
  ChatLauncher,
  ChatFAB,
  ChatDock,
  ChatHeader,
  ChatHeaderActionButton,
  ChatHeaderAudioToggle,
  ChatHeaderLanguageButton,
  ChatHeaderModeToggle,
  ChatHeaderResetButton,
  ChatGreeting,
  ChatUnreadPreview,
} from './launcher';

export {
  ChatRoot,
  MessageList,
  MessageBubble,
  MessageActions,
  Composer,
  Sources,
  ToolCalls,
  Attachments,
  AttachmentsGrid,
  AttachmentsList,
  EmptyState,
  ErrorBanner,
  JumpToLatest,
  StreamingIndicator,
  AudioToggle,
} from './components';

// Heavy-component prop types
export type {
  ChatLauncherProps,
  ChatLauncherHotkey,
  ChatLauncherGreeting,
  ChatFABProps,
  ChatFABPosition,
  ChatFABVariant,
  ChatFABSize,
  ChatDockProps,
  ChatDockMode,
  ChatDockSide,
  ChatHeaderProps,
  ChatHeaderActionButtonProps,
  ChatHeaderModeToggleProps,
  ChatHeaderAudioToggleProps,
  ChatHeaderResetButtonProps,
  ChatHeaderLanguageButtonProps,
  ChatGreetingProps,
  ChatUnreadPreviewProps,
  ChatPresencePhase,
} from './launcher';

export { useChatPresence } from './launcher';

export type {
  ChatRootProps,
  MessageListProps,
  MessageListHandle,
  MessageBubbleProps,
  MessageActionsProps,
  ComposerProps,
  SourcesProps,
  ToolCallsProps,
  ToolPayloadKind,
  AttachmentsProps,
  AttachmentsGridProps,
  AttachmentsListProps,
  AttachmentRenderer,
  AttachmentRendererArgs,
  AttachmentRendererMap,
  EmptyStateProps,
  ErrorBannerProps,
  JumpToLatestProps,
  StreamingIndicatorProps,
  AudioToggleProps,
} from './components';
