import{Uri}from"../core/uri.js";import{fload,igload}from"./login.js";const regexScript=/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,fbClientAccessToken=function(){const e=document.querySelector('meta[name="fb-client-access-token"]');return e&&e.getAttribute("content")||""}();export const initOEmbed=async(e,r,t)=>{if(!r)return;const o=Uri.from(r);let a,n=()=>{};if(o.queryParams.width=String(e.clientWidth),o.queryParams.maxwidth=String(e.clientWidth),o.host&&(o.host.includes("facebook")||o.host.includes("instagr"))&&(o.queryParams.access_token=fbClientAccessToken,o.queryParams.omitscript="true"),"string"==typeof o.queryParams.url&&-1!==o.queryParams.url.search(/instagr\.?am/)?n=()=>{igload().then((()=>{window.instgrm.Embeds.process()}))}:"string"==typeof o.queryParams.url&&-1!==o.queryParams.url.search(/facebook/)&&(n=e=>{fload().then((r=>{r.XFBML.parse(e)}))}),t){const e=`jsonp_${Date.now()}_${Math.round(1e4*Math.random())}`;o.queryParams.callback=e,o.queryParams.jsoncallback=e,a=await new Promise(((r,t)=>{window[e]=r;const a=document.createElement("script");a.async=!0,a.onerror=t,a.src=o.href,document.head.appendChild(a)})),"string"==typeof a.html&&-1===a.html.indexOf("<script")&&(a.html=a.html.replace(regexScript,""))}else{const e=await fetch(o.href);if(!e.ok)return void console.error(`failed to load oembed data from ${o.href}`);a=await e.json()}a&&a.html?(e.innerHTML=a.html,n(e)):console.error(`got invalid oembed data from ${o.href}`)};
