import { useCallback, useRef, useEffect } from 'react'
import { useLocation } from 'react-router-dom'
import 'artalk/dist/Artalk.css'
import Artalk from 'artalk'

interface CommentsProps {
  title?: string;
}

const Comments = ({ title }: CommentsProps) => {
  const { pathname } = useLocation()
  const artalkRef = useRef<Artalk>()
  const containerRef = useRef<HTMLDivElement>(null)

  useEffect(() => {
    if (!containerRef.current) return

    // Clean up previous instance
    if (artalkRef.current) {
      artalkRef.current.destroy()
      artalkRef.current = undefined
    }

    // Initialize new instance
    artalkRef.current = Artalk.init({
      el: containerRef.current,
      pageKey: pathname,
      pageTitle: title || document.title,
      server: 'https://comments.owu.one',
      site: 'STARSET Mirror Homepage',
      darkMode: document.documentElement.classList.contains('dark'),
      useBackendConf: true,
      pagination: {
        pageSize: 15,
        readMore: true,
      },
      emoticons: true,
    })

    // Handle dark mode changes
    const observer = new MutationObserver((mutations) => {
      mutations.forEach((mutation) => {
        if (mutation.attributeName === 'class') {
          const isDark = document.documentElement.classList.contains('dark')
          artalkRef.current?.setDarkMode(isDark)
        }
      })
    })

    observer.observe(document.documentElement, {
      attributes: true,
      attributeFilter: ['class'],
    })

    return () => {
      observer.disconnect()
      artalkRef.current?.destroy()
    }
  }, [pathname, title])

  return (
    <div 
      ref={containerRef}
      className="mt-12 p-4 bg-white dark:bg-gray-800 rounded-lg shadow"
      aria-label="Comments section"
      role="complementary"
    />
  )
}

export default Comments
