/* =====================================================================
   PageUsuarios (PgUsuarios) — Gestion de usuarios y roles
   Render function: recibe `app` con state/setters/helpers de App
   ===================================================================== */

function PgUsuarios(app) {
  const { D, setD, search, setSearch, eu, setEu, nu, setNu, session, setSaved } = app;

  const saveUser = (user) => {
    if (user.id) {
      setD(d => ({ ...d, usuarios: d.usuarios.map(u => u.id === user.id ? user : u) }));
    } else {
      const id = nid(D.usuarios || []);
      setD(d => ({ ...d, usuarios: [...d.usuarios, { ...user, id, fechaCreacion: hoy() }] }));
    }
    setEu(null); setNu(null);
    setSaved("✓ Usuario guardado");
    setTimeout(() => setSaved(""), 3000);
  };

  const form = eu || nu;
  const sU = search.trim().toLowerCase();
  const usuarios = (D.usuarios || []).filter(u => {
    if (!sU) return true;
    const hay = [u.nombre, u.correo, u.area, u.estado, Permissions.label(u.nivel)].filter(Boolean).join(" ").toLowerCase();
    return hay.includes(sU);
  });

  return (
    <div>
      <div style={{ display:"flex", justifyContent:"space-between", alignItems:"center", marginBottom:14 }}>
        <h2 style={{ margin:0, color:"#0a2540", fontFamily:"Georgia,serif" }}>Usuarios y roles</h2>
        <button style={S.btn} onClick={() => setNu({ nombre:"", correo:"", clave:"", nivel:1, verCostos:false, area:"", estado:"activo" })}>
          <Ic name="plus" size={14} /> Nuevo usuario
        </button>
      </div>
      <div style={{ display:"flex", gap:8, alignItems:"center", flexWrap:"wrap", marginBottom:12, padding:"8px 10px", background:"#faf9f7", border:"1px solid #e5e1d8", borderRadius:6 }}>
        <input style={{ ...S.inp, width:260 }} placeholder="Buscar por nombre, correo, área..." value={search} onChange={e => setSearch(e.target.value)} />
        {search && <button style={S.btn2} onClick={() => setSearch("")}>Limpiar</button>}
        <span style={{ marginLeft:"auto", fontSize:11, color:"#6b7280" }}>{usuarios.length} de {(D.usuarios || []).length}</span>
      </div>
      <div style={S.card}>
        <table style={{ width:"100%", borderCollapse:"collapse" }}>
          <thead><tr><th style={S.th}>Nombre</th><th style={S.th}>Correo</th><th style={S.th}>Rol</th><th style={S.th}>Área</th><th style={S.th}>Estado</th><th style={S.th}></th></tr></thead>
          <tbody>
            {usuarios.map(u => (
              <tr key={u.id}>
                <td style={S.td}><strong>{u.nombre}</strong>{session && session.id === u.id && <span style={{ marginLeft:6, fontSize:9, padding:"1px 5px", borderRadius:3, background:"#dbeafe", color:"#1e40af" }}>Tú</span>}</td>
                <td style={S.td}>{u.correo}</td>
                <td style={S.td}><span style={{ padding:"2px 8px", borderRadius:4, fontSize:10, fontWeight:700, background: u.nivel >= 3 ? "#fee2e2" : u.nivel >= 2 ? "#dbeafe" : "#f3f4f6", color: Permissions.color(u.nivel) }}>{Permissions.label(u.nivel)}</span></td>
                <td style={S.td}>{u.area || "—"}</td>
                <td style={S.td}><span style={{ color: u.estado === "activo" ? "#065f46" : "#b91c1c", fontSize:11, fontWeight:600 }}>{u.estado}</span></td>
                <td style={S.td}><button style={S.btn2} onClick={() => setEu({ ...u })}><Ic name="edit" size={12} /></button></td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
      {form && (
        <div style={S.modal} onMouseDown={e => { if (e.target === e.currentTarget) { setEu(null); setNu(null); } }}>
          <div style={{ ...S.mc, maxWidth:480 }} onMouseDown={e => e.stopPropagation()}>
            <div style={{ display:"flex", justifyContent:"space-between", alignItems:"center", marginBottom:14 }}>
              <h3 style={{ margin:0, color:"#0a2540", fontFamily:"Georgia,serif", fontSize:16 }}>{form.id ? "Editar" : "Nuevo"} usuario</h3>
              <button style={S.btn} onClick={() => saveUser(form)}><Ic name="check" size={13} /> Guardar</button>
            </div>
            <div style={S.g2}>
              <F l="Nombre completo"><input style={S.inp} value={form.nombre} onChange={e => { const v = e.target.value; eu ? setEu({ ...eu, nombre:v }) : setNu({ ...nu, nombre:v }); }} /></F>
              <F l="Correo"><input style={S.inp} type="email" value={form.correo} onChange={e => { const v = e.target.value; eu ? setEu({ ...eu, correo:v }) : setNu({ ...nu, correo:v }); }} /></F>
            </div>
            <div style={{ ...S.g3, marginTop:6 }}>
              <F l="Contraseña"><input style={S.inp} type="text" value={form.clave} onChange={e => { const v = e.target.value; eu ? setEu({ ...eu, clave:v }) : setNu({ ...nu, clave:v }); }} /></F>
              <F l="Rol"><select style={S.sel} value={form.nivel} onChange={e => { const v = parseInt(e.target.value); eu ? setEu({ ...eu, nivel:v }) : setNu({ ...nu, nivel:v }); }}>
                <option value={1}>Viewer (solo lectura)</option>
                <option value={2}>Editor (crear/editar)</option>
                <option value={3}>Admin (todo)</option>
              </select></F>
              <F l="Área"><input style={S.inp} value={form.area || ""} onChange={e => { const v = e.target.value; eu ? setEu({ ...eu, area:v }) : setNu({ ...nu, area:v }); }} placeholder="Gerencia, Operaciones..." /></F>
            </div>
            <div style={{ ...S.g2, marginTop:6 }}>
              <F l="Estado"><select style={S.sel} value={form.estado} onChange={e => { const v = e.target.value; eu ? setEu({ ...eu, estado:v }) : setNu({ ...nu, estado:v }); }}>
                <option value="activo">Activo</option>
                <option value="inactivo">Inactivo</option>
              </select></F>
              <F l="Ver costos/margen"><select style={S.sel} value={form.verCostos ? "si" : "no"} onChange={e => { const v = e.target.value === "si"; eu ? setEu({ ...eu, verCostos:v }) : setNu({ ...nu, verCostos:v }); }}>
                <option value="no">No</option>
                <option value="si">Sí</option>
              </select></F>
            </div>
            {form.nivel < 3 && <div style={{ marginTop:8, padding:"8px 10px", background:"#f0fdf4", borderRadius:5, fontSize:10, color:"#065f46", border:"1px solid #bbf7d0" }}>
              {form.nivel === 2 ? "Editor: puede crear, editar, exportar, importar masivos. NO puede ver costos (salvo flag), configuración ni gestionar usuarios." : "Viewer: solo lectura. No puede crear, editar ni eliminar nada."}
            </div>}
          </div>
        </div>
      )}
    </div>
  );
}

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