import * as ai from 'ai';
import * as react_jsx_runtime from 'react/jsx-runtime';
import { ContentBlock } from '@modelcontextprotocol/sdk/types.js';
import * as react from 'react';

/** A document the visitor uploaded through the chat widget, already stored by the platform. */
interface AttachedDocument {
    /** Pass to `documents.extract({ documentId, schema })` to read it. */
    documentId: string;
    /** Name the visitor's file had */
    filename: string;
    /** MIME type the browser declared on upload */
    mediaType: string;
}

interface SearchResult {
    source: string;
    heading: string;
    content: string;
    score: number;
    metadata?: Record<string, string>;
}
interface KbSearchTrace {
    query: string;
    resultCount: number;
    results: Array<Pick<SearchResult, "source" | "heading" | "score">>;
}

/**
 * Every event name in the typed taxonomy, as a runtime list. Single source of
 * truth for {@link EventType} and for surfaces that need to recognize
 * first-class names at runtime (the widget transport passes these through
 * verbatim instead of namespacing them as custom widget events).
 */
declare const EVENT_TYPES: readonly ["session.started", "page.viewed", "tool.called", "link.clicked", "widget_render", "user.identified", "price_shown", "prices_compared", "option_selected", "lead_qualified", "converted", "session.error"];
type EventType = (typeof EVENT_TYPES)[number];
declare const SESSION_ERROR_CODES: readonly ["agent_failed", "tool_failed", "upstream_failed"];
type SessionErrorCodeType = (typeof SESSION_ERROR_CODES)[number];
declare const ERROR_CAUSES: readonly ["timeout", "rate_limited", "upstream_4xx", "upstream_5xx", "network", "invalid_output", "flow_dead_end", "flow_unknown_node", "flow_loop", "unknown"];
type ErrorCauseType = (typeof ERROR_CAUSES)[number];
/**
 * Properties for `page.viewed` — emitted once when the chat widget initializes
 * on a host page (the top of the funnel). Attributed to the anonymous
 * `visitorId` (mapped to `externalUserId`), never to a session: a page view
 * must not create a session, otherwise sessions would equal page views and the
 * "landed → started a conversation" funnel collapses.
 */
interface PageViewedProperties {
    /** Full URL of the host page the widget loaded on. */
    url?: string;
    /** Referrer of the host page, if any. */
    referrer?: string;
    /** Embed mode the widget initialized in. */
    mode?: "inline" | "floating";
    /** Resolved device type from the visitor context. */
    deviceType?: "mobile" | "tablet" | "desktop";
    /** Primary browser language (BCP-47). */
    language?: string;
    /** IANA timezone of the visitor. */
    timezone?: string;
    /** `screen.width` in CSS pixels. */
    screenWidth?: number;
    /** `screen.height` in CSS pixels. */
    screenHeight?: number;
    /** `window.innerWidth` in CSS pixels, scrollbar included. */
    viewportWidth?: number;
    /** `window.innerHeight` in CSS pixels. */
    viewportHeight?: number;
}
interface ToolCalledProperties {
    name?: string;
    type?: "pricing" | "product_info" | "availability" | "support" | "other";
    /** Retrieval traces for kb.search() calls made inside this tool handler. */
    kbSearch?: KbSearchTrace[];
    cause?: ErrorCauseType;
}
interface LinkClickedProperties {
    url?: string;
}
interface PriceShownProperties {
    amount: number;
    currency: string;
    itemId?: string;
    label?: string;
}
interface ComparedPriceOption {
    id: string;
    amount: number;
    currency: string;
}
interface PricesComparedProperties {
    options: ComparedPriceOption[];
}
interface OptionSelectedProperties {
    id: string;
    amount: number;
    currency: string;
}
/**
 * Properties for `lead_qualified` — your code declaring that a person met your
 * qualification bar (finished the qualifying questions, requested a demo,
 * matched your target profile). Sharing an email mid-conversation is
 * `identify(userId, { email })`, not a qualified lead.
 */
interface LeadQualifiedProperties {
    /**
     * Your own lead id (e.g. the record id your lead-gen API returns). The
     * strongest dedup key and the stable reference back to your system.
     */
    externalId?: string;
    /** The lead's email, if known. */
    email?: string;
    /** The lead's name, if known. */
    name?: string;
}
interface ConvertedProperties {
    amount: number;
    currency: string;
    /** When the conversion actually happened — for backdated off-platform sales. */
    occurredAt?: string;
}
interface SessionErrorProperties {
    code: SessionErrorCodeType;
    cause: ErrorCauseType;
    tool?: string;
    node?: string;
}
interface TrackingContext {
    /**
     * MCP request metadata passed through to the API.
     *
     * Location varies by MCP library:
     * - `@vercel/mcp-handler`: `extra._meta`
     * - `@modelcontextprotocol/sdk`: `request.params._meta`
     */
    meta?: Record<string, unknown>;
    /** Legacy metadata field supported for backward compatibility. */
    metadata?: Record<string, unknown>;
    /** Optional explicit correlation fields. */
    sessionId?: string;
    traceId?: string;
    requestId?: string;
    correlationId?: string;
    externalUserId?: string;
    /**
     * Anonymous visitor id (the analytics "device id"). Counts as identity on
     * its own: the ingest API accepts `sessionId`, `externalUserId`, or
     * `visitorId`. The chat widget uses it for pre-session events like
     * `page.viewed`.
     */
    visitorId?: string;
    /** Optional explicit envelope fields. */
    eventId?: string;
    timestamp?: string | Date;
    source?: string;
}
/**
 * Modern tracking shape (preferred).
 */
interface BaseTrackEvent extends TrackingContext {
    event: EventType;
    properties?: Record<string, unknown>;
}
type TrackEvent = ({
    event: "session.started";
} & BaseTrackEvent) | ({
    event: "page.viewed";
    properties?: PageViewedProperties;
} & BaseTrackEvent) | ({
    event: "tool.called";
    properties?: ToolCalledProperties;
} & BaseTrackEvent) | ({
    event: "link.clicked";
    properties?: LinkClickedProperties;
} & BaseTrackEvent) | ({
    event: "user.identified";
} & BaseTrackEvent) | ({
    event: "widget_render";
} & BaseTrackEvent) | ({
    event: "price_shown";
    properties?: PriceShownProperties;
} & BaseTrackEvent) | ({
    event: "prices_compared";
    properties?: PricesComparedProperties;
} & BaseTrackEvent) | ({
    event: "option_selected";
    properties?: OptionSelectedProperties;
} & BaseTrackEvent) | ({
    event: "lead_qualified";
    properties?: LeadQualifiedProperties;
} & BaseTrackEvent) | ({
    event: "converted";
    properties?: ConvertedProperties;
} & BaseTrackEvent) | ({
    event: "session.error";
    properties?: SessionErrorProperties;
} & BaseTrackEvent);
/**
 * Legacy tracking shape supported for existing integrations.
 */
interface LegacyTrackEvent extends TrackingContext {
    eventType: EventType;
    properties?: Record<string, unknown>;
    toolName?: string;
    toolType?: ToolCalledProperties["type"];
    linkUrl?: string;
}
/**
 * Public track input accepted by `client.track()`.
 */
