'use client'

import { useState } from 'react'
import { generateSlug } from '@/app/lib/slug'

interface ClickableHeadingProps {
    level: 1 | 2 | 3 | 4
    children: React.ReactNode
}

export function ClickableHeading({ level, children }: ClickableHeadingProps) {
    const [copied, setCopied] = useState(false)

    const text = typeof children === 'string' ? children : extractText(children)
    const id = generateSlug(text)

    const handleClick = async () => {
        const url = `${window.location.origin}${window.location.pathname}#${id}`
        await navigator.clipboard.writeText(url)
        setCopied(true)

        // Update URL without scrolling
        window.history.pushState({}, '', `#${id}`)

        setTimeout(() => setCopied(false), 2000)
    }

    const Tag = `h${level}` as keyof React.JSX.IntrinsicElements

    const baseClasses = "font-display font-semibold leading-tight tracking-tighter text-base-content group cursor-pointer hover:text-muted transition-colors relative scroll-mt-32"
    const levelClasses = {
        1: "text-3xl sm:text-4xl mb-8",
        2: "text-2xl sm:text-3xl mt-12 mb-4",
        3: "text-xl sm:text-2xl tracking-tight mt-8 mb-3",
        4: "text-lg sm:text-xl tracking-tight mt-6 mb-2"
    }

    return (
        <Tag
            id={id}
            className={`${baseClasses} ${levelClasses[level]}`}
            onClick={handleClick}
        >
            <span className="inline-flex items-center gap-2">
                {children}
                <span className="opacity-0 group-hover:opacity-100 transition-opacity text-muted">
                    {copied ? (
                        <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
                        </svg>
                    ) : (
                        <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13.828 10.172a4 4 0 00-5.656 0l-4 4a4 4 0 105.656 5.656l1.102-1.101m-.758-4.899a4 4 0 005.656 0l4-4a4 4 0 00-5.656-5.656l-1.1 1.1" />
                        </svg>
                    )}
                </span>
            </span>
        </Tag>
    )
}

function extractText(node: React.ReactNode): string {
    if (typeof node === 'string') return node
    if (typeof node === 'number') return String(node)
    if (Array.isArray(node)) return node.map(extractText).join('')
    if (node && typeof node === 'object' && 'props' in node) {
        return extractText((node as { props: { children: React.ReactNode } }).props.children)
    }
    return ''
}
