/* global window */
(function () {
  if (typeof window === "undefined") {
    return;
  }

  var SNAKE_ATTR_MAP = {
    showPrice: "show_price",
    showBrand: "show_brand",
    showDescription: "show_description",
    showProviderBadge: "show_provider_badge",
    showDisclaimer: "show_disclaimer",
    openInNewTab: "open_in_new_tab",
    trackingEnabled: "tracking_enabled",
    buttonLabels: "button_labels",
    customButtons: "custom_buttons",
    templateVariant: "template_variant",
    buttonLayout: "button_layout",
    buttonShape: "button_shape",
    buttonTone: "button_tone",
    microcopyText: "microcopy_text",
    microcopyStartAt: "microcopy_start_at",
    microcopyEndAt: "microcopy_end_at",
    abTestingEnabled: "ab_testing_enabled",
    abButtonLabelVariant: "ab_button_label_variant",
    abMicrocopyVariant: "ab_microcopy_variant",
    customCssClass: "custom_css_class",
    itemTemplate: "item_template",
  };

  function clonePlainObject(value) {
    var out = {};
    if (!value || typeof value !== "object" || Array.isArray(value)) {
      return out;
    }
    Object.keys(value).forEach(function (key) {
      out[key] = value[key];
    });
    return out;
  }

  function withLegacySnakeAttrs(attributes) {
    var out = clonePlainObject(attributes);
    Object.keys(SNAKE_ATTR_MAP).forEach(function (camelKey) {
      if (Object.prototype.hasOwnProperty.call(out, camelKey)) {
        out[SNAKE_ATTR_MAP[camelKey]] = out[camelKey];
      }
    });
    return out;
  }

  function parsePreviewHtml(response) {
    if (
      response &&
      response.data &&
      typeof response.data.html === "string" &&
      response.data.html !== ""
    ) {
      return response.data.html;
    }
    if (response && typeof response.html === "string" && response.html !== "") {
      return response.html;
    }
    return null;
  }

  function buildSinglePayload(options) {
    var id = options && options.id ? String(options.id) : "";
    var template =
      options && typeof options.template === "string" && options.template !== ""
        ? options.template
        : "single-default-card";
    return {
      kind: "single",
      productIds: [id],
      template: template,
      attrs: withLegacySnakeAttrs(options ? options.attributes : null),
    };
  }

  function requestSingleProductPreview(options) {
    var apiFetch = options && options.apiFetch;
    if (typeof apiFetch !== "function") {
      return Promise.reject(new Error("wp.apiFetch is unavailable."));
    }
    var payload = buildSinglePayload(options || {});
    if (!payload.productIds[0]) {
      return Promise.reject(new Error("Product id is required."));
    }
    return apiFetch({
      path: "/affilun/v1/editor/preview",
      method: "POST",
      data: payload,
    }).then(function (response) {
      var html = parsePreviewHtml(response);
      if (html === null) {
        throw new Error("Preview HTML is empty.");
      }
      return html;
    });
  }

  window.affilunEditorPreview = {
    buildSinglePayload: buildSinglePayload,
    requestSingleProductPreview: requestSingleProductPreview,
    withLegacySnakeAttrs: withLegacySnakeAttrs,
    parsePreviewHtml: parsePreviewHtml,
  };
})();