type TrackInput = TrackEvent | LegacyTrackEvent;
interface RevenuePriceShownInput extends TrackingContext, PriceShownProperties {
}
interface RevenuePricesComparedInput extends TrackingContext, PricesComparedProperties {
}
interface RevenueOptionSelectedInput extends TrackingContext, OptionSelectedProperties {
}
/**
 * Input for `track.leadQualified()` — identity only (`externalId`, `email`,
 * `name`) plus the shared tracking context. There is no acquisition-source
 * property; the envelope `source` comes from `meta` or the frontend client's
 * `source` option, and is left out when neither identifies the caller.
 */
interface RevenueLeadQualifiedInput extends TrackingContext, LeadQualifiedProperties {
}
interface RevenueConvertedInput extends TrackingContext, ConvertedProperties {
}
/**
 * Revenue-oriented helpers, flat on `client.track.*` (e.g.
 * `client.track.priceShown()`, `client.track.converted()`). Decoupled from
 * product primitives — each maps to a typed first-class revenue event.
 */
interface RevenueTrackingApi {
    priceShown: (input: RevenuePriceShownInput) => Promise<{
        eventId: string;
    }>;
    pricesCompared: (input: RevenuePricesComparedInput) => Promise<{
        eventId: string;
    }>;
    optionSelected: (input: RevenueOptionSelectedInput) => Promise<{
        eventId: string;
    }>;
    leadQualified: (input?: RevenueLeadQualifiedInput) => Promise<{
        eventId: string;
    }>;
    converted: (input: RevenueConvertedInput) => Promise<{
        eventId: string;
    }>;
}
/**
 * `client.track` — callable for generic events (`track(event)`), with the
 * revenue helpers attached flat: `track.priceShown()`, `track.leadQualified()`,
 * `track.converted()`, etc.
 */
interface TrackFn extends RevenueTrackingApi {
    (event: TrackInput): Promise<{
        eventId: string;
    }>;
}

/**
 * Chat widget translation types.
 *
 * The English catalog is the source of truth — its shape is inferred and
 * every other locale must match it exactly (enforced by `ExactShape`).
 * Add a key in `en.ts` and TypeScript will flag the missing key in `fr.ts`
 * / `es.ts`.
 */
declare const SUPPORTED_LOCALES: readonly ["en", "fr", "es"];
type Locale = (typeof SUPPORTED_LOCALES)[number];

/**
 * English catalog. Source of truth — every other locale must mirror this
 * shape exactly (the `Messages` type is inferred from here).
 */
interface Messages {
    promptInput: {
        placeholder: string;
        uploadFiles: string;
        uploadFilesUpTo: string;
        uploadFilesUpToWithPages: string;
        stop: string;
        submit: string;
        removeAttachments: string;
        removeAttachment: string;
        uploading: string;
        retry: string;
        retryUpload: string;
        uploadFailed: string;
        dropToAttach: string;
        errorAccept: string;
        errorTooLarge: string;
        errorTooMany: string;
    };
    workingIndicator: {
        default: string;
    };
    reasoning: {
        thinking: string;
        thoughtBrief: string;
        thoughtForSeconds: (count: number) => string;
    };
    /** Chain-of-thought header (no icon): a generic label per state. */
    chainOfThought: {
        working: string;
        done: string;
    };
    tool: {
        copy: string;
        copied: string;
        request: string;
        response: string;
        error: string;
    };
    attachments: {
        attachmentFallback: string;
        kindPdf: string;
        kindImage: string;
        kindFile: string;
        fileFallback: string;
    };
    threadMenu: {
        newChat: string;
        threadHistory: string;
        deleteThread: string;
        noPreviousChats: string;
        hiddenThreads: (count: number) => string;
    };
    chatQueue: {
        attachmentFallback: string;
        removeFromQueue: string;
        queued: (count: number) => string;
    };
    thread: {
        scrollToLatest: string;
    };
    poweredBy: {
        label: string;
        logoAlt: string;
    };
    aiDisclaimer: {
        default: string;
        /** Shown in place of `default` when the "powered by" logo is hidden, so the line still says it is an AI. */
        standalone: string;
    };
    exportSession: {
        saving: string;
        saved: string;
        error: string;
        export: string;
        tooltip: string;
    };
    widgetErrorBoundary: {
        failedToLoad: string;
        retry: string;
    };
    launcher: {
        prompt: string;
        open: string;
        close: string;
        minimize: string;
    };
    menu: {
        newChat: string;
        restart: string;
        copyConversation: string;
        copied: string;
        copyFailed: string;
        label: string;
    };
    dialog: {
        restartTitle: string;
        restartText: string;
        clearWithoutCopy: string;
        copyAndClear: string;
        confirm: string;
        cancel: string;
        copyError: string;
        close: string;
    };
    toast: {
        conversationCopied: string;
    };
    transcript: {
        header: (site: string, date: string) => string;
        you: string;
        assistant: string;
    };
    /** Empty by default: filled from the welcome knob. */
    welcome: {
        title: string;
        subtitle: string;
    };
}

type DeepPartial<T> = T extends (...args: never[]) => unknown ? T : T extends object ? {
    [K in keyof T]?: DeepPartial<T[K]>;
} : T;
type MessageOverrides = DeepPartial<Messages>;
/** Overrides keyed by locale: `{ "fr": { … }, "en": { … } }`. */
type LocaleMessageOverrides = Partial<Record<Locale, MessageOverrides>>;

/**
 * A visitor id to apply, or a resolver that produces one. The resolver may be
 * sync (`() => posthog.get_distinct_id()`) or async
 * (`async () => (await sdk.ready()).id`), for analytics SDKs whose id is only
 * available after they bootstrap.
 */
type VisitorIdInput = string | (() => string | undefined | null | Promise<string | undefined | null>);

/** Source of truth; {@link SuggestionOrigin} derives from it. */
declare const SUGGESTION_ORIGINS: readonly ["channel", "page", "flow", "followup"];
type SuggestionOrigin = (typeof SUGGESTION_ORIGINS)[number];
/** One pill. `id` is null unless it came from an authored per-page prompt. */
interface Suggestion {
    id: string | null;
    text: string;
}
/**
 * One field per origin. `null` means the origin has nothing to say — no entry
 * on this turn, or the rung no longer applies.
 *
 * `flow` alone treats `[]` as authoritative: it clears the row and suppresses
 * every weaker rung. Elsewhere `[]` and `null` are the same.
 */
interface SuggestionCandidates {
    flow: Suggestion[] | null;
    followup: Suggestion[] | null;
    page: Suggestion[] | null;
    channel: Suggestion[] | null;
}
/**
 * The rungs an embed host reads from `/config`. Grouped because they share a
 * source and a lifetime: both stop applying at the visitor's first message.
 */
type PreChatSuggestions = Pick<SuggestionCandidates, "page" | "channel">;

