import { useState, useEffect } from 'react'
import { Link } from 'react-router-dom'
import './CookieConsent.css'

function CookieConsent() {
  const [showConsent, setShowConsent] = useState(false)

  useEffect(() => {
    // 检查用户是否已经做出过选择
    try {
      const consent = localStorage.getItem('cookieConsent')
      console.log('[CookieConsent] Checking localStorage, consent =', consent)
      
      if (!consent) {
        console.log('[CookieConsent] No consent found, will show after delay')
        // 延迟显示，让页面先加载完成
        const timer = setTimeout(() => {
          console.log('[CookieConsent] Setting showConsent to true')
          setShowConsent(true)
        }, 1000) // 减少延迟时间到1秒
        return () => {
          console.log('[CookieConsent] Cleaning up timer')
          clearTimeout(timer)
        }
      } else {
        console.log('[CookieConsent] Consent already given, not showing. To test, clear localStorage: localStorage.removeItem("cookieConsent")')
      }
    } catch (error) {
      console.error('[CookieConsent] Error accessing localStorage:', error)
      // 如果localStorage不可用，仍然显示
      const timer = setTimeout(() => {
        setShowConsent(true)
      }, 1000)
      return () => clearTimeout(timer)
    }
  }, [])

  const handleAccept = () => {
    console.log('CookieConsent: User accepted')
    localStorage.setItem('cookieConsent', 'accepted')
    setShowConsent(false)
  }

  const handleReject = () => {
    console.log('CookieConsent: User rejected')
    localStorage.setItem('cookieConsent', 'rejected')
    setShowConsent(false)
  }

  console.log('CookieConsent: Rendering, showConsent =', showConsent)

  if (!showConsent) {
    return null
  }

  return (
    <div className="cookie-consent-overlay">
      <div className="cookie-consent">
        <div className="cookie-consent-content">
          <h3 className="cookie-consent-title">Cookies</h3>
          <p className="cookie-consent-text">
            本网站使用 Cookies 以使您获得最佳的体验。为了继续浏览本网站，您需同意我们对 Cookies 的使用。想要了解更多有关于 Cookies 的信息，或不希望当您使用网站时出现 Cookies，请阅读我们的 <Link to="/privacy-policy" className="cookie-link">Cookies 声明</Link>。
          </p>
        </div>
        <div className="cookie-consent-actions">
          <button onClick={handleReject} className="cookie-btn cookie-btn-reject">
            拒绝
          </button>
          <button onClick={handleAccept} className="cookie-btn cookie-btn-accept">
            接受
          </button>
        </div>
      </div>
    </div>
  )
}

export default CookieConsent
