// Copyright 2026 The Lynx Authors. All rights reserved.
// Licensed under the Apache License Version 2.0 that can be found in the
// LICENSE file in the root directory of this source tree.
import * as v0_9 from '@a2ui/web_core/v0_9';
import { memo, useEffect, useMemo, useReducer, useRef, useSyncExternalStore, } from '@lynx-js/react';
import { A2UIProvider } from './A2UIProvider.jsx';
import { A2UIRenderer } from './A2UIRenderer.jsx';
import { defineCatalog } from '../catalog/defineCatalog.js';
import { MessageProcessor } from '../store/MessageProcessor.js';
import { createResource } from '../store/Resource.js';
// Mark v0_9 used so the namespace import doesn't get pruned. Kept around so
// future enhancements (typed protocol message guards) don't need a fresh
// import diff.
void v0_9;
/**
 * The all-in-one A2UI component. Owns a `MessageProcessor` internally,
 * processes raw messages from the buffer on each render, and renders
 * the most recent `beginRendering` surface tree.
 *
 * @example
 * const store = createMessageStore();
 *
 * // Developer's IO module pushes raw messages into the store.
 * async function streamFromAgent(input: string) {
 *   for await (const msg of myAgent.stream(input)) store.push(msg);
 * }
 *
 * <A2UI
 *   messageStore={store}
 *   catalogs={[Text, Button, [Card, cardManifest]]}
 *   onAction={(action) => { void streamFromAgent(serializeAction(action)); }}
 *   wrapSurface={(c) => <view className='luna-light'>{c}</view>}
 * />
 */
function A2UIImpl(props) {
    const { messageStore, catalogs, onAction, wrapSurface, renderEmpty, renderFallback, renderError, renderUnsupported, className, } = props;
    // Keep the latest onAction in a ref so the once-mounted processor.onEvent
    // listener always calls the up-to-date prop without re-binding.
    const onActionRef = useRef(onAction);
    useEffect(() => {
        onActionRef.current = onAction;
    }, [onAction]);
    // Per-instance session. Created once; mutated as messages arrive.
    const sessionRef = useRef(null);
    sessionRef.current ??= {
        processor: new MessageProcessor(),
        resources: new Map(),
        activeMessageId: null,
        processedCount: 0,
    };
    const session = sessionRef.current;
    // Counter used to force a re-render whenever the processor emits an
    // update (new beginRendering, surfaceUpdate that mutated the active
    // surface, deleteSurface). The processor's per-resource `onUpdate`
    // already handles fine-grained updates inside the active surface;
    // this is just for the activeResource pointer + first paint.
    const [, forceUpdate] = useReducer((n) => n + 1, 0);
    // Subscribe to the developer's raw buffer.
    const messages = useSyncExternalStore(messageStore.subscribe, messageStore.getSnapshot, messageStore.getSnapshot);
    // One-time wiring of processor → resource bookkeeping + onAction
    // dispatch. The processor instance itself is stable across renders.
    useEffect(() => {
        const proc = session.processor;
        const offUpdate = proc.onUpdate((data) => {
            const { type, surfaceId, messageId } = data;
            const surface = proc.getOrCreateSurface(surfaceId);
            if (type === 'beginRendering') {
                let resource = session.resources.get(messageId);
                if (!resource) {
                    resource = createResource(messageId);
                    session.resources.set(messageId, resource);
                }
                resource.complete({ type: 'beginRendering', surfaceId, surface });
                session.activeMessageId = messageId;
                forceUpdate();
            }
            else if (type === 'surfaceUpdate') {
                const updates = data.updates ?? [];
                for (const update of updates) {
                    if (!update.id)
                        continue;
                    const r = surface.resources.get(update.id);
                    r?.complete({
                        type: 'surfaceUpdate',
                        surfaceId,
                        surface,
                        component: update,
                    });
                }
            }
            else if (type === 'deleteSurface') {
                const targetId = data.targetId
                    ?? surface.rootComponentId;
                if (targetId && surface.resources.has(targetId)) {
                    surface.resources.get(targetId).complete({
                        type: 'deleteSurface',
                        surfaceId,
                        surface,
                    });
                }
                forceUpdate();
            }
        });
        const offEvent = proc.onEvent(({ message, resolve }) => {
            // Empty resolve — there is no "response" channel from the renderer
            // back into the protocol. Responses arrive via the buffer.
            resolve([]);
            if (typeof message === 'object' && message !== null
                && 'userAction' in message
                && message.userAction) {
                const action = message.userAction;
                try {
                    onActionRef.current?.(action);
                }
                catch (e) {
                    console.error('[a2ui] onAction handler threw:', e);
                }
            }
        });
        return () => {
            offUpdate();
            offEvent();
        };
    }, [session]);
    // Process any new messages in the buffer.
    useEffect(() => {
        if (messages.length === session.processedCount)
            return;
        const slice = messages.slice(session.processedCount);
        session.processedCount = messages.length;
        if (slice.length > 0) {
            session.processor.processMessages(slice);
        }
    }, [messages, session]);
    const catalog = useMemo(() => defineCatalog(catalogs), [catalogs]);
    const activeResource = session.activeMessageId
        ? (session.resources.get(session.activeMessageId) ?? null)
        : null;
    if (!activeResource) {
        return renderEmpty?.() ?? null;
    }
    const rendererProps = {
        resource: activeResource,
    };
    if (className !== undefined)
        rendererProps.className = className;
    if (wrapSurface)
        rendererProps.wrapSurface = wrapSurface;
    if (renderFallback)
        rendererProps.renderFallback = renderFallback;
    if (renderError)
        rendererProps.renderError = renderError;
    if (renderUnsupported)
        rendererProps.renderUnsupported = renderUnsupported;
    return (<A2UIProvider processor={session.processor} catalog={catalog}>
      <A2UIRenderer {...rendererProps}/>
    </A2UIProvider>);
}
export const A2UI = memo(A2UIImpl);
//# sourceMappingURL=A2UI.jsx.map