'use client'

import { useState } from 'react'
import { explorerPublicApiLinks } from '@/data/explorerOperations'

const footerLinkClass =
  'text-gray-600 dark:text-gray-400 hover:text-primary-600 dark:hover:text-primary-400 transition-colors'

function absoluteApiUrl(href: string): string {
  if (typeof window === 'undefined') return href
  if (href.startsWith('http://') || href.startsWith('https://')) return href
  return `${window.location.origin}${href.startsWith('/') ? href : `/${href}`}`
}

export default function FooterPublicApiLinks({ compact = false }: { compact?: boolean }) {
  const [copiedHref, setCopiedHref] = useState<string | null>(null)

  const copyUrl = async (href: string) => {
    if (typeof navigator === 'undefined' || !navigator.clipboard) return
    try {
      await navigator.clipboard.writeText(absoluteApiUrl(href))
      setCopiedHref(href)
      window.setTimeout(() => setCopiedHref((current) => (current === href ? null : current)), 1500)
    } catch {
      setCopiedHref(null)
    }
  }

  return (
    <ul className={compact ? 'space-y-1.5 text-sm' : 'space-y-3 text-sm'}>
      {explorerPublicApiLinks.map((link) => (
        <li key={link.href}>
          <div className="flex flex-wrap items-center justify-between gap-2">
            <div className="min-w-0 flex-1">
              <a
                className={footerLinkClass}
                href={link.href}
                target="_blank"
                rel="noopener noreferrer"
                title={compact ? link.description : undefined}
              >
                {link.label}
              </a>
              {!compact ? (
                <p className="mt-0.5 text-xs leading-5 text-gray-500 dark:text-gray-500">{link.description}</p>
              ) : null}
            </div>
            <button
              type="button"
              onClick={() => void copyUrl(link.href)}
              className="shrink-0 rounded-lg border border-gray-200 px-2.5 py-1 text-xs font-medium text-gray-700 transition-colors hover:border-primary-300 hover:text-primary-700 dark:border-gray-700 dark:text-gray-200 dark:hover:border-primary-500 dark:hover:text-primary-300"
              aria-label={`Copy URL for ${link.label}`}
            >
              {copiedHref === link.href ? 'Copied' : 'Copy URL'}
            </button>
          </div>
        </li>
      ))}
    </ul>
  )
}
