// ระบบพิมพ์บาร์โค้ดสินค้า — เลือกจำนวน + ขนาด (เล็ก/กลาง/ใหญ่)
// ใช้ JsBarcode library สำหรับ Code39 มาตรฐาน

const BC_SIZES = {
  s: { label: "เล็ก (40×20 มม)", w: 40, h: 20, name: 6.5, code: 5, sku: 5.5, price: 8, barH: 8, sc: 5 },
  m: { label: "กลาง (50×25 มม)", w: 50, h: 25, name: 7.5, code: 5.5, sku: 6, price: 9.5, barH: 10, sc: 5.5 },
  l: { label: "ใหญ่ (60×30 มม)", w: 60, h: 30, name: 9, code: 6.5, sku: 7, price: 11.5, barH: 13, sc: 6.5 },
};

function BarcodeLabel({ p, size, scale = 1 }) {
  const z = BC_SIZES[size];
  const mm = (v) => `${v * scale}mm`;
  const pt = (v) => `${v * scale}pt`;
  const [bcSrc, setBcSrc] = React.useState("");
  
  React.useEffect(() => {
    if (window.JsBarcode) {
      try {
        const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
        window.JsBarcode(svg, String(p.barcode), {
          format: "CODE39",
          width: 2,
          height: 40,
          margin: 2,
          displayValue: false,
        });
        const xml = new XMLSerializer().serializeToString(svg);
        const dataUrl = "data:image/svg+xml;base64," + btoa(xml);
        setBcSrc(dataUrl);
      } catch (e) { console.error("Barcode error:", e); }
    }
  }, [p.barcode]);

  return (
    <div style={{
      width: mm(z.w), height: mm(z.h), boxSizing: "border-box", padding: mm(1.2),
      display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center",
      gap: mm(0.5), overflow: "hidden", background: "#fff", border: scale > 1 ? "1px dashed #cbd5e1" : "none",
      fontFamily: "'Noto Sans Thai', sans-serif", color: "#000", textAlign: "center",
    }}>
      <div style={{ fontSize: pt(z.name), fontWeight: 700, lineHeight: 1.05, maxHeight: mm(z.h * 0.28), overflow: "hidden", width: "100%" }}>{p.name}</div>
      {bcSrc && <img src={bcSrc} style={{ maxWidth: "100%", height: mm(z.barH), objectFit: "contain" }} />}
      <div style={{ fontSize: pt(z.code), letterSpacing: "1px", fontFamily: "monospace", lineHeight: 1 }}>{p.barcode}</div>
      {p.secretCode && <div style={{ fontSize: pt(z.sc), letterSpacing: "0.5px", fontFamily: "monospace", lineHeight: 1, color: "#666" }}>{p.secretCode}</div>}
      <div style={{ display: "flex", justifyContent: "space-between", width: "100%", alignItems: "baseline", padding: `0 ${mm(0.6)}` }}>
        <span style={{ fontSize: pt(z.sku), fontFamily: "monospace", color: "#333" }}>{p.sku}</span>
        <span style={{ fontSize: pt(z.price), fontWeight: 800 }}>฿{Number(p.price).toLocaleString("th-TH")}</span>
      </div>
    </div>
  );
}

