import { DBG } from '../dbg'

export default function getElByClientId( clientId: string ) {
    const doc = getCanvasDocument();
    const element = doc.querySelector<HTMLElement>(`[data-block="${clientId}"]`)
    if (!element) {
        DBG&&console.warn('getElByClientId(): Element not found for clientId=', clientId);
        return null;
    }
    DBG&&console.log('getElByClientId(): ', { clientId, element });
    return element;
}

function getCanvasDocument(): Document {
    const iframe =
        document.querySelector<HTMLIFrameElement>('iframe[name="editor-canvas"]') ||
        document.querySelector<HTMLIFrameElement>('.editor-canvas__iframe');
    DBG&&console.log('getElByClientId() => getCanvasDocument: iframe=', iframe);
    if (!iframe) {
        DBG&&console.warn('getElByClientId() => getCanvasDocument: iframe not found');
    }
    return iframe?.contentDocument ?? document;
}
