import { createRoot, useState, useCallback, useEffect } from '@wordpress/element';
import { __ } from '@wordpress/i18n';
import Layout from './components/Layout';
import ErrorBoundary from './components/ErrorBoundary';
import Dashboard from './pages/Dashboard';
import Setup from './pages/Setup';
import Members from './pages/Members';
import Events from './pages/Events';
import Participants from './pages/Participants';
import Payments from './pages/Payments';

const ROUTE_CAPS = {
	'/setup': 'conf_manager_manage_settings',
	'/members': 'conf_manager_view_members',
	'/events': 'conf_manager_view_events',
	'/participants': 'conf_manager_view_registrations',
	'/payments': 'conf_manager_view_payments',
};

function hasCap( cap ) {
	return !! window.confManagerCaps?.caps?.[ cap ];
}

function getDefaultPath() {
	return '/';
}

function App() {
	const [ path, setPath ] = useState( window.location.hash.replace( '#', '' ) || '/' );

	const navigate = useCallback( ( newPath ) => {
		window.location.hash = newPath;
		setPath( newPath );
	}, [] );

	useEffect( () => {
		const handler = () => {
			setPath( window.location.hash.replace( '#', '' ) || '/' );
		};
		window.addEventListener( 'hashchange', handler );
		return () => window.removeEventListener( 'hashchange', handler );
	}, [] );

	const renderPage = () => {
		const routePrefix = '/' + ( path.split( '/' )[ 1 ] || '' );
		const requiredCap = ROUTE_CAPS[ routePrefix ];

		if ( requiredCap && ! hasCap( requiredCap ) ) {
			const defaultPath = getDefaultPath();
			if ( routePrefix !== defaultPath ) {
				navigate( defaultPath );
				return null;
			}
			return (
				<div className="conf-manager-notice-error">
					<p>{ __( 'You do not have permission to access this page.', 'conferencemanager' ) }</p>
				</div>
			);
		}

		if ( path.startsWith( '/setup' ) ) return <Setup />;
		if ( path.startsWith( '/members' ) ) return <Members path={ path } onNavigate={ navigate } />;
		if ( path.startsWith( '/events' ) ) return <Events path={ path } onNavigate={ navigate } />;
		if ( path.startsWith( '/participants' ) ) return <Participants />;
		if ( path.startsWith( '/payments' ) ) return <Payments />;

		return <Dashboard />;
	};

	return (
		<Layout currentPath={ '/' + ( path.split( '/' )[ 1 ] || '' ) } onNavigate={ navigate }>
			<ErrorBoundary resetKey={ path }>
				{ renderPage() }
			</ErrorBoundary>
		</Layout>
	);
}

const container = document.getElementById( 'conf-manager-admin-app' );
if ( container ) {
	createRoot( container ).render( <App /> );
}
