'use client'

import { useEffect, useRef } from 'react';
import { useSearchParams } from 'next/navigation';

import { message_style } from '../components/Input.css';

export default function Input() {
	const search_params = useSearchParams();
	const input_ref = useRef<HTMLParagraphElement>(null);

	function set_message(message: string) {
		const encoded = btoa(message);
		const new_url = `${window.location.protocol}//${window.location.host}${window.location.pathname}?e=${encoded}`;
		window.history.replaceState('', '', new_url);
	}

	const message = search_params.get('e') ?
		atob(search_params.get('e')!) :
		(
			search_params.get('m')
			?? 'At the apex of the pyramid comes Big Brother. Big Brother is infallible and all-powerful. Every success, every achievement, every victory, every scientific discovery, all knowledge, all wisdom, all happiness, all virtue, are held to issue directly from his leadership and inspiration.'
		);

	useEffect(() => {
		set_message(message);
	});

	return (
		<p
			ref={input_ref}
			className={message_style}
			onInput={() => set_message(input_ref.current!.textContent ?? '')}
			contentEditable
		>
			{message}
		</p>
	);
}