/** Surface the widget is mounted on. */
type WidgetMode = "inline" | "floating" | "composer";
interface WidgetEventBase {
    /** Surface the widget is mounted on. */
    mode: WidgetMode;
    /**
     * Conversation session id, when one exists. Assigned on the first
     * exchange, so it is `undefined` for events that precede it.
     */
    sessionId?: string;
    /** Epoch milliseconds at emit time. */
    timestamp: number;
}
/**
 * Per-event discriminant and extra properties. Events in the first branch
 * carry no `properties` object.
 */
type WidgetEventDetail = {
    name: "chat.ready" | "chat.opened" | "chat.closed" | "message.sent" | "message.received" | "conversation.copied" | "conversation.restarted";
} | {
    name: "session.started";
    properties: {
        sessionId: string;
    };
} | {
    name: "thread.changed";
    properties: {
        threadId: string;
    };
} | {
    name: "chat.error";
    properties: {
        message: string;
    };
} | {
    name: "suggestion.clicked";
    properties: {
        text: string;
        index: number;
        /** Which provider supplied the clicked pill: `"channel"` (starter prompts), `"page"` (per-URL starter prompts), `"flow"` (an MCP flow's `interrupt({ suggestions })`), or `"followup"` (generated from the conversation). */
        origin: SuggestionOrigin;
    };
} | {
    name: "suggestions.shown";
    properties: {
        texts: string[];
        /** Origin of the rendered set, same taxonomy as `suggestion.clicked`. */
        origin: SuggestionOrigin;
    };
} | {
    name: "link.clicked";
    properties: {
        url: string;
    };
};
/** Payload handed to `onEvent` subscribers. Discriminated on `name`. */
type WidgetEvent = WidgetEventBase & WidgetEventDetail;
type WidgetEventName = WidgetEventDetail["name"];

/**
 * Built-in theme presets. `auto` follows the host's `prefers-color-scheme`
 * and switches at runtime without re-rendering.
 */
type ThemePreset = "light" | "dark" | "auto";
/**
 * Appearance config for the chat widget. Pick a preset and (optionally) layer
 * per-property `variables` on top.
 *
 * ```ts
 * appearance: { theme: "dark", variables: { primaryColor: "#ff6b6b" } }
 * ```
 *
 * The same shape is accepted by the `embed.js` script (`init({ appearance })`),
 * `<WaniwaniChat overrides={{ appearance }} />`, and `<ChatEmbed appearance />`.
 */
interface ChatAppearance {
    /** Base theme preset. Defaults to `"light"`. */
    theme?: ThemePreset;
    /** Per-property overrides applied on top of the preset. */
    variables?: ChatTheme;
    /**
     * Render assistant messages inside a filled bubble (background + padding +
     * radius), styled by `variables.assistantBubbleColor` /
     * `assistantBubbleTextColor`. Defaults to `false` — assistant messages
     * render as plain text. Opt in for a "both sides bubbled" chat style.
     */
    assistantBubble?: boolean;
}
/**
 * Tool-call activity rendering mode. Steps are grouped into one collapsible
 * "chain of thought".
 *
 * - `true` (default) — each step expands to its request/response JSON.
 * - `"titles-only"` — step labels only, no JSON.
 * - `false` — the chain (and the reasoning trace) are hidden entirely; only
 *   a generic working indicator shows while the agent works.
 */
type ShowToolCalls = boolean | "titles-only";
declare const AVATAR_SLOTS: readonly ["welcome", "header", "message", "composer", "dock"];
/** Where the avatar image may appear. */
type AvatarSlot = (typeof AVATAR_SLOTS)[number];
declare const MENU_ACTIONS: readonly ["new-chat", "restart", "copy-conversation", "history", "delete"];
/** An entry of the header menu, in the order given. */
type MenuAction = (typeof MENU_ACTIONS)[number];

interface ChatTheme {
    /** Primary brand color (bubble, send button, user messages) */
    primaryColor?: string;
    /** Primary text color on primary background */
    primaryForeground?: string;
    /** Chat panel background */
    backgroundColor?: string;
    /** Default text color */
    textColor?: string;
    /** Secondary/muted text */
    mutedColor?: string;
    /** Border color */
    borderColor?: string;
    /** Border width for the panel (px). Defaults to 0 (no border). */
    borderWidth?: number;
    /** Box-shadow shorthand applied to the panel. Use any valid CSS box-shadow string (e.g. `"0 10px 25px rgba(0,0,0,0.1)"`). Defaults to `none`. */
    boxShadow?: string;
    /** Assistant message bubble background */
    assistantBubbleColor?: string;
    /** User message bubble background */
    userBubbleColor?: string;
    /** Input field background */
    inputBackgroundColor?: string;
    /** Border radius for the panel (px) */
    borderRadius?: number;
    /** Border radius for message bubbles (px) */
    messageBorderRadius?: number;
    /** Font family */
    fontFamily?: string;
    /** Header background color (card layout). Falls back to backgroundColor. */
    headerBackgroundColor?: string;
    /** Header text color. Falls back to textColor. */
    headerTextColor?: string;
    /**
     * Status dot color. Defaults to green (#22c55e).
     * @deprecated Nothing renders a status dot, so this has no visible effect.
     */
    statusColor?: string;
    /** Tool call JSON section background. Defaults to light gray / #262626 in dark. */
    toolCardColor?: string;
    /** Text color inside the user message bubble. Falls back to `primaryForeground`. */
    userBubbleTextColor?: string;
    /** Text color inside the assistant message bubble (only visible when `appearance.assistantBubble` is enabled). Falls back to `textColor`. */
    assistantBubbleTextColor?: string;
    /** Horizontal padding inside message bubbles (px). Defaults to 16. */
    messagePaddingX?: number;
    /** Vertical padding inside message bubbles (px). Defaults to 12. */
    messagePaddingY?: number;
    /** Max width of a message bubble as a CSS length/percentage. Defaults to `"80%"`. */
    messageMaxWidth?: string;
    /** Base font size for message text (px). When unset, messages use the CSS default of `1rem` (16px at the standard root font size). */
    fontSize?: number;
    /** Base line height for message text (unitless string, e.g. `"1.5"`). Defaults to `"1.5"`. */
    lineHeight?: string;
    /** Frosted-glass tint color for the floating bar's suggestion card, layered
     *  over the backdrop blur. Programmatic-only via appearance.variables.
     *  Unset = the default neutral glass (unchanged). */
    glassTint?: string;
    /** Strength of the glass tint, 0–1 as a unitless string (e.g. "0.5").
     *  Unset/"0" = no tint (default rendering). */
    glassTintStrength?: string;
}
/**
 * An animated image (GIF, animated WebP, APNG) shown in place of the avatar
 * once per slot and page load, for `durationMs` after it loads, then replaced
 * by the still avatar. Skipped under `prefers-reduced-motion: reduce` and in
 * the `message` slot.
 */
