const INVITE_CONFIG_KEYS = Object.fromEntries(TemplateCatalog.all.map(template => [template.id, template.configKey]));
function publicBootstrapJson(value) {
    return JSON.stringify(value).replace(/[<>&\u2028\u2029]/g, c => ({ '<': '\\u003c', '>': '\\u003e', '&': '\\u0026', '\u2028': '\\u2028', '\u2029': '\\u2029' }[c]));
}
function buildPublicInviteDocument(html, project, templateUrl, slug) {
    const base = templateUrl.replace(/&/g, '&amp;').replace(/"/g, '&quot;');
    const bootstrap = '<base href="' + base + '"><script>window.EA_PUBLIC_PROJECT=' + publicBootstrapJson(project) + ';window.EA_PUBLIC_SLUG=' + publicBootstrapJson(slug) + ';window.EA_RENDER_QUERY=' + publicBootstrapJson('?public=1&slug=' + encodeURIComponent(slug)) + ';<\/script>';
    if (!/<head(?:\s[^>]*)?>/i.test(html))
        throw new Error('This invitation renderer is unavailable.');
    return html.replace(/<head(?:\s[^>]*)?>/i, match => match + bootstrap);
}
function PublicInvite({ slug }) {
    const [documentHtml, setDocumentHtml] = React.useState('');
    const [frameTitle, setFrameTitle] = React.useState('A page shared with you');
    const [error, setError] = React.useState('');
    const [retry, setRetry] = React.useState(0);
    React.useEffect(() => {
        const previousTitle = document.title;
        return () => { document.title = previousTitle; };
    }, []);
    const showPageTitle = event => {
        try {
            const title = event.currentTarget.contentDocument?.title;
            if (typeof title === 'string')
                document.title = title;
        }
        catch (_) { }
    };
    React.useEffect(() => {
        let cancelled = false;
        const controller = new AbortController();
        const timer = setTimeout(() => controller.abort(), 25000);
        setDocumentHtml('');
        setError('');
        (async () => {
            try {
                if (!slug)
                    throw new Error('This link is incomplete.');
                const { project } = await window.EA.getPublicProject(slug);
                if (cancelled)
                    return;
                const template = TemplateCatalog.get(project?.template_id);
                if (!project?.id || !template || project.status !== 'published')
                    throw new Error('This page is not available. Please check the link with the person who shared it.');
                const renderer = window.EA_APP?.path ? window.EA_APP.path(template.builderTemplatePath) : template.builderTemplatePath;
                const url = new URL(renderer, window.location.origin);
                if (url.origin !== window.location.origin)
                    throw new Error('Invalid invitation renderer.');
                const response = await fetch(url.href, { signal: controller.signal, credentials: 'same-origin' });
                if (!response.ok)
                    throw new Error('The page could not be loaded. Please try again.');
                const html = await response.text();
                if (cancelled)
                    return;
                setFrameTitle(template.experienceType === 'apology' ? template.name + ' — a personal story' : 'Wedding invitation');
                setDocumentHtml(buildPublicInviteDocument(html, project, url.href, slug));
                window.EA.track(project.id, 'view', { slug, source: 'direct' });
            }
            catch (err) {
                if (!cancelled)
                    setError(err.name === 'AbortError' ? 'The page took too long to load. Please try again.' : err.message || 'Unable to open this page.');
            }
            finally {
                clearTimeout(timer);
            }
        })();
        return () => { cancelled = true; clearTimeout(timer); controller.abort(); };
    }, [slug, retry]);
    if (documentHtml)
        return React.createElement("iframe", { title: frameTitle, onLoad: showPageTitle, srcDoc: documentHtml, sandbox: "allow-scripts allow-same-origin allow-popups allow-popups-to-escape-sandbox allow-downloads allow-forms", referrerPolicy: "strict-origin-when-cross-origin", style: { position: 'fixed', inset: 0, width: '100%', height: '100%', border: 0, background: '#f8f3e9' } });
    return React.createElement("main", { className: "public-invite-state" },
        React.createElement("div", null,
            React.createElement("div", { className: "signin-logo" },
                React.createElement("span", { className: "logo-mark" }, "e"),
                React.createElement("span", null,
                    "Everafter ",
                    React.createElement("small", null, "by Makebiodata.shop"))),
            React.createElement("h1", { className: "serif" }, error ? 'This page couldn’t open' : 'Opening something made for you'),
            React.createElement("p", { role: error ? 'alert' : 'status' }, error || 'Your page will be here in a moment…'),
            error && React.createElement("button", { className: "btn btn-primary", onClick: () => setRetry(v => v + 1) }, "Try again")));
}
Object.assign(window, { PublicInvite, INVITE_CONFIG_KEYS });