function BarcodePrintModal({ open, onClose, product }) {
  const [qty, setQty] = React.useState(12);
  const [size, setSize] = React.useState("m");
  if (!product) return null;
  const z = BC_SIZES[size];

  const doPrint = () => {
    const n = Math.max(1, Math.min(200, Number(qty) || 1));
    // สร้าง barcode SVG สำหรับการพิมพ์
    const generateBarcodeSvg = () => {
      const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
      if (window.JsBarcode) {
        window.JsBarcode(svg, String(product.barcode), {
          format: "CODE39",
          width: 2,
          height: 40,
          margin: 2,
          displayValue: false,
        });
      }
      const xml = new XMLSerializer().serializeToString(svg);
      return "data:image/svg+xml;base64," + btoa(xml);
    };
    const bcDataUrl = generateBarcodeSvg();
    
    const label = (i) => `
      <div class="lbl">
        <div class="nm">${escapeHtml(product.name)}</div>
        <img src="${bcDataUrl}" class="bars" />
        <div class="bc">${escapeHtml(product.barcode)}</div>
        ${product.secretCode ? `<div class="sc">${escapeHtml(product.secretCode)}</div>` : ""}
        <div class="row"><span class="sku">${escapeHtml(product.sku)}</span><span class="pr">฿${Number(product.price).toLocaleString("th-TH")}</span></div>
      </div>`;
    
    const labels = Array.from({ length: n }, (_, i) => label(i)).join("");
    const w = window.open("", "_blank", "width=700,height=800");
    w.document.write(`<!doctype html><html><head><meta charset="utf-8"><title>พิมพ์บาร์โค้ด ${escapeHtml(product.sku)}</title>
      <link href="https://fonts.googleapis.com/css2?family=Noto+Sans+Thai:wght@400;600;700;800&display=swap" rel="stylesheet">
      <style>
        @page { size: ${z.w}mm ${z.h}mm; margin: 0; }
        * { margin:0; padding:0; box-sizing:border-box; -webkit-print-color-adjust:exact; print-color-adjust:exact; }
        html, body { -webkit-print-color-adjust:exact; print-color-adjust:exact; }
        body { font-family:'Noto Sans Thai',sans-serif; color:#000; }
        .lbl { width:${z.w}mm; height:${z.h}mm; padding:1.2mm; display:flex; flex-direction:column; align-items:center; justify-content:center; gap:0.5mm; overflow:hidden; page-break-after:always; text-align:center; }
        .nm { font-size:${z.name}pt; font-weight:700; line-height:1.05; max-height:${(z.h * 0.3).toFixed(1)}mm; overflow:hidden; width:100%; }
        .bars { max-width:100%; height:${z.barH}mm; object-fit:contain; }
        .bc { font-size:${z.code}pt; letter-spacing:1px; font-family:monospace; line-height:1; }
        .sc { font-size:${z.sc}pt; letter-spacing:0.5px; font-family:monospace; line-height:1; color:#666; }
        .row { display:flex; justify-content:space-between; width:100%; align-items:baseline; padding:0 0.6mm; }
        .sku { font-size:${z.sku}pt; font-family:monospace; color:#333; }
        .pr { font-size:${z.price}pt; font-weight:800; }
        @media screen { body { background:#e2e8f0; padding:14px; display:flex; flex-wrap:wrap; gap:6px; } .lbl { background:#fff; box-shadow:0 1px 4px rgba(0,0,0,.2); } }
      </style></head><body>${labels}
      <script>window.onload=function(){setTimeout(function(){window.print();},350);};<\/script>
      </body></html>`);
    w.document.close();
  };

  return (
    <Modal open={open} onClose={onClose} title="พิมพ์บาร์โค้ดสินค้า" width={460}
      footer={<React.Fragment>
        <Btn kind="ghost" onClick={onClose}>ปิด</Btn>
        <Btn kind="warn" onClick={doPrint}>🖨 พิมพ์ {qty} ดวง</Btn>
      </React.Fragment>}>
      <div style={{ display: "flex", flexDirection: "column", gap: 15 }}>
        <div style={{ display: "flex", justifyContent: "center", padding: "14px 0", background: T.chipBg, borderRadius: 12 }}>
          <BarcodeLabel p={product} size={size} scale={2.4} />
        </div>
        <Field label="ขนาดสติกเกอร์">
          <div style={{ display: "flex", gap: 8 }}>
            {Object.entries(BC_SIZES).map(([k, v]) => (
              <button key={k} className="ss-btn" onClick={() => setSize(k)} style={{
                flex: 1, cursor: "pointer", border: `1.5px solid ${size === k ? T.primary : T.border}`,
                background: size === k ? T.infoBg : "#fff", color: size === k ? T.primary : T.sub,
                borderRadius: 10, padding: "9px 6px", fontWeight: 700, fontSize: 11.5, fontFamily: T.bodyFont, lineHeight: 1.3,
              }}>{v.label}</button>
            ))}
          </div>
        </Field>
        <Field label="จำนวนที่จะพิมพ์ (ดวง)">
          <div style={{ display: "flex", gap: 8, alignItems: "center" }}>
            <NumInput value={qty} min="1" onChange={(e) => setQty(e.target.value)} style={{ width: 110 }} />
            <div style={{ display: "flex", gap: 6 }}>
              {[6, 12, 24, 50].map((n) => <Btn key={n} sm kind="ghost" onClick={() => setQty(n)}>{n}</Btn>)}
            </div>
          </div>
        </Field>
        <div style={{ fontSize: 11.5, color: T.sub, background: T.chipBg, borderRadius: 10, padding: "9px 13px", lineHeight: 1.6 }}>
          แต่ละดวงมี: ชื่อสินค้า · บาร์โค้ด · รหัสสินค้า (SKU) · ราคาขาย<br />
          ระบบจะเปิดหน้าพิมพ์ขนาด {z.w}×{z.h} มม. — เลือกเครื่องพิมพ์สติกเกอร์แล้วสั่งพิมพ์ได้เลย
        </div>
      </div>
    </Modal>
  );
}

function escapeHtml(s) { return String(s).replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" }[c])); }

Object.assign(window, { BarcodePrintModal, BarcodeLabel, BC_SIZES });
