import { useState } from 'react'
import { Link } from 'react-router'
import { RssIcon } from '@heroicons/react/24/outline'

interface Props {
  pub: { atUri: string; name: string; url: string; description?: string; authorHandle?: string }
  action?: React.ReactNode
}

export default function PublicationCard({ pub, action }: Props) {
  const [copied, setCopied] = useState(false)
  const isSameOrigin = new URL(pub.url).origin === window.location.origin

  async function handleCopyFeed() {
    const feedUrl = `${pub.url.replace(/\/$/, '')}/feed.xml`
    try {
      await navigator.clipboard.writeText(feedUrl)
      setCopied(true)
      setTimeout(() => setCopied(false), 2500)
    } catch { /* ignore */ }
  }

  return (
    <li className="flex items-center justify-between gap-4 rounded-lg border border-stone-200 dark:border-stone-700/80 px-4 py-3 bg-white dark:bg-stone-900/40">
      <div className="min-w-0">
        {isSameOrigin ? (
          <Link to={new URL(pub.url).pathname} className="text-sm font-medium text-stone-900 dark:text-white truncate hover:underline">{pub.name}</Link>
        ) : (
          <a href={pub.url} target="_blank" rel="noopener noreferrer" className="text-sm font-medium text-stone-900 dark:text-white truncate hover:underline">{pub.name}</a>
        )}
        <p className="text-sm text-stone-500 dark:text-stone-400 truncate mt-0.5">
          {new URL(pub.url).host}{pub.authorHandle && ` · @${pub.authorHandle}`}
        </p>
        {pub.description && (
          <p className="text-sm text-stone-500 dark:text-stone-400 truncate mt-0.5">{pub.description}</p>
        )}
        {copied && (
          <p className="text-xs text-green-600 dark:text-green-400 mt-1">
            Feed URL copied — paste into your RSS reader
          </p>
        )}
      </div>
      <div className="shrink-0 flex items-center gap-2">
        {isSameOrigin && (
          <button
            onClick={handleCopyFeed}
            title="Copy Atom feed URL"
            className="p-1.5 rounded-md text-stone-400 dark:text-stone-500 hover:text-orange-500 dark:hover:text-orange-400 hover:bg-stone-100 dark:hover:bg-stone-800 transition-colors"
          >
            <RssIcon className="h-4 w-4" />
          </button>
        )}
        {action}
      </div>
    </li>
  )
}
