import React from "react";
import { Root, createRoot } from "react-dom/client";
import styles from "./styles/profile-selector.css?inline";
import { ProfileSelectorApi } from "./types/profile-selector-types";
import { WithProfileSelectorApiContext } from "./context/profile-selector-api-context";
import { ProfileSelector } from "./components/profile-selector";

export class ProfileSelectorElement extends HTMLElement {
	private root: Root | null = null;
	private api: ProfileSelectorApi | undefined;

	constructor(private shouldAutoSelect?: boolean) {
		super();
		this.attachShadow({ mode: "open" });
		this.root = this.root
			? this.root
			: createRoot(this.shadowRoot as ShadowRoot);
		this.style.flex = "1";
		const styleEl = document.createElement("style");
		styleEl.textContent = styles;
		this.shadowRoot?.appendChild(styleEl);
	}

	public setApi(api: ProfileSelectorApi): void {
		this.api = api;
		this.render();
	}

	private render() {
		if (!this.api) {
			return null;
		}
		this.root?.render(
			<React.StrictMode>
				<WithProfileSelectorApiContext api={this.api}>
					<ProfileSelector shouldAutoSelect={this.shouldAutoSelect} />
				</WithProfileSelectorApiContext>
			</React.StrictMode>
		);
	}

	connectedCallback() {
		this.render();
	}
}

// Register the custom element
customElements.define("profile-selector", ProfileSelectorElement);
