import { useLinkPreview } from '../lib/useLinkPreview';

interface Props {
  url: string;
}

// Renders a compact OpenGraph preview card under a message bubble. Fetches
// lazily through the edge function; silent when the URL returned no meta.
export function LinkPreviewCard({ url }: Props) {
  const preview = useLinkPreview(url);
  if (!preview || !preview.ok) return null;
  if (!preview.title && !preview.description && !preview.imageUrl) return null;

  return (
    <a
      href={url}
      target="_blank"
      rel="noreferrer noopener"
      className="mt-2 flex max-w-[320px] overflow-hidden rounded-lg border border-line bg-surface-2 text-sm no-underline transition hover:bg-surface-3"
    >
      {preview.imageUrl && (
        <img
          src={preview.imageUrl}
          alt=""
          loading="lazy"
          className="h-20 w-20 shrink-0 object-cover"
          onError={(e) => {
            (e.currentTarget as HTMLImageElement).style.display = 'none';
          }}
        />
      )}
      <div className="flex min-w-0 flex-1 flex-col justify-center gap-0.5 p-2.5">
        {preview.siteName && (
          <p className="truncate text-[10px] uppercase tracking-wider text-fg-muted">
            {preview.siteName}
          </p>
        )}
        {preview.title && (
          <p className="line-clamp-2 text-sm font-semibold text-fg">
            {preview.title}
          </p>
        )}
        {preview.description && (
          <p className="line-clamp-2 text-xs text-fg-muted">{preview.description}</p>
        )}
      </div>
    </a>
  );
}
