"use client";

import { Copy } from "lucide-react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { useT } from "@/i18n";

/**
 * A value on screen with a button to copy it.
 *
 * Always left-to-right, even in Arabic: these are URLs and keys, and a bidi algorithm reordering
 * the punctuation of a secret is a way to copy it wrong without noticing.
 */
export function CopyField({ label, value }: { label?: string; value: string }) {
  const t = useT();

  async function copy() {
    try {
      await navigator.clipboard.writeText(value);
      toast.success(t("portal.integration.copied"));
    } catch {
      // Clipboard access can be refused (insecure origin, permissions). The value is on screen.
      toast.error(t("portal.integration.copyFailed"));
    }
  }

  return (
    <div className="space-y-1.5">
      {label ? <p className="text-xs font-medium text-muted-foreground">{label}</p> : null}
      <div className="flex items-center gap-2">
        <code
          dir="ltr"
          className="min-w-0 flex-1 select-all overflow-x-auto whitespace-nowrap rounded-md bg-muted px-3 py-2 text-start text-xs"
        >
          {value}
        </code>
        <Button type="button" size="sm" variant="outline" onClick={() => void copy()}>
          <Copy aria-hidden />
          {t("portal.integration.copy")}
        </Button>
      </div>
    </div>
  );
}
