import "grapesjs";
const v = "app.grapesjs.com", P = "app-stage.grapesjs.com", f = [
  v,
  P,
  "localhost",
  "127.0.0.1",
  ".local-credentialless.webcontainer.io",
  // For stackblitz.com demos
  ".local.webcontainer.io",
  // For stackblitz.com demos
  "-sandpack.codesandbox.io"
  // For Sandpack demos
], k = "license:check:start", R = "license:check:end", U = () => typeof window < "u", x = ({ isDev: e, isStage: o }) => `${e ? "" : `https://${o ? P : v}`}/api`, I = () => {
  const e = U() && window.location.hostname;
  return !!e && (f.includes(e) || f.some((o) => e.endsWith(o)));
};
var g = /* @__PURE__ */ ((e) => (e.free = "free", e.startup = "startup", e.business = "business", e.enterprise = "enterprise", e))(g || {});
async function $({
  path: e,
  baseApiUrl: o,
  method: r = "GET",
  headers: n = {},
  params: l,
  body: c
}) {
  const t = `${o || x({ isDev: !1, isStage: !1 })}${e}`, i = {
    method: r,
    headers: {
      "Content-Type": "application/json",
      ...n
    }
  };
  c && (i.body = JSON.stringify(c));
  const a = l ? new URLSearchParams(l).toString() : "", s = a ? `?${a}` : "", u = await fetch(`${t}${s}`, i);
  if (!u.ok)
    throw new Error(`HTTP error! status: ${u.status}`);
  return u.json();
}
const T = {
  [g.free]: 0,
  [g.startup]: 10,
  [g.business]: 20,
  [g.enterprise]: 30
};
function O(e) {
  const o = e;
  return o.init = (r) => (n) => e(n, r), o;
}
const M = (e) => /* @__PURE__ */ O(e);
async function B({
  editor: e,
  plan: o,
  pluginName: r,
  licenseKey: n,
  cleanup: l
}) {
  let c = "", d = !1;
  const t = I(), i = (s) => {
    console.warn("Cleanup plugin:", r, "Reason:", s), l();
  }, a = (s = {}) => {
    var b;
    const { error: u, sdkLicense: y } = s, p = (b = s.plan) == null ? void 0 : b.category;
    if (!(y || s.license) || u)
      i(u || "Invalid license");
    else if (p) {
      const A = T[o], L = T[p];
      A > L && i({ pluginRequiredPlan: o, licensePlan: p });
    }
  };
  e.on(k, (s) => {
    c = s == null ? void 0 : s.baseApiUrl, d = !0;
  }), e.on(R, (s) => {
    a(s);
  }), setTimeout(async () => {
    if (!d) {
      if (t) return;
      if (n) {
        const s = await E({ licenseKey: n, pluginName: r, baseApiUrl: c });
        s && a(s);
      } else
        i("The `licenseKey` option not provided");
    }
  }, 2e3);
}
async function E(e) {
  const { licenseKey: o, pluginName: r, baseApiUrl: n } = e;
  try {
    return (await $({
      baseApiUrl: n,
      path: `/sdk/${o || "na"}`,
      method: "POST",
      params: {
        d: window.location.hostname,
        pn: r
      }
    })).result || {};
  } catch (l) {
    return console.error("Error during SDK license check:", l), !1;
  }
}
const j = (e) => {
  const o = {};
  for (const r of Object.keys(e)) {
    let n = e[r];
    n && (Array.isArray(n) ? n = n.map((l) => l.toString()).join(",") : n = n.toString(), o[r] = n);
  }
  return new URLSearchParams(o);
}, m = (e) => {
  const { apiKey: o, searchParams: r, thumbnailQuality: n = "high" } = e, l = (t = {}) => {
    const a = "https://www.googleapis.com/youtube/v3/search", s = j(t);
    return `${a}?${s}`;
  }, c = (t) => {
    var i, a, s;
    return ((i = t[n]) == null ? void 0 : i.url) || ((a = t.high) == null ? void 0 : a.url) || ((s = t.medium) == null ? void 0 : s.url) || t.default.url;
  }, d = (t) => {
    const i = c(t.snippet.thumbnails);
    return {
      id: t.id.videoId,
      src: `https://www.youtube.com/watch?v=${t.id.videoId}`,
      name: t.snippet.title,
      customData: { thumbnailUrl: i, videoItem: t }
    };
  };
  return {
    id: "youtube",
    types: ["youtube-video"],
    label: "YouTube Videos",
    search: { reloadOnInput: !0, debounceMs: 1e3 },
    async onLoad({ searchValue: t, pageCustomData: i }) {
      var b;
      const a = {
        maxResults: 25,
        q: t,
        pageToken: i == null ? void 0 : i.token,
        type: ["video"],
        key: o
      }, s = r == null ? void 0 : r({ searchValue: t }), u = {
        ...a,
        ...s
      };
      u.part ? u.part.includes("snippet") || u.part.push("snippet") : u.part = ["snippet"];
      const p = await (await fetch(l(u))).json();
      return (b = p.items) != null && b.length ? {
        items: p.items.map(d),
        nextPageCustomData: { token: p.nextPageToken },
        isLastPage: !p.nextPageToken
      } : { items: [], isLastPage: !0 };
    },
    itemLayout: ({ assetProps: t, onSelect: i }) => ({
      type: "column",
      onClick: () => i(t),
      htmlAttrs: {
        title: t.name
      },
      style: {
        border: "1px solid gray",
        borderRadius: 8,
        overflow: "hidden",
        cursor: "pointer"
      },
      children: [
        {
          type: "custom",
          render: () => {
            var a;
            return `<img src="${(a = t.customData) == null ? void 0 : a.thumbnailUrl}" alt="${t.name}" style="width: 100%; height: 100px; object-fit: cover">`;
          }
        },
        {
          type: "text",
          content: t.name,
          style: {
            overflow: "hidden",
            textOverflow: "ellipsis",
            whiteSpace: "nowrap",
            paddingLeft: 8,
            paddingRight: 8
          }
        }
      ]
    })
  };
};
var h = /* @__PURE__ */ ((e) => (e.toastAdd = "studio:toastAdd", e.dialogOpen = "studio:dialogOpen", e.dialogClose = "studio:dialogClose", e.sidebarLeftSet = "studio:sidebarLeft:set", e.sidebarLeftGet = "studio:sidebarLeft:get", e.sidebarLeftToggle = "studio:sidebarLeft:toggle", e.sidebarRightSet = "studio:sidebarRight:set", e.sidebarRightGet = "studio:sidebarRight:get", e.sidebarRightToggle = "studio:sidebarRight:toggle", e.sidebarTopSet = "studio:sidebarTop:set", e.sidebarTopGet = "studio:sidebarTop:get", e.sidebarTopToggle = "studio:sidebarTop:toggle", e.sidebarBottomSet = "studio:sidebarBottom:set", e.sidebarBottomGet = "studio:sidebarBottom:get", e.sidebarBottomToggle = "studio:sidebarBottom:toggle", e.symbolAdd = "studio:symbolAdd", e.symbolDetach = "studio:symbolDetach", e.symbolOverride = "studio:symbolOverride", e.symbolPropagateStyles = "studio:propagateStyles", e.getPagesConfig = "studio:getPagesConfig", e.setPagesConfig = "studio:setPagesConfig", e.getPageSettings = "studio:getPageSettings", e.setPageSettings = "studio:setPageSettings", e.projectFiles = "studio:projectFiles", e.canvasReload = "studio:canvasReload", e.getBlocksPanel = "studio:getBlocksPanel", e.setBlocksPanel = "studio:setBlocksPanel", e.getStateContextMenu = "studio:getStateContextMenu", e.setStateContextMenu = "studio:setStateContextMenu", e.contextMenuComponent = "studio:contextMenuComponent", e.layoutAdd = "studio:layoutAdd", e.layoutRemove = "studio:layoutRemove", e.layoutToggle = "studio:layoutToggle", e.getStateTheme = "studio:getStateTheme", e.setStateTheme = "studio:setStateTheme", e.assetProviderGet = "studio:assetProviderGet", e.assetProviderAdd = "studio:assetProviderAdd", e.assetProviderRemove = "studio:assetProviderRemove", e))(h || {});
const D = "youtubeAssetProvider", G = function(e, o) {
  const { skipVideoComponent: r } = o, n = m(o);
  e.runCommand(h.assetProviderAdd, { provider: n });
  const l = "search-on-youtube", c = "video";
  if (!r) {
    const d = e.Components.getType(c).model.prototype;
    e.Components.addType(c, {
      model: {
        getYoutubeTraits() {
          const [t, ...i] = d.getYoutubeTraits.apply(this);
          return [
            t,
            {
              id: l,
              type: "button",
              label: e.I18n.t("youtube.searchBtn"),
              command: () => {
                e.AssetManager.open({
                  select: (a) => {
                    e.Assets.close(), this.set({ videoId: a.attributes.id });
                  },
                  content: {
                    header: {
                      addUrl: !1,
                      upload: !1
                    }
                  }
                });
              }
            },
            ...i
          ];
        }
      }
    });
  }
  B({
    editor: e,
    licenseKey: o.licenseKey,
    plan: g.startup,
    pluginName: D,
    cleanup: () => {
      if (e.runCommand(h.assetProviderRemove, { id: n.id }), !r) {
        const d = e.Components.getType(c).model.prototype;
        e.Components.addType(c, {
          model: {
            getYoutubeTraits() {
              return d.getYoutubeTraits.apply(this).filter((t) => t.id !== l);
            }
          }
        });
      }
    }
  });
}, W = M(G);
export {
  W as default
};
