"use client";
import { useEffect, useRef } from "react";

export default function BarcodeDisplay({ value, height = 50, width = 1.5, displayValue = true, fontSize = 12 }: {
  value: string;
  height?: number;
  width?: number;
  displayValue?: boolean;
  fontSize?: number;
}) {
  const ref = useRef<SVGSVGElement>(null);

  useEffect(() => {
    if (!ref.current || !value) return;
    let mounted = true;
    (async () => {
      const JsBarcode = (await import("jsbarcode")).default;
      if (!mounted || !ref.current) return;
      try {
        JsBarcode(ref.current, value, {
          format: "EAN13",
          height,
          width,
          displayValue,
          fontSize,
          margin: 4,
        });
      } catch {
        // Fallback to CODE128 if EAN13 fails
        try {
          JsBarcode(ref.current, value, {
            format: "CODE128",
            height,
            width,
            displayValue,
            fontSize,
            margin: 4,
          });
        } catch {}
      }
    })();
    return () => { mounted = false; };
  }, [value, height, width, displayValue, fontSize]);

  return <svg ref={ref} className="barcode" />;
}