interface AvatarIntro {
    src: string;
    durationMs: number;
}
interface WelcomeConfig {
    /**
     * Icon displayed above the title. Any React node (e.g. an SVG), or a
     * string: one that reads as a URL or path (`http:`, `https:`, `data:`,
     * `blob:`, or containing `/`) renders as the welcome avatar image, any
     * other string (`"👋"`) renders as text, and `""` renders nothing.
     */
    icon?: React.ReactNode | string;
    /** Title text shown prominently in the welcome screen. */
    title: string;
    /** Description text shown below the title. */
    description?: string;
    /** Subtitles shown in place of `description`, rotating when there are several. */
    subtitles?: string[];
    /** Milliseconds between subtitle swaps. Unset or `0` keeps the first one. */
    subtitleRotateMs?: number;
    /** Suggestion cards shown in the welcome screen. Disappear after the first message. */
    suggestions?: string[];
}
interface SuggestionsConfig {
    /**
     * Starter prompts shown before the user sends their first message.
     * Defaults to an empty array.
     */
    initial?: string[];
}
/**
 * Per-slot class name overrides for the chat widget. Each string is appended
 * to the slot's own classes (merged with `tailwind-merge`, `ww` prefix). Use
 * with your own (prefixed or plain) CSS to restyle any element. In the React
 * path these reach into internals directly; in the `<script>` embed, prefer
 * the stable `.ww-*` semantic classes with a `data-css` stylesheet.
 */
interface ChatClassNames {
    /** Root chat container. */
    root?: string;
    /** Sticky header bar. */
    header?: string;
    /** Every message wrapper (both roles). */
    message?: string;
    /** The user message bubble content. */
    userBubble?: string;
    /** The assistant message bubble content. */
    assistantBubble?: string;
    /** The input bar container. */
    input?: string;
}
/** What the platform reports about the documents module for this project. */
interface DocumentUploadConfig {
    enabled: boolean;
    /** Refused before the upload starts. */
    maxBytes: number;
    /** Stated to the visitor; the OCR vendor is what enforces it. */
    maxPdfPages: number;
    /** The chat request refuses more than this, so the composer must not take more. */
    maxFiles: number;
    /** MIME types the platform accepts. */
    accept: string[];
}
interface ChatBaseProps {
    /** Waniwani project API key */
    apiKey?: string;
    /** Chat API endpoint URL. Defaults to Waniwani hosted endpoint */
    api?: string;
    /**
     * Builds the transport turns are sent through. Defaults to the chat's own
     * HTTP transport to `api`, which it also hands the factory as `fallback`.
     */
    transport?: ChatTransportFactory;
    /** Pre-loaded messages to display when the chat mounts. */
    initialMessages?: ai.UIMessage[];
    /** Initial greeting shown before user types */
    welcomeMessage?: string;
    /**
     * Rich welcome screen shown when the conversation is empty.
     * Replaces `welcomeMessage` with a centered layout featuring an icon, title,
     * description, and card-style suggestion prompts.
     * Takes precedence over `welcomeMessage` when provided.
     */
    welcome?: WelcomeConfig;
    /**
     * Assistant avatar image, the places it appears, and an optional intro
     * animation that plays once per slot before the image takes over.
     */
    avatar?: {
        src: string;
        slots: AvatarSlot[];
        intro?: AvatarIntro;
    };
    /**
     * Header menu entries, in order. When set, one menu replaces the New chat
     * and thread history buttons; unset keeps them.
     */
    menu?: MenuAction[];
    /** Ask before the menu's `restart` clears the conversation. */
    restartConfirm?: boolean;
    /**
     * Theme preset (`light`/`dark`/`auto`) plus per-property overrides.
     * See `ChatAppearance` for the shape.
     */
    appearance?: ChatAppearance;
    /** Per-slot class name overrides. See {@link ChatClassNames}. */
    classNames?: ChatClassNames;
    /**
     * Override the anonymous visitor id the widget generates with one you
     * already track (a PostHog / Amplitude / Segment distinct id, your own
     * cookie, etc.). The chat sends it on every request, so Waniwani sessions
     * and events correlate to the same visitor, and server-side MCP tools and
     * flows read it back as `context.waniwani.visitorId`.
     *
     * A string, or a resolver that returns one — sync
     * (`() => posthog.get_distinct_id()`) or async
     * (`async () => (await sdk.ready()).id`), for analytics SDKs whose id is
     * only ready after they bootstrap. A blank / failed result is ignored, so
     * the auto-generated, `localStorage`-persisted id is kept. Leave unset to
     * always use the auto id.
     */
    visitorId?: VisitorIdInput;
    /** Additional headers to send with chat API requests */
    headers?: Record<string, string>;
    /**
     * Extra headers for the document upload and discard requests, merged over
     * `headers` for those calls only. Set it where those endpoints take a
     * different credential than the chat; everything else in `headers` still
     * goes out. Matching names replace, case-insensitively. Browser-visible, so
     * public credentials only.
     */
    uploadHeaders?: Record<string, string>;
    /** Additional body fields to send with each chat request */
    body?: Record<string, unknown>;
    /** Enable file attachments in the input. Defaults to false. */
    allowAttachments?: boolean;
    /**
     * Document upload, as the platform reports it on `GET /api/mcp/chat/config`.
     * The composer offers a paperclip, a drop target and paste only while
     * `enabled` is true, and the upload endpoint enforces the same flag.
     */
    documentUpload?: DocumentUploadConfig;
    /** Placeholder text shown in the input field. Defaults to "Ask me anything...". Animates with a typing effect. */
    placeholder?: string;
    /**
     * Name of a custom DOM event to listen for that triggers focus (scroll + glow) and optionally sends a message.
     * Dispatch via `new CustomEvent('triggerDemoRequest', { detail: { message: 'Hi!' } })`.
     * Set to `false` to disable. Defaults to `"triggerDemoRequest"`.
     */
    triggerEvent?: string | false;
    /** Callback fired when a message is sent */
    onMessageSent?: (message: string) => void;
    /** Callback fired when a response is received */
    onResponseReceived?: () => void;
    /** @experimental Answers tool calls the server left without a result: the return value goes back to the AI as the result, a throw as an error result, and the chat then carries on. Ignored with a custom `transport`. */
    onToolCall?: (call: {
        toolCallId: string;
        toolName: string;
        input: unknown;
    }) => unknown;
    /**
     * Suggestion pills. The row obeys a fixed hierarchy — flow > followup >
     * page > channel — and every origin is always active.
     *
     * `false` hides the row; `true` / unset is the default. `{ initial: [...] }`
     * sets starter prompts. Embed hosts pass the resolved
     * {@link PreChatSuggestions} from `useSuggestions(config)` instead, which
     * carries the prompt ids needed for click attribution.
     */
    suggestions?: boolean | SuggestionsConfig | PreChatSuggestions;
    /**
     * Handler for MCP tool calls from widgets.
     * Called when a widget uses `callServerTool` (MCP Apps standard).
     * If not provided, defaults to POSTing to `${api}/tool`.
     */
    onCallTool?: CallToolHandler;
    /**
     * Enable debug mode. When true, the `_meta` field is shown in tool call
     * inputs and outputs instead of being filtered out.
     * Tip: set to `process.env.NEXT_PUBLIC_WANIWANI_DEBUG === '1'` to mirror
     * the server-side `WANIWANI_DEBUG` env var.
     */
    debug?: boolean;
    /**
     * How the agent's tool-call activity renders. Steps are grouped into a
     * single collapsible "chain of thought" that auto-expands while the agent
     * works and collapses to a summary once it settles.
     *
     * - `true` (default) — each step expands to its request/response JSON.
     * - `"titles-only"` — step labels only, no JSON.
     * - `false` — the chain is hidden entirely, along with the reasoning
     *   trace; only the generic "On it…" indicator shows while the agent works.
     *
     * MCP App widgets attached to a tool call are always rendered.
     */
    showToolCalls?: ShowToolCalls;
    /**
     * Skip fetching `/config` and `/tools` from the API on mount.
     * Use when the chat endpoint doesn't serve these routes (e.g. embed widgets
     * talking directly to the Waniwani app).
     * @internal
     */
    skipRemoteConfig?: boolean;
    /**
     * Persist the conversation across page reloads using IndexedDB so the user
     * can resume previous threads. Defaults to `false` — opt in explicitly.
     */
    enableThreadHistory?: boolean;
    /**
     * Force a specific thread to be active. When provided, the embed renders
     * that thread's messages and ignores the most-recently-updated default.
     */
    activeThreadId?: string;
    /** Fired whenever the active thread changes (new chat, switch, delete). */
    onThreadChange?: (threadId: string) => void;
    /**
     * AI transparency notice rendered under the input (EU AI Act compliance).
     * Defaults to `"AI can make mistakes. Verify important information."`.
     * Pass a string to override the wording, or `false` to hide it entirely.
     */
    disclaimer?: string | false;
    /** @internal Enterprise only: hides the "powered by Waniwani" logo. */
    hidePoweredBy?: boolean;
    /**
     * UI language for built-in labels (buttons, placeholders, status text).
     * Supports `"en"`, `"fr"`, `"es"`. When omitted, the widget detects the
     * locale from `<html lang>` and `navigator.language(s)`, falling back
     * to English.
     */
    locale?: string;
    /**
     * Per-key overrides on top of the resolved locale catalog. Use this to
     * tweak individual built-in strings without contributing a new locale.
     * Flat (applies to every locale) or keyed by locale.
     *
     * ```tsx
     * messages={{ promptInput: { placeholder: "Ask the agent…" } }}
     * messages={{ fr: { menu: { restart: "Recommencer" } } }}
     * ```
     */
    messages?: MessageOverrides | LocaleMessageOverrides;
}
/**
 * MCP Apps configuration for {@link ChatEmbedProps}.
 *
 * Only needed when your backend proxies an MCP server whose tools return
 * widget metadata (`_meta.ui.resourceUri`). Without this, tool calls still
 * render with collapsible input/output — just no iframe widgets.
 */
