// 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, useSyncExternalStore } from '@lynx-js/react';
import { useA2UIContext } from './useA2UIContext.js';
import { useAction } from './useAction.js';
import { useCatalog } from './useCatalog.js';
import { splitUnsupportedProps, useResolvedProps } from './useDataBinding.js';
import { Loading } from '../catalog/Loading/index.jsx';
const noop = () => {
    /* no-op subscribe disposer */
};
const noopSubscribe = () => noop;
const emptySnapshot = {
    status: 'pending',
    value: undefined,
    error: undefined,
};
const returnEmptySnapshot = () => emptySnapshot;
const warnedTags = new Set();
function DefaultLoading(_props) {
    return Loading({ variant: 'block' });
}
function DefaultUnsupportedNotice(props) {
    return (<view style={{
            width: '100%',
            minHeight: '20px',
            marginBottom: '8px',
            padding: '6px',
            borderRadius: '6px',
            border: '1px dashed var(--a2ui-color-border)',
            backgroundColor: 'var(--a2ui-color-surface-muted)',
            color: 'var(--a2ui-color-text-muted)',
        }}>
      <text style={{ color: 'inherit', fontSize: '10px', lineHeight: '12px' }}>
        Unsupported {props.kind} in {props.id}
      </text>
    </view>);
}
function buildNodeRecursive(component, surface, catalog, renderUnsupported, props, setValue, sendAction, suppressActionDispatch = false) {
    const tag = component.component;
    const Component = catalog.get(tag);
    const renderUnsupportedNotice = (info) => {
        if (typeof renderUnsupported === 'function') {
            return renderUnsupported(info);
        }
        return <DefaultUnsupportedNotice {...info}/>;
    };
    if (!Component) {
        return renderUnsupportedNotice({
            id: component.id ?? '',
            tag,
            kind: 'component',
        });
    }
    const { unsupportedFields, displayProps } = splitUnsupportedProps(props);
    return (<>
      {unsupportedFields.length > 0
            ? (renderUnsupportedNotice({
                id: component.id ?? '',
                tag,
                kind: 'syntax',
                fields: unsupportedFields,
            }))
            : null}
      <Component key={component.id} {...displayProps} id={component.id ?? ''} surface={surface} setValue={setValue} sendAction={suppressActionDispatch
            ? undefined
            : (a) => {
                void sendAction?.(a);
            }} dataContextPath={component.dataContextPath}/>
    </>);
}
function A2UIRendererImpl(props) {
    const { resource, renderUnsupported, wrapSurface, renderFallback, renderError, className: surfaceClassName = 'surface-root', } = props;
    // Eagerly read context so the renderer fails clearly outside <A2UIProvider>.
    useCatalog();
    const snapshot = useSyncExternalStore(resource.subscribe, resource.getSnapshot, resource.getSnapshot);
    const data = snapshot.value;
    const status = snapshot.status;
    const error = snapshot.error;
    if (status === 'pending' && data === undefined) {
        // Use a ternary instead of `??` so consumers can return `null` from
        // the override callback to suppress the built-in placeholder.
        return renderFallback
            ? renderFallback()
            : <DefaultLoading id={resource.id}/>;
    }
    if (status === 'error') {
        return renderError
            ? renderError(error)
            : <text>Error: {String(error)}</text>;
    }
    if (!data)
        return null;
    const dataObj = data;
    const type = dataObj['type'];
    const surfaceId = dataObj['surfaceId'];
    const surface = dataObj['surface'];
    const component = dataObj['component'];
    if (type === 'beginRendering') {
        const id = surface.rootComponentId;
        const childResource = surface.resources.get(id);
        if (!childResource)
            return null;
        const childProps = { resource: childResource };
        if (wrapSurface)
            childProps.wrapSurface = wrapSurface;
        if (renderFallback)
            childProps.renderFallback = renderFallback;
        if (renderError)
            childProps.renderError = renderError;
        if (renderUnsupported)
            childProps.renderUnsupported = renderUnsupported;
        const inner = (<view id={`surface-${surfaceId}`} className={surfaceClassName}>
        <A2UIRenderer {...childProps}/>
      </view>);
        return wrapSurface ? wrapSurface(inner, { surfaceId }) : inner;
    }
    if (type === 'surfaceUpdate' && component) {
        return (<NodeRenderer component={component} surface={surface} renderUnsupported={renderUnsupported}/>);
    }
    if (type === 'deleteSurface') {
        return null;
    }
    return null;
}
export const A2UIRenderer = memo(A2UIRendererImpl);
function NodeRendererImpl(props) {
    const { component: initialComponent, surface, suppressActionDispatch = false, renderUnsupported, } = props;
    const { catalog: activeCatalog, processor } = useA2UIContext();
    const catalog = useCatalog();
    const resource = surface.resources.get(initialComponent.id);
    const latest = useSyncExternalStore(resource ? resource.subscribe : noopSubscribe, resource ? resource.getSnapshot : returnEmptySnapshot, resource ? resource.getSnapshot : returnEmptySnapshot);
    const component = latest.value?.component
        ?? initialComponent;
    const effectiveComponent = initialComponent.dataContextPath !== undefined
        && component.dataContextPath !== initialComponent.dataContextPath
        ? { ...component, dataContextPath: initialComponent.dataContextPath }
        : component;
    useEffect(() => {
        const tag = effectiveComponent.component;
        if (!catalog.has(tag) && !warnedTags.has(tag)) {
            warnedTags.add(tag);
            console.warn(`[a2ui] Component "${tag}" is not in the active catalog.`);
        }
    }, [effectiveComponent.component, catalog]);
    const [resolvedProps, setValue] = useResolvedProps(effectiveComponent, surface, effectiveComponent.dataContextPath, processor, activeCatalog.functions);
    const actionProps = useMemo(() => ({
        id: effectiveComponent.id,
        surfaceId: surface.surfaceId,
        dataContext: effectiveComponent.dataContextPath,
    }), [
        effectiveComponent.id,
        surface.surfaceId,
        effectiveComponent.dataContextPath,
    ]);
    const { sendAction } = useAction(actionProps);
    return (buildNodeRecursive(effectiveComponent, surface, catalog, renderUnsupported, resolvedProps, setValue, (a) => {
        void sendAction(a);
    }, suppressActionDispatch));
}
export const NodeRenderer = NodeRendererImpl;
//# sourceMappingURL=A2UIRenderer.jsx.map