/** @jsx jsx */

import { Children } from 'react';
import uniqBy from 'lodash.uniqby';
import getConfig from 'next/config';
import Head from 'next/head';
import { jsx } from '@emotion/core';

const {
  publicRuntimeConfig: { meetup },
} = getConfig();

export const makeMetaUrl = path => {
  const base = meetup.siteUrl;
  const url = base.endsWith('/') ? base.slice(0, base.length - 1) : base;
  return `${url}${path}`;
};

const logoPath = makeMetaUrl(meetup.logo.src);

const rootTags = [
  <meta dismiss property="og:url" content={meetup.siteUrl} />,
  <meta dismiss property="og:type" content="website" />,
  <meta dismiss property="og:locale" content="en" />,
  <meta dismiss property="og:site_name" content={meetup.name} />,
  <meta dismiss property="og:image" content={logoPath} />,
  <meta dismiss property="og:image:width" content={meetup.logo.width} />,
  <meta dismiss property="og:image:height" content={meetup.logo.height} />,
  <meta dismiss name="twitter:site" content={meetup.twitterHandle} />,
  <meta dismiss name="twitter:card" content="summary" />,
  <meta dismiss name="twitter:image" content={logoPath} />,
];

function getUniqueTags(children) {
  // NOTE: the concatenation order is important for the unique filter;
  // we want to give `children` precedence over root tags.
  const tags = Children.toArray(children.concat(rootTags));
  const uniqueTags = uniqBy(tags, t => t.props.name || t.props.property);
  return uniqueTags.map((tag, idx) => <tag.type key={tag.key || idx} {...tag.props} />);
}

export default function PageMeta({ children, description, title, titleExclusive }) {
  const titleContent = titleExclusive ? titleExclusive : title ? `${title} | ${meetup.name}` : null;
  const uniqueTags = children ? getUniqueTags(children) : rootTags;

  return (
    <Head>
      {titleContent && <title>{titleContent}</title>}
      {description && <meta name="description" content={description} />}
      {uniqueTags}
    </Head>
  );
}

@@ -489,32 +489,24 @@
 = %5B%0A  %3Cmeta 
-dismiss 
 property=%22og
@@ -544,32 +544,24 @@
 /%3E,%0A  %3Cmeta 
-dismiss 
 property=%22og
@@ -593,32 +593,24 @@
 /%3E,%0A  %3Cmeta 
-dismiss 
 property=%22og
@@ -639,32 +639,24 @@
 /%3E,%0A  %3Cmeta 
-dismiss 
 property=%22og
@@ -697,32 +697,24 @@
 /%3E,%0A  %3Cmeta 
-dismiss 
 property=%22og
@@ -748,32 +748,24 @@
 /%3E,%0A  %3Cmeta 
-dismiss 
 property=%22og
@@ -818,24 +818,16 @@
   %3Cmeta 
-dismiss 
 property
@@ -882,32 +882,24 @@
 /%3E,%0A  %3Cmeta 
-dismiss 
 name=%22twitte
@@ -945,32 +945,24 @@
 /%3E,%0A  %3Cmeta 
-dismiss 
 name=%22twitte
@@ -1003,16 +1003,8 @@
 eta 
-dismiss 
 name

remove unused prop