
interface LinkCardProps {
    title?: string
    description?: string
    url: string
    image?: string
}

async function fetchOGMetadata(url: string) {
    try {
        const response = await fetch(url, {
            next: { revalidate: 86400 }, // Cache for 24 hours
            headers: {
                'User-Agent': 'Mozilla/5.0 (compatible; Standard.site/1.0; +https://standard.site)'
            }
        })

        if (!response.ok) {
            console.warn(`Failed to fetch ${url}: ${response.status}`)
            return null
        }

        const html = await response.text()
        const urlObj = new URL(url)

        // Extract OG metadata - try both property and name attributes
        let ogImage =
            html.match(/<meta[^>]*property=["']og:image["'][^>]*content=["']([^"']*)["']/i)?.[1] ||
            html.match(/<meta[^>]*content=["']([^"']*)["'][^>]*property=["']og:image["']/i)?.[1]

        const ogTitle =
            html.match(/<meta[^>]*property=["']og:title["'][^>]*content=["']([^"']*)["']/i)?.[1] ||
            html.match(/<meta[^>]*content=["']([^"']*)["'][^>]*property=["']og:title["']/i)?.[1]

        const ogDescription =
            html.match(/<meta[^>]*property=["']og:description["'][^>]*content=["']([^"']*)["']/i)?.[1] ||
            html.match(/<meta[^>]*content=["']([^"']*)["'][^>]*property=["']og:description["']/i)?.[1]

        // Resolve relative image URLs to absolute
        if (ogImage && !ogImage.startsWith('http')) {
            if (ogImage.startsWith('//')) {
                ogImage = `${urlObj.protocol}${ogImage}`
            } else if (ogImage.startsWith('/')) {
                ogImage = `${urlObj.protocol}//${urlObj.host}${ogImage}`
            } else {
                ogImage = `${urlObj.protocol}//${urlObj.host}/${ogImage}`
            }
        }

        return {
            image: ogImage || null,
            title: ogTitle || null,
            description: ogDescription || null
        }
    } catch (error) {
        console.error('Failed to fetch OG metadata from', url, error)
        return null
    }
}

export async function LinkCard({ title, description, url, image }: LinkCardProps) {
    const urlObj = new URL(url)
    const hostname = urlObj.hostname.replace('www.', '')

    // Fetch OG metadata if not provided
    const metadata = await fetchOGMetadata(url)

    const finalTitle = title || metadata?.title || hostname
    const finalDescription = description || metadata?.description || ''
    const finalImage = image || metadata?.image

    urlObj.searchParams.set('utm_source', 'standard.site')
    urlObj.searchParams.set('utm_medium', 'docs')
    urlObj.searchParams.set('utm_campaign', 'implementations')

    return (
        <a
            href={urlObj.toString()}
            target="_blank"
            rel="noopener noreferrer"
            className="group flex rounded-2xl border border-border bg-linear-to-br from-base-200/50 to-base-200 transition-all hover:border-border/60 hover:shadow-lg not-prose mb-4"
        >
            <div className="flex min-w-0 flex-1 flex-col gap-2 px-3 py-2">
                <hgroup className="flex flex-col gap-0">
                    <h3 className="font-bold tracking-tight text-base-content group-hover:underline line-clamp-2">
                        {finalTitle}
                    </h3>
                    {finalDescription && (
                        <p className="text-sm tracking-tight text-muted-content line-clamp-2">
                            {finalDescription}
                        </p>
                    )}
                </hgroup>
                <div className="mt-auto text-xs @md/content:pt-2 @md/content:border-t border-base-300/50 font-medium text-muted-content">
                    <span className="font-mono">{hostname}</span>
                </div>
            </div>
            {finalImage && (
                <div className="shrink-0">
                    <div className="size-26 @md/content:h-29 @md/content:aspect-[1.91/1] @md/content:w-auto overflow-hidden rounded-r-2xl bg-base-100">
                        <img
                            src={finalImage}
                            alt={finalTitle}
                            className="h-full w-full object-cover"
                        />
                    </div>
                </div>
            )}
        </a>
    )
}
