import React from "react";
import { Root, createRoot } from "react-dom/client";
import styles from "./styles/account-dashboard.css?inline";
import { AccountDashboardApi } from "./types/account-dashboard-types";
import { WithKiroAccountApiContext } from "./context/account-dashboard-api-context";
import { AccountDashboardPage } from "./components/account-dashboard-page/account-dashboard-page";

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

	private api: AccountDashboardApi | undefined;
	private refreshKey: number = 0;

	constructor() {
		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: AccountDashboardApi): void {
		this.api = api;
		this.render();
	}

	public refreshData(): void {
		// Increment refresh key to force re-render and data refresh
		this.refreshKey++;
		this.render();
	}

	private render() {
		if (!this.api) {
			return null;
		}
		this.root?.render(
			<React.StrictMode>
				<WithKiroAccountApiContext api={this.api}>
					<AccountDashboardPage key={this.refreshKey} />
				</WithKiroAccountApiContext>
			</React.StrictMode>
		);
	}

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

// Register the custom element
customElements.define("account-dashboard", AccountDashboardElement);
