import type { ILoadingScreen } from '@babylonjs/core';
import { ADOM_LOGO_BASE64 } from '../assets/adomLogo';

export class ResizableLoadingScreen implements ILoadingScreen {
    private _renderingCanvas: HTMLCanvasElement;
    private _loadingDiv: HTMLDivElement | null = null;
    private _resizeObserver: ResizeObserver | null = null;

    public loadingUIText: string;
    public loadingUIBackgroundColor: string;

    constructor(
        renderingCanvas: HTMLCanvasElement,
        loadingText: string = 'Loading...',
        loadingDivBackgroundColor: string = '#bfbfbf'
    ) {
        this._renderingCanvas = renderingCanvas;
        this.loadingUIText = loadingText;
        this.loadingUIBackgroundColor = loadingDivBackgroundColor;
    }

    public displayLoadingUI(): void {
        if (this._loadingDiv) return;

        this._loadingDiv = document.createElement('div');
        this._loadingDiv.id = 'babylonjsLoadingDiv';
        this._loadingDiv.style.cssText = `
            position: absolute; top: 0; left: 0;
            width: 100%; height: 100%;
            background-color: ${this.loadingUIBackgroundColor};
            display: flex; flex-direction: column;
            justify-content: center; align-items: center;
            z-index: 1000; pointer-events: none;
        `;

        const logoImg = document.createElement('img');
        logoImg.src = ADOM_LOGO_BASE64;
        logoImg.style.cssText = `
            max-width: 15%; max-height: 15%;
            object-fit: contain; margin-bottom: 20px;
        `;

        const textDiv = document.createElement('div');
        textDiv.innerText = this.loadingUIText;
        textDiv.style.cssText = `
            color: white; font-size: 14px;
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
        `;

        this._loadingDiv.appendChild(logoImg);
        this._loadingDiv.appendChild(textDiv);

        const canvasParent = this._renderingCanvas.parentElement;
        if (canvasParent) {
            canvasParent.appendChild(this._loadingDiv);
            this._resizeObserver = new ResizeObserver(() => this._updateSize());
            this._resizeObserver.observe(canvasParent);
        }
    }

    public hideLoadingUI(): void {
        this._loadingDiv?.remove();
        this._loadingDiv = null;
        this._resizeObserver?.disconnect();
        this._resizeObserver = null;
    }

    private _updateSize(): void {
        if (this._loadingDiv && this._renderingCanvas.parentElement) {
            const p = this._renderingCanvas.parentElement;
            this._loadingDiv.style.width = `${p.clientWidth}px`;
            this._loadingDiv.style.height = `${p.clientHeight}px`;
        }
    }
}
