import React from "react";
import { Root, createRoot } from "react-dom/client";
import styles from "./styles/welcome.index.css?inline";
import { RecentEntry, WelcomeActions, WelcomeApi } from "./types/shared-types";
import { WelcomePage } from "./components/welcome-page";
import { WithWelcomeApiContext } from "./context/welcome-api-context";

export class KiroWelcomePage extends HTMLElement {
	private root: Root | null = null;

	private api: WelcomeApi | undefined;
	private recentlyOpened: RecentEntry[] = [];
	private actions: WelcomeActions = {
		mainAction: undefined,
		secondaryActions: [],
	};

	// Define the observed attributes
	static get observedAttributes(): string[] {
		return ["isinternaluser", "requiredsteps", "themetype"];
	}

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

	// Handle attribute changes
	attributeChangedCallback(name: string) {
		if (
			name === "isinternaluser" ||
			name === "requiredsteps" ||
			name === "themetype"
		) {
			this.render();
		}
	}

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

	public setRecentlyOpened(recentlyOpened: RecentEntry[]): void {
		this.recentlyOpened = recentlyOpened;
		this.render();
	}

	public setActions(actions: WelcomeActions): void {
		this.actions = actions;
		this.render();
	}

	private render() {
		if (!this.api) {
			return null;
		}
		this.root?.render(
			<React.StrictMode>
				<WithWelcomeApiContext api={this.api}>
					<WelcomePage
						actions={this.actions}
						recentEntries={this.recentlyOpened}
					/>
				</WithWelcomeApiContext>
			</React.StrictMode>
		);
	}

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

//export default KiroSignInPage;

// Register the custom element
customElements.define("kiro-welcome-page", KiroWelcomePage);
