// MostlyQR — free standalone barcode generator at /Barcode (F033, the deferred F001 follow-up).
// A no-login SEO free-tool: type a value, pick EAN-13 or Code 128, get a barcode you can download —
// a funnel into the serialized/dynamic tiers. Uses the shared @mostly-tiny/barcode kit, lazy-loaded
// only on this page (window.MostlyBarcode), so it never weighs on the other marketing pages.
//
// English body copy by design (same as /Compare, /Enterprise, /Verify). IIFE-scoped so no top-level
// name leaks into the shared global scope (see enterprise.jsx).
(function () {
const { Icon: IconBC, MQMark: MQMarkBC, Wordmark: WordmarkBC } = window.MQR;
const { Button: BtnBC } = window.ForgeDesignSystem_e40d74;
const HOME_BC = "/";

let _bcLoad;
function loadBarcodeKit() {
  if (typeof window !== "undefined" && window.MostlyBarcode) return Promise.resolve(window.MostlyBarcode);
  if (_bcLoad) return _bcLoad;
  _bcLoad = new Promise((resolve, reject) => {
    const sc = document.createElement("script");
    sc.src = "/_kit/barcode-kit.js";
    sc.onload = () => resolve(window.MostlyBarcode);
    sc.onerror = () => { _bcLoad = null; reject(new Error("barcode-kit-failed")); };
    document.head.appendChild(sc);
  });
  return _bcLoad;
}

const FORMATS = [
  { id: "code128", label: "Code 128", hint: "Letters, digits & symbols — any text.", placeholder: "MQR-2026-0001" },
  { id: "ean13", label: "EAN-13", hint: "12 digits (a 13th check digit is added).", placeholder: "012345678905" },
];

function BarcodeGen() {
  const [format, setFormat] = React.useState("code128");
  const [data, setData] = React.useState("MQR-2026-0001");
  const [showText, setShowText] = React.useState(true);
  const [ready, setReady] = React.useState(false);
  const [loadErr, setLoadErr] = React.useState("");
  const [svg, setSvg] = React.useState("");
  const [err, setErr] = React.useState("");

  React.useEffect(() => {
    let live = true;
    loadBarcodeKit().then(() => { if (live) setReady(true); }).catch(() => { if (live) setLoadErr("Couldn’t load the barcode engine. Please refresh."); });
    return () => { live = false; };
  }, []);

  // Re-render the barcode whenever inputs change (once the kit is ready).
  React.useEffect(() => {
    if (!ready) return;
    const value = String(data || "").trim();
    if (!value) { setSvg(""); setErr(""); return; }
    try {
      const s = window.MQR.barcodeSVGFor({ data: value, format, showText, fg: "#1d1d1f", bg: "#ffffff", width: 520 });
      setSvg(s); setErr("");
    } catch (e) {
      setSvg(""); setErr(format === "ean13" ? "EAN-13 needs 12–13 digits." : "That value can’t be encoded.");
    }
  }, [ready, data, format, showText]);

  const download = (kind) => {
    if (!svg) return;
    let blob, name;
    if (kind === "svg") { blob = new Blob([svg], { type: "image/svg+xml" }); name = "barcode.svg"; }
    else {
      // Rasterize the SVG → PNG via a canvas.
      const img = new Image();
      const url = "data:image/svg+xml;charset=utf-8," + encodeURIComponent(svg);
      img.onload = () => {
        const cv = document.createElement("canvas"); cv.width = img.width * 2; cv.height = img.height * 2;
        const cx = cv.getContext("2d"); cx.fillStyle = "#fff"; cx.fillRect(0, 0, cv.width, cv.height); cx.drawImage(img, 0, 0, cv.width, cv.height);
        cv.toBlob((b) => { const a = document.createElement("a"); a.href = URL.createObjectURL(b); a.download = "barcode.png"; a.click(); });
      };
      img.src = url; return;
    }
    const a = document.createElement("a"); a.href = URL.createObjectURL(blob); a.download = name; a.click();
  };

  const fmt = FORMATS.find((f) => f.id === format) || FORMATS[0];
  return (
    <div className="mk-root ent-root bc-page">
      <header className="mk-nav ent-nav">
        <div className="mk-wrap mk-nav__inner">
          <a className="mk-brand" href={HOME_BC}><MQMarkBC animate /><WordmarkBC /></a>
          <nav className="mk-nav__links"><a href="/#pricing">Pricing</a><a href="/Enterprise">Enterprise</a></nav>
          <div className="mk-nav__cta" />
        </div>
      </header>

      <section className="bc-hero">
        <div className="mk-wrap bc-hero__inner">
          <span className="mk-eyebrow" style={{ color: "var(--accent)" }}>Free barcode generator</span>
          <h1 className="ent-h1" style={{ color: "var(--fg)", fontSize: 40 }}>Make a barcode in seconds.</h1>
          <p className="mk-lead" style={{ marginInline: "auto" }}>EAN-13 and Code 128, free, no sign-up — download SVG or PNG. Need codes that track scans or verify every unit? That’s <a href="/#pricing">MostlyQR</a>.</p>

          <div className="bc-card">
            <div className="bc-controls">
              <div className="bc-seg">
                {FORMATS.map((f) => (
                  <button key={f.id} type="button" data-on={format === f.id} onClick={() => setFormat(f.id)}>{f.label}</button>
                ))}
              </div>
              <input className="bc-input ent-mono" value={data} placeholder={fmt.placeholder} onChange={(e) => setData(e.target.value)} aria-label="Barcode value" />
              <div className="bc-row">
                <label className="bc-check"><input type="checkbox" checked={showText} onChange={(e) => setShowText(e.target.checked)} /> Show the number</label>
                <span className="bc-hint">{fmt.hint}</span>
              </div>
            </div>

            <div className="bc-preview">
              {!ready && !loadErr && <div className="vf-loading"><span className="vf-spinner" /> Loading…</div>}
              {loadErr && <div className="vf-scanerr">{loadErr}</div>}
              {ready && svg && <div className="bc-svgwrap" dangerouslySetInnerHTML={{ __html: svg }} />}
              {ready && !svg && err && <div className="bc-err">{err}</div>}
              {ready && svg && (
                <div className="bc-actions">
                  <BtnBC variant="primary" iconRight={<IconBC name="download" size={15} />} onClick={() => download("png")}>Download PNG</BtnBC>
                  <BtnBC variant="secondary" onClick={() => download("svg")}>SVG</BtnBC>
                </div>
              )}
            </div>
          </div>
          <p className="vf-foot"><IconBC name="shield" size={14} sw={2.2} /> Generated in your browser · free · no watermark.</p>
        </div>
      </section>
      <window.MQRFooter />
    </div>
  );
}

window.MQRBarcodeGen = BarcodeGen;
})();
