"use strict";
/**
 * @file react-bridge.ts
 * Bridge for mounting React components in Drupal
 */
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ReactBridge = void 0;
const react_1 = __importDefault(require("react"));
const client_1 = __importDefault(require("react-dom/client"));
// Import AI components
const AiButton_1 = require("../components/AiButton");
const AiCard_1 = require("../components/AiCard");
const AiInput_1 = require("../components/AiInput");
const AiDashboard_1 = require("../components/AiDashboard");
// Component registry
const componentRegistry = {
    AiButton: AiButton_1.AiButton,
    AiCard: AiCard_1.AiCard,
    AiInput: AiInput_1.AiInput,
    AiDashboard: AiDashboard_1.AiDashboard,
};
/**
 * React Bridge for Drupal integration
 */
class ReactBridge {
    /**
     * Mount a React component in a DOM element
     */
    static mount(componentName, element, options) {
        const Component = componentRegistry[componentName];
        if (!Component) {
            console.error(`Component ${componentName} not found in registry`);
            return '';
        }
        // Generate unique instance ID
        const instanceId = `${componentName}-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
        // Create root
        const root = client_1.default.createRoot(element);
        // Render component with props
        const wrappedComponent = react_1.default.createElement(Component, options.props);
        // Render component
        root.render(wrappedComponent);
        // Store instance
        this.instances.set(instanceId, root);
        // Call mount callback
        if (options.onMount) {
            options.onMount();
        }
        // Add data attribute for tracking
        element.setAttribute('data-react-instance', instanceId);
        return instanceId;
    }
    /**
     * Unmount a React component
     */
    static unmount(instanceId) {
        const root = this.instances.get(instanceId);
        if (!root) {
            console.warn(`No React instance found with ID: ${instanceId}`);
            return false;
        }
        // Unmount component
        root.unmount();
        // Remove from registry
        this.instances.delete(instanceId);
        // Find element and clean up
        const element = document.querySelector(`[data-react-instance="${instanceId}"]`);
        if (element) {
            element.removeAttribute('data-react-instance');
        }
        return true;
    }
    /**
     * Update props for a mounted component
     */
    static updateProps(instanceId, newProps) {
        const root = this.instances.get(instanceId);
        if (!root) {
            console.warn(`No React instance found with ID: ${instanceId}`);
            return false;
        }
        // Re-render with new props
        const element = document.querySelector(`[data-react-instance="${instanceId}"]`);
        if (element) {
            const componentName = instanceId.split('-')[0];
            const Component = componentRegistry[componentName];
            if (Component) {
                root.render(react_1.default.createElement(Component, newProps));
                return true;
            }
        }
        return false;
    }
    /**
     * Mount all components found in the DOM
     */
    static mountAll(context = document.body) {
        // Find all elements with data-react-component attribute
        const elements = context.querySelectorAll('[data-react-component]');
        elements.forEach((element) => {
            const componentName = element.getAttribute('data-react-component');
            const propsJson = element.getAttribute('data-react-props');
            if (componentName && componentRegistry[componentName]) {
                let props = {};
                // Parse props if provided
                if (propsJson) {
                    try {
                        props = JSON.parse(propsJson);
                    }
                    catch (e) {
                        console.error('Failed to parse React props:', e);
                    }
                }
                // Extract props from data attributes
                const dataProps = this.extractDataProps(element);
                props = { ...props, ...dataProps };
                // Mount component
                this.mount(componentName, element, {
                    props,
                    enableAI: element.hasAttribute('data-ai-enabled'),
                });
            }
        });
    }
    /**
     * Extract props from data attributes
     */
    static extractDataProps(element) {
        const props = {};
        // Convert data-prop-* attributes to props
        Array.from(element.attributes).forEach((attr) => {
            if (attr.name.startsWith('data-prop-')) {
                const propName = attr.name.replace('data-prop-', '').replace(/-./g, x => x[1].toUpperCase());
                props[propName] = attr.value;
                // Parse JSON values
                if (attr.value.startsWith('{') || attr.value.startsWith('[')) {
                    try {
                        props[propName] = JSON.parse(attr.value);
                    }
                    catch (e) {
                        // Keep as string if JSON parsing fails
                    }
                }
                // Convert boolean strings
                if (attr.value === 'true' || attr.value === 'false') {
                    props[propName] = attr.value === 'true';
                }
            }
        });
        return props;
    }
    /**
     * Get all mounted instances
     */
    static getInstances() {
        return Array.from(this.instances.keys());
    }
    /**
     * Clear all mounted instances
     */
    static unmountAll() {
        this.instances.forEach((root, instanceId) => {
            this.unmount(instanceId);
        });
    }
}
exports.ReactBridge = ReactBridge;
ReactBridge.instances = new Map();
// AI functionality removed for working implementation
/**
 * Global exports for Drupal integration
 */
if (typeof window !== 'undefined') {
    window.LLMUIComponents = {
        ...componentRegistry,
        ReactBridge,
        mount: ReactBridge.mount.bind(ReactBridge),
        unmount: ReactBridge.unmount.bind(ReactBridge),
        mountAll: ReactBridge.mountAll.bind(ReactBridge),
        unmountAll: ReactBridge.unmountAll.bind(ReactBridge),
    };
}
/**
 * Auto-mount components on DOM ready
 */
if (typeof document !== 'undefined') {
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', () => {
            ReactBridge.mountAll();
        });
    }
    else {
        // DOM already loaded
        ReactBridge.mountAll();
    }
}
// Export for module usage
exports.default = ReactBridge;
//# sourceMappingURL=react-bridge.js.map