import './bootstrap';
import './username-availability';

import Alpine from 'alpinejs';
import React from 'react';
import { createRoot } from 'react-dom/client';
import AvatarUploader from './components/profile/AvatarUploader';

window.Alpine = Alpine;

Alpine.start();

document.querySelectorAll('[data-avatar-uploader="true"]').forEach((element) => {
	const uploadUrl = element.getAttribute('data-upload-url') || '';
	const initialSrc = element.getAttribute('data-initial-src') || '';
	const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content') || '';

	createRoot(element).render(
		React.createElement(AvatarUploader, {
			uploadUrl,
			initialSrc,
			csrfToken,
		})
	);
});

const storyEditorRoot = document.getElementById('story-editor-react-root');

if (storyEditorRoot) {
	const mode = storyEditorRoot.getAttribute('data-mode') || 'create';
	const storyRaw = storyEditorRoot.getAttribute('data-story') || '{}';
	const storyTypesRaw = storyEditorRoot.getAttribute('data-story-types') || '[]';
	const endpointsRaw = storyEditorRoot.getAttribute('data-endpoints') || '{}';
	const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content') || '';

	let initialStory = {};
	let storyTypes = [];
	let endpoints = {};

	try {
		initialStory = JSON.parse(storyRaw);
		storyTypes = JSON.parse(storyTypesRaw);
		endpoints = JSON.parse(endpointsRaw);
	} catch (_) {
		// If parsing fails, the editor falls back to empty defaults in the component.
	}

	void import('./components/editor/StoryEditor').then(({ default: StoryEditor }) => {
		createRoot(storyEditorRoot).render(
			React.createElement(StoryEditor, {
				mode,
				initialStory,
				storyTypes,
				endpoints,
				csrfToken,
			})
		);
	});
}
