import { createRoot } from '@wordpress/element';
import apiFetch from '@wordpress/api-fetch';
import RegistrationForm from './pages/RegistrationForm';
import Mypage from './pages/Mypage';

// CSRF トークン + ボットガードを全 POST リクエストに自動付与
apiFetch.use( ( options, next ) => {
	if ( options.method && options.method !== 'GET' ) {
		const security = window.confManagerSecurity || {};

		// CSRF ヘッダー
		if ( security.csrfToken ) {
			options.headers = {
				...( options.headers || {} ),
				'X-Conf-CSRF-Token': security.csrfToken,
			};
		}

		// ボットガードパラメータ（リクエストボディに追加）
		if ( security.botGuard && options.data && typeof options.data === 'object' ) {
			options.data = {
				...options.data,
				_hp: '',
				_ts: security.botGuard._ts,
				_ts_sig: security.botGuard._ts_sig,
			};
		}
	}
	return next( options );
} );

function App( { view } ) {
	switch ( view ) {
		case 'mypage':
			return <Mypage />;
		case 'registration':
		default:
			return <RegistrationForm />;
	}
}

const container = document.getElementById( 'conf-manager-public-app' );
if ( container ) {
	const view = container.getAttribute( 'data-view' ) || 'registration';
	createRoot( container ).render( <App view={ view } /> );
}
