/* =====================================================================
   PageMaestro (MPg) — Pagina generica de maestros (CRUD)
   Tabla con buscador, boton Nuevo, importacion masiva.
   Render function: recibe (app, props) — props = {title, type, tpl, cols, rr, extra}
   ===================================================================== */

function MPg(app, props) {
  const {
    D, search, setSearch, openNew, openEd, del, filt, tbl,
    showBulk, setShowBulk, bulkText, setBulkText,
    showBulkIns, setShowBulkIns, bulkTextIns, setBulkTextIns,
    showBulkProv, setShowBulkProv, bulkTextProv, setBulkTextProv,
    bulkMsg, setBulkMsg,
    doBulkImport, doBulkImportIns, doBulkImportProv,
  } = app;
  const { title, type, tpl, cols, rr, extra } = props;

  return (
    <div>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 14 }}>
        <h2 style={{ margin: 0, color: "#0a2540", fontFamily: "Georgia,serif" }}>{title}</h2>
        <div style={{ display: "flex", gap: 6, alignItems: "center" }}>
          <input style={{ ...S.inp, width: 220 }} placeholder={"Buscar " + title.toLowerCase() + "..."} value={search} onChange={e => setSearch(e.target.value)} />
          {extra}
          <button style={S.btn} onClick={() => openNew(type, tpl)}><Ic name="plus" size={14} /> Nuevo</button>
        </div>
      </div>
      <div style={S.card}>{tbl(cols, filt(D[type]).map(rr), true)}</div>
      {type === "textiles" && showBulk && (
        <div style={S.card}>
          <h4 style={{ margin: "0 0 6px", color: "#0a2540", fontSize: 12 }}>Importar Textiles (masivo)</h4>
          <p style={{ fontSize: 11, color: "#7c8594", margin: "0 0 6px" }}>16 columnas: Código, Nombre, Proveedor, Composición, Gramaje, Ancho, Unidad, Precio, IVA%, DctoPP%, DctoVol%, VolMín, DíasAbast, Colores, Ref.Prov, Estado — <strong>Guardar como CSV desde Excel</strong></p>
          <div style={{ display: "flex", gap: 6, marginBottom: 6, flexWrap: "wrap" }}>
            <button style={S.btn2} onClick={() => setBulkText("TX-001;Nombre textil;Proveedor;Composición;150;150;Metro;10000;19;5;0;0;5;Colores;Ref;Activo")}><Ic name="download" size={12} /> Ver formato ejemplo</button>
            <label style={{ ...S.btn2, cursor: "pointer", display: "inline-flex", alignItems: "center", gap: 4 }}><Ic name="download" size={12} /> Cargar CSV<input type="file" accept=".csv,.tsv,.txt,.xls" style={{ display: "none" }} onChange={e => { const f = e.target.files[0]; if (!f) return; if (f.name.endsWith(".xlsx")) { setBulkMsg("Archivo .xlsx no soportado. Guárdalo como CSV."); setTimeout(() => setBulkMsg(""), 5000); return; } const reader = new FileReader(); reader.onload = ev => { const txt = ev.target.result.replace(/^\uFEFF/, ""); const lines = txt.split(/\r?\n/).filter(l => l.trim()); setBulkText(lines.slice(1).join("\n")); }; reader.readAsText(f, "utf-8"); e.target.value = ""; }} /></label>
          </div>
          {bulkMsg && <div style={{ background: "#fef2f2", border: "1px solid #fca5a5", borderRadius: 5, padding: "6px 10px", fontSize: 11, color: "#991b1b", marginBottom: 6 }}>{bulkMsg}</div>}
          <textarea style={{ ...S.inp, minHeight: 100, fontFamily: "monospace", fontSize: 11 }} value={bulkText} onChange={e => setBulkText(e.target.value)} placeholder={"TX-010\tDry-Fit Premium\tTextiles del Sur\tMetro\t18500\t5"} />
          <div style={{ display: "flex", gap: 6, marginTop: 6, alignItems: "center" }}>
            <button style={S.btnG} onClick={doBulkImport}><Ic name="check" size={12} /> Importar</button>
            <button style={S.btn2} onClick={() => setShowBulk(false)}>Cancelar</button>
            {bulkText && <span style={{ fontSize: 10, color: "#6b7280" }}>{bulkText.trim().split("\n").length} fila(s)</span>}
          </div>
        </div>
      )}
      {type === "insumos" && showBulkIns && (
        <div style={S.card}>
          <h4 style={{ margin: "0 0 6px", color: "#0a2540", fontSize: 12 }}>Importar Insumos (masivo)</h4>
          <p style={{ fontSize: 11, color: "#7c8594", margin: "0 0 6px" }}>Columnas: Código, Nombre, Categoría, Unidad, Costo, IVA%, Proveedor, Variante — <strong>Guardar como CSV</strong></p>
          <div style={{ display: "flex", gap: 6, marginBottom: 6, flexWrap: "wrap" }}>
            <button style={S.btn2} onClick={() => setBulkTextIns("IN-001;Nombre insumo;Categoría;Unidad;1000;19;Proveedor;Variante")}><Ic name="download" size={12} /> Ver formato ejemplo</button>
            <label style={{ ...S.btn2, cursor: "pointer", display: "inline-flex", alignItems: "center", gap: 4 }}><Ic name="download" size={12} /> Cargar CSV<input type="file" accept=".csv,.tsv,.txt,.xls" style={{ display: "none" }} onChange={e => { const f = e.target.files[0]; if (!f) return; if (f.name.endsWith(".xlsx")) { setBulkMsg("Archivo .xlsx no soportado. Guárdalo como CSV."); setTimeout(() => setBulkMsg(""), 5000); return; } const reader = new FileReader(); reader.onload = ev => { const txt = ev.target.result.replace(/^\uFEFF/, ""); const lines = txt.split(/\r?\n/).filter(l => l.trim()); setBulkTextIns(lines.slice(1).join("\n")); }; reader.readAsText(f, "utf-8"); e.target.value = ""; }} /></label>
          </div>
          {bulkMsg && <div style={{ background: "#fef2f2", border: "1px solid #fca5a5", borderRadius: 5, padding: "6px 10px", fontSize: 11, color: "#991b1b", marginBottom: 6 }}>{bulkMsg}</div>}
          <textarea style={{ ...S.inp, minHeight: 100, fontFamily: "monospace", fontSize: 11 }} value={bulkTextIns} onChange={e => setBulkTextIns(e.target.value)} placeholder={"IN-010\tBotón 4H\tBotones\tInsumos Cali\tUnidad\t250"} />
          <div style={{ display: "flex", gap: 6, marginTop: 6, alignItems: "center" }}>
            <button style={S.btnG} onClick={doBulkImportIns}><Ic name="check" size={12} /> Importar</button>
            <button style={S.btn2} onClick={() => setShowBulkIns(false)}>Cancelar</button>
            {bulkTextIns && <span style={{ fontSize: 10, color: "#6b7280" }}>{bulkTextIns.trim().split("\n").length} fila(s)</span>}
          </div>
        </div>
      )}
      {type === "proveedores" && showBulkProv && (
        <div style={S.card}>
          <h4 style={{ margin: "0 0 6px", color: "#0a2540", fontSize: 12 }}>Importar Proveedores (masivo)</h4>
          <p style={{ fontSize: 11, color: "#7c8594", margin: "0 0 6px" }}>Columnas: Nombre, NIT, Contacto, Dirección, Ciudad, Email, Celular, Tipo — <strong>Guardar como CSV</strong></p>
          <div style={{ display: "flex", gap: 6, marginBottom: 6, flexWrap: "wrap" }}>
            <button style={S.btn2} onClick={() => setBulkTextProv("Textiles del Sur;800111222-3;Carlos Ruiz;Cra 5 # 12-34;Cali;carlos@textiles.com;3151234567;Textil")}><Ic name="download" size={12} /> Ver formato ejemplo</button>
            <label style={{ ...S.btn2, cursor: "pointer", display: "inline-flex", alignItems: "center", gap: 4 }}><Ic name="download" size={12} /> Cargar CSV<input type="file" accept=".csv,.tsv,.txt,.xls" style={{ display: "none" }} onChange={e => { const f = e.target.files[0]; if (!f) return; if (f.name.endsWith(".xlsx")) { setBulkMsg("Archivo .xlsx no soportado. Guárdalo como CSV."); setTimeout(() => setBulkMsg(""), 5000); return; } const reader = new FileReader(); reader.onload = ev => { const txt = ev.target.result.replace(/^\uFEFF/, ""); const lines = txt.split(/\r?\n/).filter(l => l.trim()); setBulkTextProv(lines.slice(1).join("\n")); }; reader.readAsText(f, "utf-8"); e.target.value = ""; }} /></label>
          </div>
          {bulkMsg && <div style={{ background: "#fef2f2", border: "1px solid #fca5a5", borderRadius: 5, padding: "6px 10px", fontSize: 11, color: "#991b1b", marginBottom: 6 }}>{bulkMsg}</div>}
          <textarea style={{ ...S.inp, minHeight: 100, fontFamily: "monospace", fontSize: 11 }} value={bulkTextProv} onChange={e => setBulkTextProv(e.target.value)} placeholder={"Textiles del Sur;800111222;Carlos Ruiz;Cra 5;Cali;carlos@mail.com;3151234567;Textil"} />
          <div style={{ display: "flex", gap: 6, marginTop: 6, alignItems: "center" }}>
            <button style={S.btnG} onClick={doBulkImportProv}><Ic name="check" size={12} /> Importar</button>
            <button style={S.btn2} onClick={() => setShowBulkProv(false)}>Cancelar</button>
            {bulkTextProv && <span style={{ fontSize: 10, color: "#6b7280" }}>{bulkTextProv.trim().split("\n").length} fila(s)</span>}
          </div>
        </div>
      )}
    </div>
  );
}

// ── Exports a global scope (Babel standalone aisla cada <script>) ──
window.MPg         = MPg;
