/* Reusable <Asin> — click to copy to clipboard with toast feedback */

const Asin = ({ value, size = 11, prefix = null }) => {
  const toast = useToast ? useToast() : null;
  const [copied, setCopied] = useState(false);

  const copy = async (e) => {
    e.stopPropagation();
    if (!value) return;
    try {
      await navigator.clipboard.writeText(value);
      setCopied(true);
      if (toast) toast({ message: `ASIN ${value} copié`, tone: "green" });
      setTimeout(() => setCopied(false), 1200);
    } catch (_) {
      // Fallback for older browsers / restricted contexts
      const ta = document.createElement("textarea");
      ta.value = value;
      ta.style.position = "fixed";
      ta.style.opacity = "0";
      document.body.appendChild(ta);
      ta.select();
      try { document.execCommand("copy"); setCopied(true); if (toast) toast({ message: `ASIN ${value} copié`, tone: "green" }); }
      catch (_) { if (toast) toast({ message: "Copie impossible", tone: "red" }); }
      document.body.removeChild(ta);
      setTimeout(() => setCopied(false), 1200);
    }
  };

  return (
    <button
      onClick={copy}
      title={`Cliquer pour copier · ${value}`}
      className="mono"
      style={{
        display: "inline-flex", alignItems: "center", gap: 4,
        padding: "2px 6px", border: 0, borderRadius: 4,
        background: copied ? "var(--green-soft)" : "transparent",
        color: copied ? "var(--green)" : "var(--text-dim)",
        fontSize: size, cursor: "pointer",
        transition: "background 120ms, color 120ms",
        fontFamily: "var(--font-mono)",
      }}
      onMouseEnter={(e) => { if (!copied) e.currentTarget.style.background = "var(--bg-3)"; }}
      onMouseLeave={(e) => { if (!copied) e.currentTarget.style.background = "transparent"; }}
    >
      {prefix}
      <span>{value}</span>
      <Icon name={copied ? "check" : "copy"} size={size - 1} style={{ opacity: 0.6 }} />
    </button>
  );
};

window.Asin = Asin;
