import React, { StrictMode, useState } from 'react'
import { createRoot } from 'react-dom/client'


import { useUnstrictEffect as useEffect } from './useUnstrictEffect'


const ApiTest = function ({ path, method, params }) {
	const [ result, setResult ] = useState(null)
	useEffect(() => {
		let endpoint_full
		let body
		if (method === 'GET') {
			endpoint_full = path + '?' + new URLSearchParams({
				p: JSON.stringify(params),
			}).toString()
		}
		else if (method === 'POST') {
			endpoint_full = path
			body = JSON.stringify(params)
		}
		else {
			throw `bad method : ${method}`
		}
		fetch(endpoint_full, { method, body }).then(async (resp) => {
			const resp_json = await resp.json()
			setResult(resp_json)
			return
		})
		return () => {
			return
		}
	}, [])
	return (
		<div>
			{JSON.stringify(result)}
		</div>
	)
}


const App = function () {
	
	//let jsx_inner = <ApiTest path={'/stash'} method={'POST'} params={{ collection_name: 'misc', documents: ['hello', 'world'], wait_for_result: true }} />
	let jsx_inner = <ApiTest path={'/search'} method={'POST'} params={{ collection_name: 'misc', qtext: 'hello!', limit: 10 }} />

	return (
		<div style={{ height: '100%', width: '100%', overflow: 'auto', backgroundColor: '#000', color: '#FFF', fontFamily: 'monospace', fontSize: `${2*8}px`, lineHeight: `${2*8}px` }}>
			{jsx_inner}
		</div>
	)
}


const render_app = function () {
	
	const elem_appstyles = document.createElement('style')
	elem_appstyles.innerHTML = `
html, body {
	height: 100%;
	width: 100%;
	overflow: hidden;
	margin: 0px;
	padding: 0px;
	border: 0px;
}
`.trim()
	document.head.appendChild(elem_appstyles)
	
	const elem_root = document.createElement('div')
	elem_root.style = 'height:100%; width:100%;'
	document.body.appendChild(elem_root)
	
	const func_render_app = () => {
		
		const react_root = createRoot(elem_root)
		
		react_root.render((
			<StrictMode>
				<App />
			</StrictMode>
		))
		
		return
		
	}
	
	func_render_app()

	return {}
	
}

export { render_app }