interface ChatEmbedMcpConfig {
    /** Endpoint that serves MCP app resources (HTML widgets). Called as `GET ${resourceEndpoint}?uri=...`. */
    resourceEndpoint: string;
    /**
     * Handler for MCP tool calls triggered by widgets via `callServerTool`.
     * If not provided, widget-initiated tool calls will be ignored.
     */
    onCallTool?: CallToolHandler;
}
/** Handler signature for MCP tool calls from widgets. */
type CallToolHandler = (params: {
    name: string;
    arguments: Record<string, unknown>;
}) => Promise<{
    content?: Array<{
        type: string;
        text?: string;
    }>;
    structuredContent?: Record<string, unknown>;
    _meta?: Record<string, unknown>;
}>;
/**
 * **Advanced / bare-bones primitive.** Most apps should use
 * `WaniwaniChat` instead — it wires up the hosted Waniwani backend
 * (`app.waniwani.ai`) from a single `wwp_...` token and applies the
 * dashboard's display config automatically.
 *
 * `ChatEmbed` is the unmanaged escape hatch: you bring your own `api`
 * endpoint, your own auth headers, your own theme, and your own
 * (optional) MCP resource endpoint for widgets. Nothing is fetched or
 * defaulted for you — `skipRemoteConfig` is implied by the BYO design.
 * Reach for it when:
 *
 * - You self-host the chat backend (Next.js/Express route, your own
 *   provider) and don't want Waniwani's hosted features.
 * - You need full control over headers, body, and tool-call dispatch.
 *
 * The component fills its parent container (`width: 100%; height: 100%`)
 * with no header, border, or shadow.
 *
 * @example
 * ```tsx
 * // Self-hosted chat endpoint, no MCP App widgets
 * <ChatEmbed
 *   api="/api/my-chat-endpoint"
 *   body={{ environmentId, sessionId }}
 *   appearance={{ theme: "dark" }}
 * />
 *
 * // Self-hosted chat endpoint with MCP App widgets
 * <ChatEmbed
 *   api="/api/my-chat-endpoint"
 *   mcp={{ resourceEndpoint: "/api/mcp/resource" }}
 * />
 * ```
 */
