// ===== Código de barras Code 128 + impresión de etiquetas de SKU =====
// Genera barcodes Code 128 (subconjunto B, alfanumérico) sin librerías externas.
// Pensado para etiquetas térmicas de 2x1" (estándar) o 1.5x1".

const C128_PATTERNS = [
  "212222","222122","222221","121223","121322","131222","122213","122312","132212","221213",
  "221312","231212","112232","122132","122231","113222","123122","123221","223211","221132",
  "221231","213212","223112","312131","311222","321122","321221","312212","322112","322211",
  "212123","212321","232121","111323","131123","131321","112313","132113","132311","211313",
  "231113","231311","112133","112331","132131","113123","113321","133121","313121","211331",
  "231131","213113","213311","213131","311123","311321","331121","312113","312311","332111",
  "314111","221411","431111","111224","111422","121124","121421","141122","141221","112214",
  "112412","122114","122411","142112","142211","241211","221114","413111","241112","134111",
  "111242","121142","121241","114212","124112","124211","411212","421112","421211","212141",
  "214121","412121","111143","111341","131141","114113","114311","411113","411311","113141",
  "114131","311141","411131","211412","211214","211232","2331112"
];

// Devuelve la secuencia de módulos (string de anchos) para Code 128B.
function code128bModules(data){
  const START_B = 104, STOP = 106;
  const clean = String(data).replace(/[^\x20-\x7E]/g, "").slice(0, 40) || " ";
  const codes = [START_B];
  let sum = START_B;
  for(let i=0;i<clean.length;i++){
    const v = clean.charCodeAt(i) - 32;
    codes.push(v); sum += v * (i+1);
  }
  codes.push(sum % 103);
  codes.push(STOP);
  return codes.map(c => C128_PATTERNS[c]).join("");
}

// SVG (string) del código de barras. Negro sobre transparente; escala con preserveAspectRatio.
function barcodeSVG(data, { height = 56, quiet = 10 } = {}){
  const mods = code128bModules(data);
  const total = mods.split("").reduce((s,d)=>s+(+d),0) + quiet*2;
  let x = quiet, bar = true, rects = "";
  for(const d of mods){
    const w = +d;
    if(bar) rects += `<rect x="${x}" y="0" width="${w}" height="${height}" fill="#000"/>`;
    x += w; bar = !bar;
  }
  return `<svg viewBox="0 0 ${total} ${height}" preserveAspectRatio="none" xmlns="http://www.w3.org/2000/svg" style="width:100%;height:${height}px;display:block">${rects}</svg>`;
}

// Componente React para previsualizar el barcode.
function Barcode({ value, height = 56 }){
  return <div style={{ width:"100%" }} dangerouslySetInnerHTML={{ __html: barcodeSVG(value, { height }) }} />;
}

// HTML de una etiqueta individual (se repite por copia).
function labelHTML(item, { w, h, showName, showPrice }){
  const sku = (item.sku||"").toUpperCase();
  const padIn = 0.06;
  const name = showName && item.name ? `<div class="lname">${escapeHTML(item.name)}</div>` : "";
  const price = showPrice && item.price>0 ? `<div class="lprice">${fmtMoney(item.price)}</div>` : "";
  return `<div class="label">
    <div class="ltop">${name}${price}</div>
    <div class="lbar">${barcodeSVG(sku, { height: 60 })}</div>
    <div class="lsku">${escapeHTML(sku)}</div>
  </div>`;
}
function escapeHTML(s){ return String(s).replace(/[&<>"]/g, c=>({ "&":"&amp;","<":"&lt;",">":"&gt;","\"":"&quot;" }[c])); }

// Imprime N etiquetas usando un iframe oculto con @page del tamaño exacto.
function printLabels(items, { copies = 1, w = 2, h = 1, showName = true, showPrice = false } = {}){
  const labels = [];
  items.forEach(it => { for(let i=0;i<copies;i++) labels.push(labelHTML(it, { w, h, showName, showPrice })); });
  const css = `
    @page { size: ${w}in ${h}in; margin: 0; }
    * { margin:0; padding:0; box-sizing:border-box; -webkit-print-color-adjust:exact; print-color-adjust:exact; }
    body { font-family: ui-sans-serif, system-ui, -apple-system, Arial, sans-serif; }
    .label { width:${w}in; height:${h}in; padding:0.06in 0.08in; display:flex; flex-direction:column;
      justify-content:center; align-items:center; gap:0.02in; page-break-after:always; overflow:hidden; }
    .label:last-child { page-break-after:auto; }
    .ltop { width:100%; display:flex; align-items:baseline; justify-content:center; gap:6px; }
    .lname { font-size:8.5pt; font-weight:700; line-height:1.05; text-align:center; max-height:0.22in; overflow:hidden;
      display:-webkit-box; -webkit-line-clamp:2; -webkit-box-orient:vertical; }
    .lprice { font-size:9pt; font-weight:800; white-space:nowrap; }
    .lbar { width:100%; flex:1; display:flex; align-items:center; min-height:0; }
    .lbar svg { width:100%; height:auto !important; max-height:0.42in; }
    .lsku { font-family: ui-monospace, "SF Mono", Menlo, monospace; font-size:8pt; font-weight:700; let-spacing:0.04em; }
  `;
  const html = `<!DOCTYPE html><html><head><meta charset="utf-8"><style>${css}</style></head><body>${labels.join("")}</body></html>`;
  const ifr = document.createElement("iframe");
  ifr.style.cssText = "position:fixed;right:0;bottom:0;width:0;height:0;border:0;opacity:0;";
  document.body.appendChild(ifr);
  ifr.srcdoc = html;
  ifr.onload = () => {
    try { ifr.contentWindow.focus(); ifr.contentWindow.print(); }
    catch(e){ console.warn("print label", e); }
    setTimeout(()=>{ try{ document.body.removeChild(ifr); }catch(e){} }, 1200);
  };
}

