import { ExternalLink } from "lucide-react";
import { truncateLink } from "@/lib/format";
import { ordersTexts } from "@/lib/i18n/orders";

function isHttpLink(link: string): boolean {
  return /^https?:\/\//i.test(link);
}

/** Truncated link with the full value in the native tooltip + external-link icon. */
export function LinkCell({ link, max = 34 }: { link: string | null; max?: number }) {
  if (!link) {
    return <span className="text-muted-foreground">{ordersTexts.noLink}</span>;
  }

  const label = truncateLink(link, max);

  if (!isHttpLink(link)) {
    return (
      <span title={link} className="text-foreground/90">
        {label}
      </span>
    );
  }

  return (
    <a
      href={link}
      target="_blank"
      rel="noopener noreferrer nofollow"
      title={link}
      aria-label={ordersTexts.openLink}
      className="inline-flex max-w-[16rem] items-center gap-1.5 text-foreground/90 underline-offset-4 transition-colors hover:text-primary hover:underline"
    >
      <span className="truncate">{label}</span>
      <ExternalLink className="size-3 shrink-0 opacity-60" />
    </a>
  );
}

export default LinkCell;