interface ChatEmbedProps extends Omit<ChatBaseProps, "api" | "onCallTool"> {
    /** The chat API endpoint URL. Required — there is no default. */
    api: string;
    /** Additional class names applied to the root element (e.g. Tailwind classes). */
    className?: string;
    /** MCP Apps configuration. Only needed if your backend serves widget resources. */
    mcp?: ChatEmbedMcpConfig;
    /** Hide the input bar at the bottom, making the chat read-only. */
    readOnly?: boolean;
    /**
     * Sticky header title. When set (or when `enableThreadHistory` is true, or
     * `headerActions` is provided), a sticky header is rendered at the top of
     * the chat. Without any of these, the chat is headerless.
     */
    title?: string;
    /** Extra React node rendered in the sticky header, right of the title. */
    headerActions?: React.ReactNode;
    /**
     * Force-hide the sticky header even when `title`, `enableThreadHistory`,
     * or `headerActions` would otherwise show it. Useful when the host page
     * already provides its own chrome.
     */
    hideHeader?: boolean;
    /**
     * @internal
     * When `true`, the root renders at `opacity: 0` so the chrome doesn't
     * paint with stale defaults while the layout's remote config is still
     * loading. Flipping to `false` triggers a single coordinated fade-in.
     * Set by `WaniwaniChat` / the IIFE embed; standalone `ChatEmbed` callers
     * should leave this unset.
     */
    initializing?: boolean;
    /**
     * @internal
     * Whether the chat is actually on screen. `false` suppresses
     * `suggestions.shown` impressions, so a mount kept hidden behind other
     * chrome (the floating dock) never reports pills the visitor cannot see.
     * Defaults to `true`; standalone `ChatEmbed` callers should leave it unset.
     */
    onScreen?: boolean;
    /**
     * @internal
     * The script embed surface hosting the chat, rendered as `data-mode` on
     * `.ww-root`. Set by the IIFE embed; unset on the React path.
     */
    mode?: "inline" | "floating" | "composer";
    /**
     * @internal
     * `"pills"` is the script embed's structured welcome: it shows the
     * pre-chat pill row as its chips (the row above the input hides while it
     * shows), takes the avatar's `welcome` slot as its icon, and falls back to
     * `messages.welcome` when `welcome` is unset. Defaults to `"cards"`.
     */
    welcomeVariant?: "cards" | "pills";
    /** `"single-row"` clips the suggestion row to one line. Defaults to `"wrap"`. */
    suggestionsLayout?: "wrap" | "single-row";
    /**
     * `"after-message"` shows the suggestion row under the last assistant
     * message instead of above the input; while the conversation is empty the
     * row stays above the input. Defaults to `"above-input"`.
     */
    suggestionsPosition?: "above-input" | "after-message";
    /** Arrow on the send button. Defaults to `"up"`. */
    sendIcon?: "up" | "right";
    /**
     * `false` hides the copy and download toolbar above tables in answers.
     * Defaults to `true`.
     */
    showTableToolbar?: boolean;
}
interface ChatHandle {
    /** Programmatically send a user message into the chat */
    sendMessage: (text: string) => void;
    /**
     * Send a user message and wait for the assistant response to complete.
     * Returns the final assistant message. Useful for eval/testing flows.
     */
    sendMessageAndWait: (text: string) => Promise<unknown>;
    /** Clear all messages and start a fresh conversation */
    reset: () => void;
    /**
     * Clear the conversation without asking, and emit
     * `conversation.restarted`.
     */
    restart: () => void;
    /**
     * Copy the conversation as plain text to the clipboard. Resolves `false`
     * when the browser refuses; emits `conversation.copied` on success.
     */
    copyConversation: () => Promise<boolean>;
    /** Scroll to the chat input, focus it, and show a highlight glow */
    focus: () => void;
    /** Current chat messages */
    messages: ai.UIMessage[];
    /** Session ID used for event correlation. Available after the first message. */
    sessionId: string | undefined;
    /**
     * Track a funnel event from the host page with the chat session attached
     * automatically. Same surface as the server client: callable with a typed
     * event, plus the flat revenue helpers (`track.converted({ ... })`, ...).
     * Present on `WaniwaniChat` (hosted); absent on the bare `ChatEmbed`
     * primitive, which has no Waniwani credential to send events with.
     */
    track?: TrackFn;
    /**
     * Tie the visitor to a stable user id (emits `user.identified`).
     * Present on `WaniwaniChat` only, like `track`.
     */
    identify?: (userId: string, traits?: Record<string, unknown>) => Promise<{
        eventId: string;
    }>;
}
/** What the chat hands a transport factory. */
interface ChatTransportContext {
    /** The chat's HTTP transport to `api`. */
    fallback: ai.ChatTransport<ai.UIMessage>;
    headers: () => Record<string, string> | undefined;
    /** The channel, visitor and MCP `extra` a turn is attributed to. */
    body: () => Record<string, unknown>;
    /** Whether the chat keeps saved threads, whose messages the chat restores itself. */
    threadHistory: () => boolean;
    /** The active saved thread, started if there is none. Undefined without saved threads. */
    threadId: () => string | undefined;
    /** Whether the chat already shows messages the transport did not restore. */
    hasMessages: () => boolean;
    /** The documents attached to the message being sent, handed over once. */
    takeTurnInput: () => {
        documents?: AttachedDocument[];
    };
    onSession: (sessionId: string) => void;
}
/** Optional hooks the chat calls on a transport. */
interface ChatTransportLifecycle {
    /** The visitor started typing their first message. */
    prepare?(): void;
    /** On mount: the conversation this browser already holds, as messages to show. */
    restore?(): Promise<ai.UIMessage[]>;
    /** The visitor started a new conversation. */
    reset?(): void;
    /** A saved thread was deleted. */
    forget?(threadId: string): void;
    /** Whether a page load brings the session back, which the New chat button needs. */
    keepsSession?(): boolean;
    dispose?(): void;
}
type ChatTransportFactory = (context: ChatTransportContext) => ai.ChatTransport<ai.UIMessage> & ChatTransportLifecycle;

type ModelContextContentBlock = ContentBlock;
type ModelContextUpdate = {
    content?: ModelContextContentBlock[];
    structuredContent?: Record<string, unknown>;
};

/**
 * Per-tool definition metadata, keyed by tool name. The chat UI caches the
 * MCP `tools/list` response here so widget resolution can happen by tool
 * name (spec-canonical) rather than by inspecting every tool call result.
 */
type ToolDefinitionsMap = Record<string, {
    _meta?: Record<string, unknown>;
}>;

type McpAppDisplayMode = "inline" | "pip" | "fullscreen";
interface McpAppFrameProps {
    resourceUri: string;
    toolInput: Record<string, unknown>;
    toolResult: {
        content?: Array<{
            type: string;
            text?: string;
        }>;
        structuredContent?: Record<string, unknown>;
        _meta?: Record<string, unknown>;
    };
    resourceEndpoint?: string;
    chatSessionId?: string;
    isDark?: boolean;
    className?: string;
    /** When true, the iframe height auto-adapts to its content. Set via `_meta.ui.autoHeight` in the tool result. */
    autoHeight?: boolean;
    /** Called when the view requests to open a URL */
    onOpenLink?: (url: string) => void;
    /** Called when a widget sends a follow-up message via `ui/message` */
    onFollowUp?: (message: {
        role: string;
        content: Array<{
            type: string;
            text?: string;
        }>;
        modelContext?: ModelContextUpdate;
    }) => void;
    /** Called when a widget calls a tool via `tools/call` (MCP Apps standard). */
    onCallTool?: (params: {
        name: string;
        arguments: Record<string, unknown>;
    }) => Promise<{
        content?: Array<{
            type: string;
            text?: string;
        }>;
        structuredContent?: Record<string, unknown>;
        _meta?: Record<string, unknown>;
    }>;
    /** Called when the widget requests a display mode change (e.g. "fullscreen" for expand) */
    onDisplayModeChange?: (mode: McpAppDisplayMode) => void;
    /** When true, the iframe fills its container (fullscreen mode). */
    isFullscreen?: boolean;
    /**
     * Cached tool catalog keyed by tool name. Passed through so that
     * follow-up `tools/call` requests from the widget iframe can be
     * correctly classified as widget-producing (spec-canonical definition
     * lookup) vs. plain (result text auto-injected).
     */
    toolDefinitions?: ToolDefinitionsMap;
}
declare function McpAppFrame({ resourceUri, toolInput, toolResult, resourceEndpoint, chatSessionId, isDark, className, autoHeight, onOpenLink, onFollowUp, onCallTool, onDisplayModeChange, isFullscreen, toolDefinitions, }: McpAppFrameProps): react_jsx_runtime.JSX.Element;

/**
 * The shapes crossing the WebMCP boundary.
 *
 * Structural rather than imported from `@modelcontextprotocol/sdk`, because
 * everything here is also read by the browser bridge, and the MCP SDK is an
 * optional peer dependency that has no business in a page bundle. What the
 * server sends and what the page reads is JSON either way.
 */
/**
 * One MCP content block. `type` is the discriminator every block carries; the
 * index signature keeps the rest of whichever block it is, since nothing on
 * this path reads them and re-deriving the union would only restate a schema
 * the server already validated on the way out.
 */
