"use client";

import { createContext, useContext } from "react";
import type { ChatCopy, LanguageCode } from "@/lib/chat/i18n";
import type { UseChat } from "@/lib/chat/useChat";

/** What a block renderer may do: read copy, talk to the bot, leave the panel. */
export type ChatBlockApi = Pick<
  UseChat,
  | "sendText"
  | "sendAction"
  | "retry"
  | "isFormSubmitted"
  | "isFormDismissed"
  | "dismissForm"
  | "prepareResume"
  | "cancelResume"
> & {
  copy: ChatCopy;
  language: LanguageCode;
  /** A turn is in flight, a 429 cooldown is running, or the browser is offline. */
  busy: boolean;
  /** Form key of the in-flight submit, so only that form shows a spinner. */
  pendingFormKey: string | null;
  /** Call when following a link out of the chat (closes the sheet on phones). */
  onNavigate: () => void;
};

const ChatBlockContext = createContext<ChatBlockApi | null>(null);

export const ChatBlockProvider = ChatBlockContext.Provider;

export function useChatBlocks(): ChatBlockApi {
  const ctx = useContext(ChatBlockContext);
  if (!ctx) throw new Error("useChatBlocks must be used within <ChatBlockProvider>");
  return ctx;
}
