var __rest = (this && this.__rest) || function (s, e) {
  var t = {};
  for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
    t[p] = s[p];
  if (s != null && typeof Object.getOwnPropertySymbols === "function")
    for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
      if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
        t[p[i]] = s[p[i]];
    }
  return t;
};
import { h } from '@stencil/core';
import PrismicRichTextLib from 'prismic-richtext';
import PrismicHelpers from 'prismic-helpers';
import { href as routerHref } from 'stencil-router-v2';
import { createScript, embeds } from './embeds';
import { Heading, Paragraph } from '../../../core';
import { slugify } from '../../utils/slugify';
import { applyProps } from '../../../core/components/common';
let Poster;
let Leading;
let ParagraphLevel;
export function htmlSerializer(type, element, _content, children) {
  // give headings an ID
  switch (type) {
    case 'heading1':
    case 'heading2':
    case 'heading3':
    case 'heading4':
    case 'heading5':
    case 'heading6':
      const level = parseInt(type[type.length - 1], 10);
      const id = `h-${slugify(element.text)}`;
      return (h(Heading, Object.assign({}, { id, level, poster: Poster }), children));
    case 'paragraph':
      return h(Paragraph, Object.assign({}, { level: ParagraphLevel, leading: Leading }), children);
    case 'preformatted':
      return (h("pre", null,
        h("code", null, children)));
    // Return null to stick with the default behavior for all other elements
    default:
      return null;
  }
}
function slugifyHeading(children) {
  return children.reduce((id, c) => {
    return id + slugify(c[0]);
  }, '');
}
function serialize(linkResolver, elements, type, element, content, children, index, routerLink = false, router = null) {
  if (elements[type]) {
    return serializeElement(elements[type], type, element, content, children, index);
  }
  const Elements = PrismicRichTextLib.Elements;
  switch (type) {
    case Elements.heading1:
      return serializeStandardTag('h1', element, children, index, { id: slugifyHeading(children) });
    case Elements.heading2:
      return serializeStandardTag('h2', element, children, index, { id: slugifyHeading(children) });
    case Elements.heading3:
      return serializeStandardTag('h3', element, children, index, { id: slugifyHeading(children) });
    case Elements.heading4:
      return serializeStandardTag('h4', element, children, index, { id: slugifyHeading(children) });
    case Elements.heading5:
      return serializeStandardTag('h5', element, children, index, { id: slugifyHeading(children) });
    case Elements.heading6:
      return serializeStandardTag('h6', element, children, index, { id: slugifyHeading(children) });
    case Elements.paragraph:
      return serializeStandardTag('p', element, children, index);
    case Elements.preformatted:
      return serializeStandardTag('pre', element, children, index);
    case Elements.strong:
      return serializeStandardTag('strong', element, children, index);
    case Elements.em:
      return serializeStandardTag('em', element, children, index);
    case Elements.listItem:
      return serializeStandardTag('li', element, children, index);
    case Elements.oListItem:
      return serializeStandardTag('li', element, children, index);
    case Elements.list:
      return serializeStandardTag('ul', element, children, index);
    case Elements.oList:
      return serializeStandardTag('ol', element, children, index);
    case Elements.image:
      return serializeImage(linkResolver, element, index);
    case Elements.embed:
      return serializeEmbed(element, index);
    case Elements.hyperlink:
      return serializeHyperlink(linkResolver, element, children, index, routerLink, router);
    case Elements.label:
      return serializeLabel(element, children, index);
    case Elements.span:
      return serializeSpan(content);
    default:
      return null;
  }
}
function propsWithUniqueKey(props = {}, key) {
  return Object.assign(props, { key });
}
function serializeElement(Element, type, props, _content, children, index) {
  return (h(Element, Object.assign({ key: `element-${type}-${index + 1}` }, props, (type === 'image' ? { src: props.url, url: undefined } : null)), children && children.length ? children : undefined));
}
function serializeStandardTag(Tag, element, children, key, extra = {}) {
  const props = element.label ? Object.assign(extra, { className: element.label }) : extra;
  return h(Tag, Object.assign({}, propsWithUniqueKey(props, key)), children);
}
function serializeHyperlink(linkResolver, element, children, key, routerLink = false, router = null) {
  const targetAttr = element.data.target ? { target: element.data.target } : {};
  const relAttr = element.data.target ? { rel: 'noopener' } : {};
  let href = PrismicHelpers.Link.url(element.data, linkResolver);
  if (element.data.url) {
    const parsed = new URL(element.data.url);
    if (parsed.hostname.indexOf('.') < 0) {
      // Allow relative links
      href = `/${parsed.hostname}${parsed.pathname + parsed.search + parsed.hash}`;
    }
  }
  const props = Object.assign({ href }, targetAttr, relAttr);
  if (routerLink) {
    return h("a", Object.assign({}, propsWithUniqueKey(props, key), routerHref(props.href, router)), children);
  }
  else {
    return h("a", Object.assign({}, propsWithUniqueKey(props, key)), children);
  }
}
function serializeLabel(element, children, key) {
  const props = element.data ? Object.assign({}, { className: element.data.label }) : {};
  return h("span", Object.assign({}, propsWithUniqueKey(props, key)), children);
}
function serializeSpan(content) {
  if (content) {
    return content.split('\n').reduce((acc, p) => {
      if (acc.length === 0) {
        return [p];
      }
      else {
        const brIndex = (acc.length + 1) / 2 - 1;
        const br = h("br", Object.assign({}, propsWithUniqueKey({}, brIndex)));
        return acc.concat([br, p]);
      }
    }, []);
  }
  else {
    return null;
  }
}
function serializeImage(linkResolver, element, key) {
  const linkUrl = element.linkTo ? PrismicHelpers.Link.url(element.linkTo, linkResolver) : null;
  const linkTarget = element.linkTo && element.linkTo.target ? { target: element.linkTo.target } : {};
  const relAttr = linkTarget.target ? { rel: 'noopener' } : {};
  const img = h("img", { loading: 'lazy', src: element.url, alt: element.alt || '' });
  return (h("p", Object.assign({}, propsWithUniqueKey({ className: [element.label || '', 'block-img'].join(' ') }, key)), linkUrl ? h("a", Object.assign({}, Object.assign({ href: linkUrl }, linkTarget, relAttr)), img) : img));
}
function serializeEmbed(element, key) {
  if (embeds[element.oembed.provider_name]) {
    createScript(embeds[element.oembed.provider_name]);
  }
  const className = `embed embed-${element.oembed.provider_name.toLowerCase()}`;
  const props = Object.assign({
    'data-oembed': element.oembed.embed_url,
    'data-oembed-type': element.oembed.type,
    'data-oembed-provider': element.oembed.provider_name,
    ref: (ref) => {
      if (embeds[element.oembed.provider_name]) {
        embeds[element.oembed.provider_name].load(ref);
      }
    },
  }, element.label ? { className: `${className} ${element.label}` } : { className });
  const embedHtml = h("div", { innerHTML: element.oembed.html });
  return h("div", Object.assign({}, propsWithUniqueKey(props, key)), embedHtml);
}
export const asText = (structuredText) => PrismicRichTextLib.asText(structuredText, null);
const PrismicRichText = (_a, _, utils) => {
  var { richText, linkResolver, htmlSerializerProp = htmlSerializer, routerLink, router, paragraphLevel, poster, leading } = _a, props = __rest(_a, ["richText", "linkResolver", "htmlSerializerProp", "routerLink", "router", "paragraphLevel", "poster", "leading"]);
  // I hate doing this with closure shenanigans, but there aren't many good ways
  // to pass data through the Prismic library's serialize function to the custom
  // serializer ~pg
  ParagraphLevel = paragraphLevel > 0 && paragraphLevel < 7 ? paragraphLevel : undefined;
  Poster = poster;
  Leading = leading;
  const serializedChildren = PrismicRichTextLib.serialize(richText, (...args) => serialize.apply(null, [linkResolver, {}, ...args, routerLink, router]), 
  // serialize.bind(null, linkResolver, {}), 
  htmlSerializerProp);
  return utils.map(serializedChildren, Child => {
    Child.vattrs = applyProps(props, Child.vattrs);
    return Child;
  });
};
export { PrismicRichText };