type WebMcpContentBlock = {
    type: string;
    text?: string;
    [key: string]: unknown;
};
/** A tool as `tools/list` describes it. */
type WebMcpTool = {
    name: string;
    description?: string;
    inputSchema?: Record<string, unknown>;
    annotations?: Record<string, unknown>;
    _meta?: Record<string, unknown>;
};
/**
 * Everything the page needs to mount a widget itself.
 *
 * Assembled server-side because none of it is derivable on the page: the view
 * URI carries a content hash that moves every deploy, and the display tool's
 * result is what the view reads its own configuration from.
 */
type WebMcpWidgetPayload = {
    /**
     * The `ui://` the view was resolved from.
     *
     * Carries a content hash that moves on every deploy, which is why this is
     * resolved server-side per call and why nothing on the page can cache it.
     *
     * The only half of the view the page is told. Where to fetch it from is the
     * resource endpoint the page already derived from its token, the same one
     * the chat's own widget iframes use.
     */
    viewUri: string;
    /** Display tool the view belongs to. */
    tool: string;
    /** Props, delivered to the view as `ui/notifications/tool-input`. */
    data: Record<string, unknown>;
    /** The display tool's own result, delivered as `ui/notifications/tool-result`. */
    result: {
        content: WebMcpContentBlock[];
        structuredContent?: Record<string, unknown>;
        _meta?: Record<string, unknown>;
    };
    /** Whether the flow is waiting on the visitor before it can advance. */
    interactive: boolean;
    /**
     * Set by the preview endpoint. A real widget step is a flow waiting on the
     * visitor and has no way out; a preview is something someone opened to look
     * at, so the host can give it one.
     */
    preview?: boolean;
};
type WebMcpCallResponse = {
    content: WebMcpContentBlock[];
    structuredContent?: Record<string, unknown>;
    isError?: boolean;
    _meta?: Record<string, unknown>;
    /** Present and non-null only when the call produced a resolvable widget step. */
    widget: WebMcpWidgetPayload | null;
};

/**
 * The WebMCP bridge.
 *
 * A browsing agent standing on a page never speaks to the MCP server. It speaks
 * to the page, through `document.modelContext`, and this is what puts the
 * server's tools there. Every `execute()` the agent calls lands on the endpoint
 * below, which stamps attribution server-side and answers.
 *
 * Nothing here discovers its own configuration. The endpoint, both ids, and the
 * widget callback are arguments, because there are two callers with two
 * different ways of knowing them: the chat embed reads them from its remote
 * config, and the standalone loader derives them from its own script tag.
 * Sniffing `document.currentScript` inside a bundle that may be loaded twenty
 * modules deep finds the wrong script or none.
 */

/** Live for as long as the bridge is registered. */
type WebMcpBridge = {
    /** Tools successfully registered with the browser. */
    readonly tools: WebMcpTool[];
    /**
     * Call a tool with the bridge's auth and identity, for a mounted view's own
     * `tools/call`. Resolves to the raw response; widgets are not re-dispatched.
     */
    callTool: (params: {
        name: string;
        arguments?: Record<string, unknown>;
    }) => Promise<WebMcpCallResponse>;
    /** Unregister everything. Idempotent. */
    dispose: () => void;
};

/**
 * `McpAppFrame` is used exactly as the chat uses it, with no new props.
 *
 * Three things would be worth telling it on this surface, and none of them are
 * worth touching a component every customer's chat renders:
 *
 * - It advertises a `message` capability in its handshake, which is how a view
 *   pushes a follow-up into the conversation. There is no channel back to a
 *   browsing agent, so a view that uses it is ignored. The panel's own content
 *   still works; only the agent's narration is lost.
 * - Its `hostInfo` says "Waniwani Chat". A view reading it is told the wrong
 *   host, and nothing in ours reads it.
 * - It clamps its own height. The panel below sets `maxHeight` and scrolls, so
 *   an oversized view is contained here rather than there.
 *
 * Each becomes worth doing once this surface has run in front of real traffic
 * and one of them has actually cost something.
 */
type WebMcpOverlayProps = {
    /** The step to show, or `null` for nothing. */
    widget: WebMcpWidgetPayload | null;
    /**
     * Proxies a view's own `tools/call`. Pass the bridge's `callTool` so the
     * request carries the same auth and session identity as the agent's calls.
     */
    onCallTool?: WebMcpBridge["callTool"];
    /** @deprecated Pass `onCallTool`. Removed in 0.23.0. */
    toolsEndpoint?: string;
    /** @deprecated Pass `onCallTool`. Removed in 0.23.0. */
    headers?: Record<string, string>;
    /**
     * Where view HTML is fetched from, resolved from the token the same way the
     * chat's own widget iframes resolve theirs.
     */
    resourceEndpoint: string;
    /** Raised when the view says it is finished, and on Escape for a preview. */
    onClose: () => void;
    isDark?: boolean;
};
declare function WebMcpOverlay({ widget, onCallTool, toolsEndpoint, headers, resourceEndpoint, onClose, isDark, }: WebMcpOverlayProps): react_jsx_runtime.JSX.Element | null;

/**
 * **Bare-bones, bring-your-own-backend chat primitive.** Most apps want
 * `WaniwaniChat` (the hosted version) — `ChatEmbed` is the unmanaged
 * escape hatch with no token, no remote config, no defaults, and no
 * built-in MCP resource endpoint. You wire up `api`, `headers`, `body`,
 * theme, and (optionally) `mcp` yourself.
 *
 * Sizes off its parent via two complementary mechanisms applied by the
 * embed host: a `height: 100%; max-height: inherit` chain for
 * definite-height parents, and `flex: 1 1 auto; min-height: 0` so the
 * chat also fills a flex-column parent bounded only by `max-height`.
 * Both work across the shadow boundary. When the parent is truly
 * unbounded the chat grows with content; bound it by setting `height`,
 * `max-height`, or a flex/grid track on the parent. Internally a flex
 * column: header and input pinned, messages scrolling between them.
 */
declare const ChatEmbed: react.ForwardRefExoticComponent<ChatEmbedProps & react.RefAttributes<ChatHandle>>;

/**
 * Per-page overrides for `WaniwaniChat`. The Waniwani dashboard is the
 * source of truth for the agent's display config; reach for these only
 * when you need a local tweak that doesn't justify cloning an agent.
 *
 * `welcome` (with a `ReactNode` icon) is the one field that cannot live
 * in the dashboard — it has to be passed here when used.
 */