// Modal para configurar e imprimir la etiqueta de un artículo.
function LabelModal({ item, onClose }){
  const [copies, setCopies] = React.useState(1);
  const [size, setSize] = React.useState("2x1");
  const [showName, setShowName] = React.useState(true);
  const [showPrice, setShowPrice] = React.useState(item.price>0);
  const dims = size==="2x1" ? { w:2, h:1 } : { w:1.5, h:1 };

  function print(){ printLabels([item], { copies:+copies||1, ...dims, showName, showPrice }); }

  const sku = (item.sku||"").toUpperCase();
  return (
    <ModalShell title="Imprimir etiqueta de código de barras" onClose={onClose} maxWidth={460}>
      <div style={{ padding:"20px 22px", display:"flex", flexDirection:"column", gap:18 }}>
        {/* preview */}
        <div style={{ display:"flex", justifyContent:"center" }}>
          <div style={{ width:240, height:120, border:"1px dashed var(--line)", borderRadius:8, background:"#fff",
            padding:"8px 10px", display:"flex", flexDirection:"column", alignItems:"center", justifyContent:"center", gap:3 }}>
            <div style={{ display:"flex", alignItems:"baseline", gap:8, width:"100%", justifyContent:"center" }}>
              {showName && <div style={{ fontSize:11, fontWeight:700, color:"#111", textAlign:"center", lineHeight:1.05,
                overflow:"hidden", display:"-webkit-box", WebkitLineClamp:2, WebkitBoxOrient:"vertical" }}>{item.name}</div>}
              {showPrice && item.price>0 && <div style={{ fontSize:12, fontWeight:800, color:"#111", whiteSpace:"nowrap" }}>{fmtMoney(item.price)}</div>}
            </div>
            <div style={{ width:"90%" }}><Barcode value={sku} height={42} /></div>
            <div style={{ fontFamily:"var(--mono)", fontSize:11, fontWeight:700, color:"#111", letterSpacing:"0.04em" }}>{sku}</div>
          </div>
        </div>

        <div style={{ display:"grid", gridTemplateColumns:"1fr 1fr", gap:14 }}>
          <Field label="Tamaño de etiqueta">
            <div style={{ display:"flex", gap:8 }}>
              {[["2x1",'2" × 1"'],["1.5x1",'1.5" × 1"']].map(([v,l])=>(
                <button key={v} onClick={()=>setSize(v)} style={{ flex:1, padding:"9px 6px", borderRadius:9, fontSize:12.5, fontWeight:600, cursor:"pointer",
                  border:`1px solid ${size===v?"var(--accent)":"var(--line)"}`, background:size===v?"var(--accent-soft)":"var(--surface)", color:size===v?"var(--accent-ink)":"var(--ink-2)" }}>{l}</button>
              ))}
            </div>
          </Field>
          <Field label="Cantidad de copias">
            <TextInput type="number" min="1" max="100" value={copies} onChange={e=>setCopies(e.target.value)} style={{ fontFamily:"var(--mono)" }} />
          </Field>
        </div>

        <div style={{ display:"flex", gap:18 }}>
          <label style={{ display:"flex", alignItems:"center", gap:8, fontSize:13, fontWeight:600, color:"var(--ink-2)", cursor:"pointer" }}>
            <input type="checkbox" checked={showName} onChange={e=>setShowName(e.target.checked)} style={{ accentColor:"var(--accent)", width:15, height:15 }} /> Mostrar nombre
          </label>
          <label style={{ display:"flex", alignItems:"center", gap:8, fontSize:13, fontWeight:600, color:"var(--ink-2)", cursor:"pointer" }}>
            <input type="checkbox" checked={showPrice} onChange={e=>setShowPrice(e.target.checked)} style={{ accentColor:"var(--accent)", width:15, height:15 }} /> Mostrar precio
          </label>
        </div>
      </div>
      <div style={{ display:"flex", alignItems:"center", gap:10, padding:"16px 22px", borderTop:"1px solid var(--line)", justifyContent:"flex-end" }}>
        <Btn variant="secondary" onClick={onClose}>Cancelar</Btn>
        <Btn icon="print" onClick={print}>Imprimir {(+copies||1)>1?`(${copies})`:""}</Btn>
      </div>
    </ModalShell>
  );
}

Object.assign(window, { Barcode, barcodeSVG, code128bModules, printLabels, LabelModal });
