import React from 'react';
import { render, cleanup, waitFor } from '@testing-library/react';
import '@testing-library/jest-dom/extend-expect';

import Head, { getLanguage, getCanonicalUrl, getRobotOptions } from '.';

describe('Head Component', () => {
  test('getLanguage()', () => {
    expect(getLanguage('str')).toEqual('str');
    expect(getLanguage('')).toEqual('en');
    expect(getLanguage('no')).toEqual('nb-NO');
  });

  test('getCanonicalUrl()', () => {
    expect(getCanonicalUrl({ path: '/' })).toEqual(process.env.GATSBY_SITE_URL);
    expect(getCanonicalUrl({ path: 'sdsdasdsajkdhjkashk' })).toEqual(
      `${process.env.GATSBY_SITE_URL}sdsdasdsajkdhjkashk`
    );
    expect(getCanonicalUrl({ path: 'about', canonical_url: 'contact' })).toEqual(
      `${process.env.GATSBY_SITE_URL}contact`
    );
  });

  test('getRobotOptions()', () => {
    const arrOne = {
      page_index: 0,
      links_followed: 0,
      images_index: 0,
      show_snippet: 0,
    };
    expect(getRobotOptions(arrOne)).toEqual('noindex,nofollow,noimageindex,nosnippet');
    arrOne.page_index = 1;
    arrOne.show_snippet = 1;
    expect(getRobotOptions(arrOne)).toEqual('nofollow,noimageindex');
  });

  test('render with props', async () => {
    const { container } = render(
      <Head
        siteInfo={{
          site_name: 'test',
          site_logo: '#',
        }}
        page={{
          meta_title: 'my meta title',
          language: 'en',
          meta_description: 'my meta description',
          meta_robots: ['one', 'two', 'three'],
          path: 'my path',
          preconnect_links: ['1', '2', '3'],
          seo_json_schema: [],
          sections: { main: {} },
        }}
      />
    );
    expect(container).toBeTruthy();
    await waitFor(() => {
      expect(document.title).toEqual('my meta title');
      // expect(document.documentElement.lang).toEqual('en');
      expect(document.querySelectorAll('link[rel=preconnect]')).toHaveLength(3);
      expect(document.getElementsByTagName('meta')[0].getAttribute('content')).toEqual(
        'my meta description'
      );
      expect(document.getElementsByTagName('meta')[1].getAttribute('content')).toEqual(
        'one,two,three'
      );

      expect(document.querySelector("meta[name='og:title']").getAttribute('content')).toEqual(
        'my meta title'
      );
      // expect(document.querySelector('meta[name=og:site_name]').getAttribute('content')).toEqual(
      //   'test'
      // );
    });
  });
});
afterEach(() => {
  cleanup();
});