interface WaniwaniChatOverrides {
    /** Sticky header title. */
    title?: string;
    /**
     * Force-hide the sticky header. Useful when the host page already provides
     * its own chrome and a header would be redundant.
     */
    hideHeader?: boolean;
    /** Greeting shown before the first user message. */
    welcomeMessage?: string;
    /** Rich welcome screen (icon, title, suggestion cards). Takes precedence over `welcomeMessage`. */
    welcome?: WelcomeConfig;
    /** Placeholder for the input field. */
    placeholder?: string;
    /** Initial suggestion chips. */
    suggestions?: string[];
    /** Persist conversations across reloads in IndexedDB. */
    enableThreadHistory?: boolean;
    /**
     * How tool calls render: `true` (default) shows full request/response
     * panels, `"titles-only"` shows a compact indicator with just the tool
     * title, `false` hides tool calls entirely.
     */
    showToolCalls?: ShowToolCalls;
    /** Enable file attachments in the input. */
    allowAttachments?: boolean;
    /**
     * Theme preset (`light`/`dark`/`auto`) plus per-property overrides.
     *
     * ```tsx
     * appearance={{ theme: "dark", variables: { primaryColor: "#ff6b6b" } }}
     * ```
     */
    appearance?: ChatAppearance;
    /** Per-slot class name overrides. See `ChatClassNames`. */
    classNames?: ChatClassNames;
    /** Chat API URL. Defaults to `https://app.waniwani.ai/api/mcp/chat`. */
    api?: string;
    /** Override the MCP server URL (rarely needed). */
    mcpServerUrl?: string;
    /**
     * The app's agent-runtime session route (`/api/mcp/agent/session`). Set,
     * turns go straight to the agent runtime for a chat the route admits, and
     * through `api` for one it does not.
     */
    sessionApi?: string;
    /**
     * AI transparency notice rendered under the input (EU AI Act compliance).
     * String overrides the default wording; `false` hides it.
     */
    disclaimer?: string | false;
    /** @internal Enterprise only: hides the "powered by Waniwani" logo. */
    hidePoweredBy?: boolean;
    /**
     * UI language for built-in labels. One of `"en"`, `"fr"`, `"es"`.
     * When omitted, the widget detects the locale from `<html lang>` /
     * `navigator.language` and falls back to English.
     */
    locale?: Locale;
    /**
     * Per-key overrides on top of the resolved locale catalog. Lets you
     * tweak individual built-in strings without contributing a full locale.
     * Flat (applies to every locale) or keyed by locale.
     */
    messages?: MessageOverrides | LocaleMessageOverrides;
    /**
     * Opt out of the top-of-funnel `page.viewed` event fired once on mount.
     * Defaults to `false` (the event fires). Set `true` on surfaces where a
     * page view is meaningless and would pollute the customer's funnel — an
     * already-authenticated app shell, an internal tool, a preview, etc.
     */
    disablePageView?: boolean;
}
/**
 * Hosted-tier Waniwani chat. The React counterpart to the `<script>` embed.
 *
 * Configure the agent (title, welcome message, suggestions, theme, tool
 * behavior) in the Waniwani dashboard — the component fetches that config
 * on mount. Pass a `wwp_...` token and the `channelId` of the agent, and
 * you're done.
 *
 * Forward a `ChatHandle` ref to drive the chat imperatively
 * (`sendMessage`, `sendMessageAndWait`, `reset`, `focus`, `messages`).
 *
 * Use `overrides` only for per-page tweaks that don't justify a new agent,
 * or for the `welcome` field (which can't be serialized to the dashboard
 * because its `icon` is a `ReactNode`).
 *
 * If you are self-hosting the chat backend, use {@link ChatEmbed} instead.
 *
 * @example
 * ```tsx
 * import { useRef } from "react";
 * import { WaniwaniChat, type ChatHandle } from "@waniwani/chat";
 *
 * function MyPage() {
 *   const ref = useRef<ChatHandle>(null);
 *
 *   return (
 *     <>
 *       <WaniwaniChat
 *         ref={ref}
 *         token="wwp_..."
 *         channelId="51c3658a-..."
 *       />
 *       <button onClick={() => ref.current?.sendMessage("Show me pricing")}>
 *         Ask about pricing
 *       </button>
 *     </>
 *   );
 * }
 * ```
 */
interface WaniwaniChatProps {
    /** Public token (`wwp_...`) from the Waniwani dashboard. */
    token: string;
    /** Agent channel ID — routes the conversation to the right agent. */
    channelId?: string;
    /**
     * Override the anonymous visitor id the widget generates with one you
     * already track (a PostHog / Amplitude / Segment distinct id, your own
     * cookie, etc.). The chat sends it on every request, so Waniwani sessions
     * and events correlate to the same visitor, and server-side MCP tools and
     * flows read it back as `context.waniwani.visitorId`.
     *
     * A string, or a resolver that returns one — sync
     * (`() => posthog.get_distinct_id()`) or async
     * (`async () => (await sdk.ready()).id`), for analytics SDKs whose id is only
     * ready after they bootstrap. Read live on each request, so updating it
     * applies to the next message. A blank / failed result is ignored, keeping
     * the auto-generated, `localStorage`-persisted id. Leave unset to always use
     * the auto id.
     */
    visitorId?: VisitorIdInput;
    /** Additional class names applied to the root element. */
    className?: string;
    /**
     * Per-page overrides of dashboard-configured display fields. The
     * dashboard is the source of truth; use this only when a local tweak
     * doesn't justify a new agent, or to pass `welcome` (whose `icon`
     * can't be serialized to the dashboard).
     */
    overrides?: WaniwaniChatOverrides;
    /**
     * Callback fired on chat lifecycle events (`chat.ready`, `message.sent`,
     * `message.received`, `session.started`, `thread.changed`, `chat.error`,
     * `suggestion.clicked`, `suggestions.shown`, `link.clicked`; `chat.opened`/`chat.closed` are
     * floating-embed-only and never fire here). Message events never include
     * the message text. Use it to mirror widget activity into the host page's
     * analytics. Exceptions thrown by the callback are swallowed and never
     * break the chat.
     */
    onEvent?: (event: WidgetEvent) => void;
}
declare const WaniwaniChat: react.ForwardRefExoticComponent<WaniwaniChatProps & react.RefAttributes<ChatHandle>>;

declare const DEFAULT_THEME: Required<ChatTheme>;
declare const DARK_THEME: ChatTheme;
declare function mergeTheme(userTheme?: ChatTheme): Required<ChatTheme>;
/**
 * Serialise a (partial) `ChatTheme` to inline CSS custom properties. Only
 * keys present on the input are emitted — unspecified properties fall back
 * to the cascade in `tailwind.css` (`var(--ww-primary, #6366f1)` chain).
 * This lets a customer's `[data-waniwani-embed] { --ww-primary: ... }` win
 * over the chat root's defaults when only a few keys are customised.
 */
declare function themeToCSSProperties(theme: ChatTheme): Record<string, string>;

export { type AvatarIntro, type AvatarSlot, type ChatAppearance, type ChatBaseProps, ChatEmbed, type ChatEmbedMcpConfig, type ChatEmbedProps, type ChatHandle, type ChatTheme, DARK_THEME, DEFAULT_THEME, type LocaleMessageOverrides, type McpAppDisplayMode, McpAppFrame, type McpAppFrameProps, type MenuAction, type MessageOverrides, type ShowToolCalls, type SuggestionsConfig, type ThemePreset, WaniwaniChat, type WaniwaniChatOverrides, type WaniwaniChatProps, WebMcpOverlay, type WebMcpOverlayProps, type WelcomeConfig, type WidgetEvent, type WidgetEventName, type WidgetMode, mergeTheme, themeToCSSProperties };
