/**
 * Frontend React component for Algolia Agent Chat block.
 * Uses React InstantSearch Chat widget.
 */

import React from 'react';
import { createRoot } from 'react-dom/client';
import algoliasearch from 'algoliasearch/lite';
import { InstantSearch, Chat } from 'react-instantsearch';

const BLOCK_SELECTOR = '.wp-block-wlc-algolia-agent-chat';

function initAgentChat() {
	const blocks = document.querySelectorAll( BLOCK_SELECTOR );
	if ( ! blocks.length ) return;

	blocks.forEach( ( block ) => {
		if ( block.dataset.initialized ) return;
		block.dataset.initialized = '1';

		const config = JSON.parse( block.dataset.config || '{}' );
		const container = block.querySelector( '[data-role="chat-container"]' );

		if ( ! container || ! config.agentId || ! config.appId || ! config.apiKey ) {
			console.error( '[Algolia Agent Chat] Missing required configuration.', { config } );
			if ( container ) {
				container.innerHTML = '<div class="wp-block-wlc-algolia-agent-chat__error-message">Error: Missing Algolia Agent Chat configuration. Please check block settings and plugin API keys.</div>';
			}
			return;
		}

		// Create search client
		const searchClient = algoliasearch( config.appId, config.apiKey );

		// Create React root and render Chat component
		const root = createRoot( container );
		root.render(
			<InstantSearch
				indexName="instant_search" // Required by InstantSearch, but not used by Chat widget
				searchClient={ searchClient }
			>
				<div
					className="wp-block-wlc-algolia-agent-chat__chat-wrapper"
					style={ {
						height: config.height || '600px',
					} }
				>
					<Chat
						agentId={ config.agentId }
						onError={ ( error ) => {
							console.error( '[Algolia Agent Chat] Chat widget error:', error );
							// Log detailed error information
							if ( error.message ) {
								console.error( '[Algolia Agent Chat] Error message:', error.message );
							}
							if ( error.response ) {
								console.error( '[Algolia Agent Chat] Error response:', error.response );
							}
						} }
						translations={ {
							header: {
								title: config.headerText || 'AI Assistant',
							},
							prompt: {
								textareaPlaceholder: config.placeholder || 'Ask me anything...',
							},
							messages: {
								loaderText: 'Thinking...',
							},
						} }
						classNames={ {
							root: 'wp-block-wlc-algolia-agent-chat__chat-root',
							container: 'wp-block-wlc-algolia-agent-chat__chat-container',
							header: {
								root: 'wp-block-wlc-algolia-agent-chat__header',
								title: 'wp-block-wlc-algolia-agent-chat__header-title',
							},
							messages: {
								root: 'wp-block-wlc-algolia-agent-chat__messages',
								content: 'wp-block-wlc-algolia-agent-chat__messages-content',
							},
							message: {
								root: 'wp-block-wlc-algolia-agent-chat__message',
								container: 'wp-block-wlc-algolia-agent-chat__message-container',
								content: 'wp-block-wlc-algolia-agent-chat__message-content',
							},
							prompt: {
								root: 'wp-block-wlc-algolia-agent-chat__prompt',
								textarea: 'wp-block-wlc-algolia-agent-chat__input',
								submit: 'wp-block-wlc-algolia-agent-chat__send',
							},
						} }
					/>
				</div>
			</InstantSearch>
		);
	} );
}

// Initialize on DOM ready
if ( document.readyState === 'loading' ) {
	document.addEventListener( 'DOMContentLoaded', initAgentChat );
} else {
	initAgentChat();
}

