import { html } from "lit";
import { ifDefined } from "lit/directives/if-defined.js";
import { ref } from "lit/directives/ref.js";
import { eventPromise } from "../../../../utils/event-utils.js";
const documentIdentifierInIframe = 'CoveoDocIdentifier';
const writeDocument = (documentWriter, content)=>{
    documentWriter.open();
    documentWriter.write(content);
    documentWriter.close();
    if (documentWriter.scrollingElement) documentWriter.scrollingElement.scrollTop = 0;
};
const currentResultAlreadyWrittenToDocument = (documentWriter, uniqueIdentifier)=>{
    const currentDocIdentifier = documentWriter.getElementById(documentIdentifierInIframe);
    return currentDocIdentifier?.textContent === uniqueIdentifier;
};
const ensureSameResultIsNotOverwritten = (documentWriter, uniqueIdentifier)=>{
    const docIdentifier = documentWriter.createElement('div');
    docIdentifier.style.display = 'none';
    docIdentifier.setAttribute('aria-hidden', 'true');
    docIdentifier.id = documentIdentifierInIframe;
    docIdentifier.textContent = uniqueIdentifier;
    documentWriter.body.appendChild(docIdentifier);
};
const warnAboutLimitedUsageQuickview = (logger)=>{
    logger?.warn('Quickview initialized in restricted mode due to incompatible sandboxing environment. Keywords hit navigation will be disabled.');
};
const iframeConnectedEvent = async (iframe, logger)=>{
    if (iframe.isConnected) return;
    const timeoutMs = 1000;
    await eventPromise(iframe, 'load', timeoutMs).catch(()=>{
        logger?.warn('Quickview timed out waiting for the iframe to load.');
    });
};
const renderQuickviewIframe = ({ props })=>{
    const { title, onSetIframeRef, uniqueIdentifier, content, sandbox, src, logger } = props;
    const waitForIframeContentToBeWritten = ()=>new Promise((resolve)=>setTimeout(resolve));
    const handleRef = (el)=>{
        if (!el) return;
        const iframeRef = el;
        if (!uniqueIdentifier || !content) return;
        const writeContentWhenReady = async ()=>{
            await iframeConnectedEvent(iframeRef, logger);
            const documentWriter = iframeRef.contentDocument;
            if (!documentWriter) {
                if (src) {
                    warnAboutLimitedUsageQuickview(logger);
                    iframeRef.src = src;
                }
                return;
            }
            if (currentResultAlreadyWrittenToDocument(documentWriter, uniqueIdentifier)) return;
            writeDocument(documentWriter, content);
            ensureSameResultIsNotOverwritten(documentWriter, uniqueIdentifier);
            await waitForIframeContentToBeWritten();
            onSetIframeRef(iframeRef);
        };
        writeContentWhenReady();
    };
    return html`<iframe
    title=${title}
    src="about:blank"
    class="h-full w-full"
    sandbox=${ifDefined(sandbox)}
    ${ref(handleRef)}
  ></iframe>`;
};
export { renderQuickviewIframe };
