import { useRouter } from 'next/router';
import { NextSeo } from 'next-seo';

const Seo = (props) => {
  const router = useRouter();

  const {
    canonical,
    description,
    additionalMetaTags = [],
    openGraph = {},
    ...restProps
  } = props;

  const origin = (process.env.NEXT_PUBLIC_SELF_HOST || '').replace(/\/+$/, '');

  const asPath = router.asPath || '';

  const [cleanPath] = asPath.split('?');

  const queryObj = router.query || {};

  const isSearchPage = cleanPath.startsWith('/search');

  const buildFallbackCanonical = () => {
    if (isSearchPage) {
      const q = queryObj.q;
      if (q) {
        return origin + cleanPath + `?q=${encodeURIComponent(String(q))}`;
      }
      return origin + cleanPath;
    }

    return origin + cleanPath;
  };

  const resolvedCanonical = canonical || buildFallbackCanonical();

  const mergedAdditionalMetaTags = [
    {
      property: 'fb:app_id',
      content: '270830718811',
    },
    {
      property: 'fb:page_id',
      content: '101759953569',
    },
    ...additionalMetaTags,
  ];

  return (
    <NextSeo
      defaultTitle='Indoteknik.com: B2B Industrial Supply & Solution'
      canonical={resolvedCanonical}
      description={description}
      {...restProps}
      openGraph={{
        siteName: 'Indoteknik.com',
        ...openGraph,
      }}
      additionalMetaTags={mergedAdditionalMetaTags}
    />
  );
};

export default Seo;
