'use client'

import React, {useEffect, useState} from "react"
import clsx from "clsx"

import styles from './CookieConfirm.module.sass'
import {BlueButton} from "@/components/BlueButton/BlueButton";
import OutLink from "@/components/Link/OutLink";
import {useCookies} from "react-cookie";
import Script from "next/script";

const COOKIE_KEY = 'allow_cookie'

export interface IProps extends React.ComponentPropsWithoutRef<'div'> {

}

export const CookieConfirm: React.FC<IProps> = (props) => {
  const {children, className, ...rest} = props
  const [show, setShow] = useState(false)
  const [cookies, setCookie, removeCookie] = useCookies([COOKIE_KEY])
  useEffect(() => {
    setShow(cookies.allow_cookie == null)
  }, [cookies.allow_cookie]);
  const handleClickClose = () => {
    setShow(false)
  }
  const handleClickAgree = () => {
    setShow(false)
    setCookie(COOKIE_KEY, Date.now())
  }
  return (
    <>
      <div className={clsx(className, styles.container)} style={{display: show ? 'unset' : 'none'}} {...rest}>
        <div className={styles.close_container}>
          <div className={styles.close} onClick={handleClickClose}>
            {/*<img src={closeIconSvg} alt="Close"/>*/}
          </div>
        </div>
        <div className={styles.main}>
          <div className={styles.start}>
            <div className={styles.title}>
              Cookie 使用策略
            </div>
            <div className={styles.content}>
              本网站使用 Cookie 来为您提供个性化的浏览体验，以及分析网站流量。如果您点击“同意”或继续浏览本网站，即表示您同意我们使用 Cookie。
              <br/>
              您可以阅读我们的 <OutLink href="/privacy-policy">隐私政策</OutLink> 和 <OutLink href="/cookie-policy">Cookie 政策</OutLink> ，以了解更多信息。
            </div>
          </div>
          <div className={styles.end}>
            <BlueButton onClick={handleClickAgree}>同意</BlueButton>
          </div>
        </div>
      </div>
      {cookies.allow_cookie && (
        <Script id={'baidutongji'} dangerouslySetInnerHTML={{__html: `
var _hmt = _hmt || [];
(function() {
  var hm = document.createElement("script");
  hm.src = "https://hm.baidu.com/hm.js?850c6a30b89fa0cbb6577c9c3fb1ac57";
  var s = document.getElementsByTagName("script")[0]; 
  s.parentNode.insertBefore(hm, s);
})();
        `}} />
      )}
    </>
  )
}
