'use client'

import { useEffect } from 'react'

/**
 * Hook to add copy buttons to rehype-pretty-code figures
 * This enhances static code blocks with interactive copy functionality
 */
export function useCodeCopy(containerRef: React.RefObject<HTMLElement | null>, deps: unknown[] = []) {
  useEffect(() => {
    if (!containerRef.current) return
    
    // Small delay to ensure content is rendered
    const timeoutId = setTimeout(() => {
      if (!containerRef.current) return

      const figures = containerRef.current.querySelectorAll('[data-rehype-pretty-code-figure]')
      
      figures.forEach((figure) => {
        // Skip if already has a copy button
        if (figure.querySelector('.code-copy-button')) return
        
        const title = figure.querySelector('[data-rehype-pretty-code-title]')
        const pre = figure.querySelector('pre')
        const code = pre?.querySelector('code')
        
        if (!pre || !code) return
        
        // Create copy button
        const button = document.createElement('button')
        button.type = 'button'
        button.className = 'code-copy-button'
        button.title = 'Copy code'
        button.innerHTML = `
          <svg class="copy-icon" xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" viewBox="0 0 256 256">
            <path d="M216,32H88a8,8,0,0,0-8,8V80H40a8,8,0,0,0-8,8V216a8,8,0,0,0,8,8H168a8,8,0,0,0,8-8V176h40a8,8,0,0,0,8-8V40A8,8,0,0,0,216,32ZM160,208H48V96H160Zm48-48H176V88a8,8,0,0,0-8-8H96V48H208Z"></path>
          </svg>
          <svg class="check-icon" xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" viewBox="0 0 256 256" style="display:none;">
            <path d="M229.66,77.66l-128,128a8,8,0,0,1-11.32,0l-56-56a8,8,0,0,1,11.32-11.32L96,188.69,218.34,66.34a8,8,0,0,1,11.32,11.32Z"></path>
          </svg>
        `
        
        button.addEventListener('click', async () => {
          const text = code.textContent || ''
          try {
            await navigator.clipboard.writeText(text)
            
            // Show check icon
            const copyIcon = button.querySelector('.copy-icon') as HTMLElement
            const checkIcon = button.querySelector('.check-icon') as HTMLElement
            if (copyIcon && checkIcon) {
              copyIcon.style.display = 'none'
              checkIcon.style.display = 'block'
              checkIcon.style.color = 'rgb(16, 185, 129)'
              
              setTimeout(() => {
                copyIcon.style.display = 'block'
                checkIcon.style.display = 'none'
              }, 2000)
            }
          } catch (err) {
            console.error('Failed to copy:', err)
          }
        })
        
        // If there's a title, add button to header area
        if (title) {
          // Create a wrapper for the header content
          const headerWrapper = document.createElement('div')
          headerWrapper.className = 'code-header-wrapper'
          
          // Move title into wrapper
          title.parentNode?.insertBefore(headerWrapper, title)
          headerWrapper.appendChild(title)
          headerWrapper.appendChild(button)
        } else {
          // For code blocks without title, add button to pre
          pre.style.position = 'relative'
          button.classList.add('code-copy-button-floating')
          pre.appendChild(button)
        }
      })
    }, 100)
    
    return () => clearTimeout(timeoutId)
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [containerRef, ...deps])
}
