// 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 { 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';
/**
 * 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) {
    if (props.messageStore === null) {
        return null;
    }
    return <A2UISession {...props} messageStore={props.messageStore}/>;
}
function A2UISession(props) {
    const { messageStore, catalogs, onAction, onMessage, catalogId = 'https://unpkg.com/@lynx-js/genui/a2ui/dist/catalog.json', 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 onMessageRef = useRef(onMessage);
    onMessageRef.current = onMessage;
    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;
    const catalog = useMemo(() => defineCatalog(catalogs), [catalogs]);
    session.processor.registerCatalog(catalogId, catalog);
    // 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, reject }) => {
            // Acknowledge transport completion; protocol responses arrive via the buffer.
            try {
                const pending = onMessageRef.current?.(message, proc.getDataModelMetadata());
                void Promise.resolve(pending).then(() => resolve([]), error => {
                    console.error('[a2ui] onMessage handler rejected:', error);
                    reject(error);
                });
            }
            catch (e) {
                console.error('[a2ui] onMessage handler threw:', e);
                reject(e);
            }
            if ('action' in message) {
                try {
                    onActionRef.current?.(message['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 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>);
}
/** Render A2UI protocol messages using the supplied catalogs. */
export const A2UI = memo(A2UIImpl);
//# sourceMappingURL=A2UI.jsx.map