//WORDPRESS

//import MorePosts from 'components/Posts/MorePosts'
import parser from 'html-react-parser'
import Link from 'next/link'
import { useEffect, useState } from 'react'
import { NextSeo } from 'next-seo'
import { format } from 'date-fns'
import PortableText from 'react-portable-text'
import { IoCalendarOutline, IoFolderOutline } from 'react-icons/io5'

import { getImageLink } from '../../lib/wordpress.image'
import { OpenGlobalEvent } from 'lib/popupimage'

import Container from 'components/BlogContainer'
import Layout from 'components/Layout'

export default function PostWordpress(props) {
  const { loading, post, preview } = props
  const [contentHtml, contentHtmlSet] = useState('')
  const [evenGlobal, eventGlobalSet] = useState(false)
  //console.log('post contetn', post)
  //const featImgUrl = post.featured_media
  const featImgUrl = getImageLink(
    post._embedded['wp:featuredmedia'],
    post.featured_media
  )
  const contentPost = parser(contentHtml)
  //console.log("content: ", contentPost)

  useEffect(() => {
    let popupimage = function () {
      //alert('whoe')
    }

    let searchImage = function (docu) {
      let imgc = []
      let caption = []
      ;(function sc(doc) {
        if (doc.tagName != 'IMG') {
          if (Array.from(doc.children).length > 0) {
            Array.from(doc.children).forEach(function (e) {
              sc(e)
            })
          }
        } else {
          if (doc.src) {
            imgc.push(doc.src)
          } else {
            caption.push(doc.innerHTML)
          }
        }
      })(docu)

      let nh = ''
      let num = 0
      imgc.forEach(function (l, i) {
        num++
        nh += `
          <div class="relative flex" style="overflow:hidden; height: auto;">
            <div>
              <img class="popup-image" style="width: 100%;" src="${l}" />
              ${(function () {
                if (caption[i]) {
                  //console.log(caption[i])
                  return `<p class="text-center text-sm pt-5 italic text-stone-600 leading-loose font-sans mb-3">${caption[i]}</p>`
                }
                return ``
              })()}
            </div>
          </div>
          `
      })
      return {
        count: num,
        html: nh,
      }
    }

    let docWp = document.createElement('div')
    docWp.innerHTML = post.content.rendered
    //console.log(docWp)
    let newHtml = ''
    Array.from(docWp.children).forEach(function (content) {
      if (
        content.tagName === 'H2' ||
        content.tagName === 'H1' ||
        content.tagName === 'H3' ||
        content.tagName === 'H4' ||
        content.tagName === 'H5' ||
        content.tagName === 'H6'
      ) {
        content.className = 'text-stone-600 leading-loose font-sans mb-3'
        newHtml += content.outerHTML
      }

      if (content.tagName === 'DIV') {
        content.className = 'text-stone-600 leading-loose font-sans mb-3'
        newHtml += content.outerHTML
      }

      if (content.tagName === 'P') {
        content.className = 'text-stone-600 leading-loose font-sans mb-3'
        newHtml += content.outerHTML
      }

      if (content.tagName === 'FIGURE') {
        let imgContainer = searchImage(content)
        let num = 3
        if (imgContainer.count < 3) {
          num = imgContainer.count
        }

        newHtml += `
        <div class="my-10" style="cursor:pointer; display:grid;grid-gap:10px;width: calc(100% - ${num}0px);grid-template-columns: calc(100% /${num}) calc(100% /${num}) calc(100% /${num})  ">
              ${imgContainer.html}
          </div>
        `
      }
    })

    document.body.addEventListener('click', OpenGlobalEvent, false)

    contentHtmlSet(newHtml)

    return function cleanup() {
      window.removeEventListener('click', OpenGlobalEvent)
    }
  }, [contentHtml, post.content.rendered, evenGlobal])

  const excerpt = post.excerpt.rendered.replace(/(<([^>]+)>)/gi, '')

  return (
    <Layout preview={preview} loading={loading}>
      <NextSeo
        title={post.title.rendered}
        //description = `${post.excerpt.rendered}.replace(/(<([^>]+)>)/gi, '')`
        description={excerpt}
        additionalLinkTags={[
          {
            rel: 'icon',
            href: '../favicon/favicon.ico',
          },
        ]}
        openGraph={{
          title: `${post.title.rendered}`,
          description: `${excerpt}`,
          url: 'https://www.gwkbali.com/monthly-release/' + `${post.slug}`,
          type: 'article',
          article: {
            publishedTime: `${post.date}`,
            // modifiedTime: '2018-01-21T18:04:43Z',
            // expirationTime: '2022-12-21T22:04:11Z',
            section: 'Monthly Release',
            // authors: [
            //   'https://www.example.com/authors/@firstnameA-lastnameA',
            //   'https://www.example.com/authors/@firstnameB-lastnameB',
            // ],
            // tags: ['Tag A', 'Tag B', 'Tag C'],
          },
          images: [
            {
              url: featImgUrl,
              width: 850,
              height: 650,
              alt: `${post.title.rendered}`,
            },
          ],
        }}
      />
      <div
        className="block min-h-[300px] w-full bg-stone-600 md:relative md:min-h-[500px]"
        style={{
          backgroundImage: 'url(' + featImgUrl + ')',
          backgroundSize: 'cover',
          backgroundPosition: 'center center',
          backgroundRepeat: 'no-repeat',
          backgroundAttachment: 'fixed',
        }}
      >
        <div className="lg:bottom:0 absolute block min-h-[300px] w-full bg-gradient-to-t from-stone-900 sm:bg-gradient-to-t sm:from-stone-900 md:absolute md:bottom-0 md:min-h-screen md:from-stone-900">
          <Container>
            <div className="absolute left-0 top-16 h-auto px-10 py-0 sm:top-[300px] md:mb-0 md:grid md:grid-cols-3 md:gap-10 ">
              <div className="relative col-span-3 animate-fade-up items-center p-0 align-middle animate-duration-[1200ms] animate-once sm:p-0 md:col-span-3 md:px-52 md:py-10 md:align-middle">
                <h1
                  className="pb-5 text-left text-3xl font-bold leading-normal text-stone-50 sm:text-center sm:text-3xl md:text-3xl xl:text-6xl"
                  dangerouslySetInnerHTML={{ __html: post.title.rendered }}
                />
              </div>
            </div>
          </Container>
        </div>
      </div>
      <Container>
        <div className="mx-auto mb-0 w-full px-5 py-10 sm:max-w-[80%]">
          <div className="md:col-span-2">
            <div className="mt-0">
              <div className="pb-3">
                <Link href="/media-corner/page/1">
                  <span className="inline-flex items-center pb-5 pr-5 font-sans text-sm text-yellow-600 hover:text-stone-600">
                    <IoFolderOutline />
                    &nbsp;News & Media
                  </span>
                </Link>
                <span className="inline-flex items-center pb-5 pr-5 font-sans text-sm text-stone-600">
                  <IoCalendarOutline />
                  &nbsp;{format(new Date(post.date), 'dd-MM-yyyy')}
                </span>
                <hr className="" />
                <div>{parser(contentHtml)}</div>
              </div>
            </div>
          </div>
          {/* <div className=""></div> */}
        </div>

        <div className="mb-5 mt-5">{/* <MorePosts /> */}</div>
      </Container>
    </Layout>
  )
}
export async function getStaticProps(data) {
  const post = await fetch(
    `https://cmswp.gwkbali.com/wp-json/wp/v2/mediacorner?slug=${
      data?.params.slug || ''
    }&_embed`
  ).then((res) => res.json())

  return {
    props: {
      post: post[0],
    },
  }
}
export async function getStaticPaths() {
  const slugs = await fetch(
    'https://cmswp.gwkbali.com/wp-json/wp/v2/mediacorner?_fields=slug&per_page=99'
  ).then((res) => res.json())

  const paths = slugs?.map(({ slug }) => `/media-corner/${slug}`) || []

  return {
    paths,
    fallback: false,
  }
}
